Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Valve cluster: refactor to make unit-testable #35631

Draft
wants to merge 35 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
6f3357b
Valve: disco ball - Attribute getters
cecille Sep 6, 2024
1ab57bb
Valve: Disco ball - Attribute Setters for client
cecille Sep 8, 2024
6d4c366
Valve: Disco ball - Open command
cecille Sep 8, 2024
30e6fd1
Valve: Disco ball - start of Remaining duration with Q
cecille Sep 11, 2024
02906e1
Valve: Disco ball - Handle automatic close
cecille Sep 15, 2024
8bf5e5a
Valve: disco ball - Handle close command
cecille Sep 16, 2024
2e4f0ff
Valve: Disco ball - Access and command interfaces
cecille Sep 16, 2024
83d5b79
Valve: Disco ball - add example app
cecille Sep 17, 2024
100a967
Add endpoint marker to print
cecille Sep 19, 2024
52449a3
add feature map and cluster revision
cecille Sep 26, 2024
9e6b521
Merge remote-tracking branch 'upstream/master' into valve
cecille Sep 27, 2024
58cfb19
Fix conformance
cecille Sep 27, 2024
6be91cd
Add taglists to distinguish endpoints
cecille Sep 27, 2024
bc8f3d4
Use Node label instead of tags
cecille Sep 29, 2024
ab2b7bd
Valve: fix write to use KVS manager properly
cecille Sep 28, 2024
0712293
TC-DESC-2.2: Fix comparison when mfg label is in the list
cecille Sep 28, 2024
2710453
TC-VALCC-3.1: Allow immediate open of valve
cecille Sep 28, 2024
e0195d7
TC-VALCC-4.2: unconditionally write open duration
cecille Sep 28, 2024
eb2dcbf
VALCC: Remove top-level PICS
cecille Sep 28, 2024
3e30568
controller start: not done or tested
cecille Sep 30, 2024
b994417
controller now tested
cecille Sep 30, 2024
f01c8f5
Add readme and additional functions for controller
cecille Oct 1, 2024
84a0899
valve: Set target state to transitioning first
cecille Oct 4, 2024
bdadfb0
fixup for 3.1 test
cecille Oct 4, 2024
847a8d7
another fixup for 3.1
cecille Oct 7, 2024
8d1491e
Add close at start of test
cecille Oct 7, 2024
31ed684
Fix tests to account for unconditional change to target and current a…
cecille Oct 9, 2024
1a1d5c6
Add a mystery option to the controller
cecille Oct 15, 2024
03c8e98
Merge remote-tracking branch 'upstream/master' into valve
cecille Jan 7, 2025
6e354ba
Fix build file from bad merge
cecille Jan 7, 2025
b95be0a
python framework: Fix warning on asyncio not awaited
cecille Dec 19, 2024
82e67de
Uncomment the attribute access interface registration - whoops
cecille Jan 7, 2025
e3a9b43
fix up some tests
cecille Jan 8, 2025
90e41f5
Merge remote-tracking branch 'upstream/master' into valve
cecille Jan 9, 2025
a0c0737
Merge remote-tracking branch 'origin/valve' into valve_rebased
cecille Jan 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions examples/valve/controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Running the drinks machine app and controller

To run this example matter application, you need a version of the example app
and a controller. The example app can be compiled with gn / ninja, the
controller functions can be used through the chip-repl python shell

## App

### Compiling the app on linux

From the root of the chip tree

```
cd examples/valve/linux
gn gen out/debug
ninja -C out/debug
```

### Running the app on linux

From the root of the chip tree

```
./examples/valve/linux/out/debug/valve-app --KVS /tmp/valve_kvs.json
```

The KVS file is where the commissioning data is stored for the app, so be sure
to start the app with the same kvs file if you do not want to re-commission it
every time. All the standard linux app flags also work for this app. Use --help
to see the available options.

## Controller

### Compiling the chip-repl

To compile the chip-repl, from the root of the chip tree:

```
. scripts/activate.sh
./scripts/build_python.sh -i out/pyenv
source out/pyenv/activate
out/pyenv/bin/chip-repl
```

The chip-repl is a shell that lets you directly call python functions. It
instantiates a controller object that can be used to communicate with devices.
The controller is called devCtrl. By default, its KVS is at
/tmp/repl-storage.json, but this can be changed on the command line if desired.
Use --help to see options.

### Commissioning the valve app

As long as the controller and the application KVSs are kept constant, the app
should only need to be commissioned once.

To commission the device use:

```
from chip import ChipDeviceCtrl
await devCtrl.CommissionOnNetwork(nodeId=1, setupPinCode=20202021, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=3840)
```

### Interacting with the valve app

To create a drinks machine controller:

```
import examples.valve.controller as DrinksController
dm = DrinksController.DrinkMachine(devCtrl, 1)
```

You can now call functions on the drinks machine controller. Tab completion will
work within the repl, so you can see the available options.
146 changes: 146 additions & 0 deletions examples/valve/controller/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import random

from enum import StrEnum
from chip import ChipDeviceCtrl
from chip.clusters.Types import NullValue
import chip.clusters as Clusters


MYSTERY_DRINK = "mystery mirrorball"


class Bottle(StrEnum):
kBourbon = "bourbon"
kGin = "gin"
kCampari = "campari"
kVermouth = "vermouth"
kSourMix = "sour mix"
kSimpleSyrup = "simple syrup",


class Oz:
def __init__(self, oz: float):
self.oz = oz

def time(self):
# One oz == approx 12s.
return self.oz * 12

def __eq__(self, other):
return self.oz == other.oz

def __lt__(self, other):
return self.oz < other.oz


class DrinkMachine:
def __init__(self, devCtrl: ChipDeviceCtrl, node_id: int):
self.dev_ctrl = devCtrl
self.node_id = node_id
# TODO: Should this actually be modelled as an aggregator with bridged nodes so I can have a NodeLabel?
# Right now I'm going to leave this as something on the app side because it's a demo, but it's weird that we don't have writeable labels unless you model it strangely. Spec issue?
self.bottles: dict[Bottle, int] = {Bottle.kBourbon: 1, Bottle.kGin: 2,
Bottle.kCampari: 3, Bottle.kVermouth: 4, Bottle.kSourMix: 5, Bottle.kSimpleSyrup: 6}
self.recipes: dict[str, dict[Bottle, Oz]] = {}
self.add_recipe("negroni", {Bottle.kGin: Oz(1.5), Bottle.kCampari: Oz(1.5), Bottle.kVermouth: Oz(1.5)})
self.add_recipe("boulevardier", {Bottle.kBourbon: Oz(1.5), Bottle.kCampari: Oz(1.5), Bottle.kVermouth: Oz(1.5)})
self.add_recipe("bourbon sour", {Bottle.kBourbon: Oz(2), Bottle.kSourMix: Oz(1), Bottle.kSimpleSyrup: Oz(1.5)})
self.add_recipe("martini", {Bottle.kGin: Oz(2), Bottle.kVermouth: Oz(0.25)})
self.add_recipe("gimlet", {Bottle.kGin: Oz(2.5), Bottle.kSourMix: Oz(0.5), Bottle.kSimpleSyrup: Oz(0.5)})
self.add_recipe("old fashioned", {Bottle.kBourbon: Oz(2), Bottle.kSimpleSyrup: Oz(0.125)})
self.add_recipe("shot of bourbon", {Bottle.kBourbon: Oz(1.5)})
self.add_recipe("shot of gin", {Bottle.kGin: Oz(1.5)})
self.add_recipe("gin sour", {Bottle.kGin: Oz(2), Bottle.kSourMix: Oz(1), Bottle.kSimpleSyrup: Oz(0.5)})
self.add_recipe("manhattan", {Bottle.kBourbon: Oz(2), Bottle.kVermouth: Oz(1)})
self.add_recipe("campari sour", {Bottle.kGin: Oz(1), Bottle.kCampari: Oz(1),
Bottle.kSourMix: Oz(0.75), Bottle.kSimpleSyrup: Oz(0.5)})
self.add_recipe(MYSTERY_DRINK, {})

def set_bottle_names(self, bottles: dict[Bottle, int]) -> bool:
''' Bottle is a dict of bottle name to endpoint and should contain all 6 endpoints at once'''
if len(bottles) != 6:
return False
self.bottles = bottles

def get_bottle_names(self):
return self.bottles

def get_recipes(self):
return self.recipes

def add_recipe(self, name: str, ingredients: dict[Bottle, Oz]):
# TODO: should store somewhere permanent - simplest is to write out to file. In the meanwhile, we have a few pre-populated
self.recipes[name] = ingredients

async def _dispense_mystery(self):
num_ingredients = random.randint(1, 3)
bottles = set()
choice = random.choice(list(Bottle))
bottles.add(choice)
while len(bottles) < num_ingredients:
# If this matches something in the bottle list already, it won't be added
choice = random.choice(list(Bottle))
bottles.add(choice)

# we're going to aim for a 2.5 Oz shot with min 0.5 shot sizes
goal = 2.5
print(f"Creating your mystery beverage:")
ingredients = {}
total = 0
for bottle in bottles:
remaining = num_ingredients - len(ingredients.keys())
if remaining == 1:
oz = goal-total
else:
max_oz = goal - total - 0.5*(remaining-1)
# multiply by 2 because randrange likes ints
oz = random.randrange(1, max_oz*2, 1)/2
total += oz
ingredients[bottle] = Oz(oz)
print(f"\t{oz} Oz of {bottle}")

largest = max(ingredients, key=ingredients.get)
mystery_prefix = ['', 'giant', 'potent', 'disco-tastic', 'shiny', 'Dr.']
mystery_suffix = ['blaster', 'concoction', 'blend', 'cocktail']
mystery_extra_suffix = ['', 'jr', 'of wonder', 'esq']
name = []
name.append(random.choice(mystery_prefix))
name.append(largest)
name.append(random.choice(mystery_suffix))
name.append(random.choice(mystery_extra_suffix))
print(f'The {" ".join(name).strip()}')
print('Please enjoy responsibly.')
await self._dispense_ingredients(ingredients)

async def dispense(self, recipe: str):
if recipe == MYSTERY_DRINK:
return await self._dispense_mystery()

# TODO: be a bit nicer on the comparison here. Strings as keys aren't great, but I want the flexibility to add non-standard recipes
if recipe not in self.recipes.keys():
print(f"Unable to find the specified recipe. Available Recipes: {self.recipes.keys()}")
return
required_bottles = set(self.recipes[recipe].keys())
if not required_bottles.issubset(set(self.bottles)):
print('Recipe requires an ingredient that is not loaded into the drink machine')
print(f'Recipe requires: {required_bottles}')
print(f'Available: {self.bottles}')
return

ingredients = self.recipes[recipe]
self._dispense_ingredients(ingredients)

async def _dispense_ingredients(self, ingredients: dict[Bottle, Oz]):
for bottle, amount in ingredients.items():
ep = self.bottles[bottle]
time = amount.time()
await self.dev_ctrl.SendCommand(nodeid=self.node_id, endpoint=ep,
payload=Clusters.ValveConfigurationAndControl.Commands.Open(openDuration=time))

async def prime(self, endpoint: int):
await self.dev_ctrl.SendCommand(nodeid=self.node_id, endpoint=endpoint,
payload=Clusters.ValveConfigurationAndControl.Commands.Open(openDuration=NullValue))

async def stop(self, endpoint: int):
await self.dev_ctrl.SendCommand(nodeid=self.node_id, endpoint=endpoint,
payload=Clusters.ValveConfigurationAndControl.Commands.Close())
25 changes: 25 additions & 0 deletions examples/valve/linux/.gn
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright (c) 2020 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import("//build_overrides/build.gni")

# The location of the build configuration file.
buildconfig = "${build_root}/config/BUILDCONFIG.gn"

# CHIP uses angle bracket includes.
check_system_includes = true

default_args = {
import("//args.gni")
}
55 changes: 55 additions & 0 deletions examples/valve/linux/BUILD.gn
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Copyright (c) 2023 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import("//build_overrides/chip.gni")

import("${chip_root}/build/chip/tools.gni")
import("${chip_root}/src/app/common_flags.gni")

assert(chip_build_tools)

import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni")

config("includes") {
include_dirs = [
".",
"include",
]
}

executable("valve-app") {
sources = [
"include/CHIPProjectAppConfig.h",
"main.cpp",
]

deps = [
"${chip_root}/examples/platform/linux:app-main",
"${chip_root}/examples/valve/valve-common",
"${chip_root}/src/lib",
]

cflags = [ "-Wconversion" ]

include_dirs = [ "include" ]
output_dir = root_out_dir
}

group("linux") {
deps = [ ":valve-app" ]
}

group("default") {
deps = [ ":linux" ]
}
25 changes: 25 additions & 0 deletions examples/valve/linux/args.gni
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright (c) 2023 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import("//build_overrides/chip.gni")

import("${chip_root}/config/standalone/args.gni")

chip_device_project_config_include = "<CHIPProjectAppConfig.h>"
chip_project_config_include = "<CHIPProjectAppConfig.h>"
chip_system_project_config_include = "<SystemProjectConfig.h>"

chip_project_config_include_dirs =
[ "${chip_root}/examples/air-purifier-app/linux/include" ]
chip_project_config_include_dirs += [ "${chip_root}/config/standalone" ]
1 change: 1 addition & 0 deletions examples/valve/linux/build_overrides
38 changes: 38 additions & 0 deletions examples/valve/linux/include/CHIPProjectAppConfig.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
*
* Copyright (c) 2023 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#pragma once

// include the CHIPProjectConfig from config/standalone
#include <CHIPProjectConfig.h>

#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY 0

#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT 0

#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1

#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DEVICE_TYPE 1

#define CHIP_DEVICE_CONFIG_DEVICE_TYPE 0x0042 // Water valve

#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DEVICE_NAME 1

#define CHIP_DEVICE_ENABLE_PORT_PARAMS 1

#define CHIP_DEVICE_CONFIG_DEVICE_NAME "DISCO Drinks"
Loading
Loading