CI: add astyle pre-commit hook

This commit is contained in:
WanqQixiang
2026-02-03 15:30:42 +08:00
parent cb27fe763d
commit 968ff042a8
199 changed files with 4422 additions and 4726 deletions
-109
View File
@@ -1,109 +0,0 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: false
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: InlineOnly
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeComma
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeCategories:
- Regex: '^<'
Priority: 2
- Regex: '^".*/'
Priority: 5
- Regex: '^"'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 1000
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
...
+31 -2
View File
@@ -1,5 +1,5 @@
stages: stages:
- check_typos - pre_check
- cleanup - cleanup
- docker_build - docker_build
- build - build
@@ -250,6 +250,7 @@ build_image:
- job: build_image - job: build_image
optional: true optional: true
- job: check_typos - job: check_typos
- job: pre_commit_check
tags: tags:
- build - build
# runner: `sudo mkdir -p /cache/matter_build/` # runner: `sudo mkdir -p /cache/matter_build/`
@@ -616,6 +617,7 @@ build_managed_component_light:
- job: build_image - job: build_image
optional: true optional: true
- job: check_typos - job: check_typos
- job: pre_commit_check
script: script:
- cd ${ESP_MATTER_PATH}/examples/managed_component_light - cd ${ESP_MATTER_PATH}/examples/managed_component_light
- idf.py set-target esp32c3 - idf.py set-target esp32c3
@@ -649,6 +651,7 @@ build_esp_rainmaker_apps:
- job: build_image - job: build_image
optional: true optional: true
- job: check_typos - job: check_typos
- job: pre_commit_check
artifacts: artifacts:
paths: paths:
@@ -754,7 +757,7 @@ deploy_docs_production:
check_typos: check_typos:
image: $CI_DOCKER_REGISTRY/esp-env-v6.0:1 image: $CI_DOCKER_REGISTRY/esp-env-v6.0:1
stage: check_typos stage: pre_check
script: script:
- pip install codespell - pip install codespell
- git fetch origin main - git fetch origin main
@@ -766,3 +769,29 @@ check_typos:
fi fi
tags: tags:
- build - build
pre_commit_check:
image: $CI_DOCKER_REGISTRY/esp-env-v6.0:1
stage: pre_check
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" || $CI_PIPELINE_SOURCE == "push" || $CI_COMMIT_BRANCH == "main"
script:
- pip install pre-commit
- git fetch origin main
- pre-commit install-hooks
- |
# Get the base commit for comparison
BASE_COMMIT=$(git merge-base origin/main HEAD)
# Run pre-commit on changed files
FILES=$(git diff --name-only --diff-filter=ACMRT ${BASE_COMMIT}...HEAD)
if [ -n "$FILES" ]; then
echo "Running pre-commit on changed files:"
echo "$FILES"
# Convert newline-separated files to space-separated and pass to pre-commit
echo "$FILES" | xargs pre-commit run --files
else
echo "No files changed, skipping pre-commit"
fi
tags:
- build
+4 -4
View File
@@ -1,8 +1,8 @@
repos: repos:
- repo: https://github.com/pre-commit/mirrors-clang-format - repo: https://github.com/espressif/astyle_py.git
rev: '0f8362ad84fe4a446b807ffbfc9e65d078ecf732' rev: v1.0.5
hooks: hooks:
- id: clang-format - id: astyle_py
exclude: '^.*/zap-generated/.*$' args: ['--astyle-version=3.4.7', '--rules=tools/ci/astyle-rules.yml']
@@ -310,7 +310,6 @@ attribute_t *create_configuration_version(cluster_t *cluster, uint32_t value)
ATTRIBUTE_FLAG_MANAGED_INTERNALLY, esp_matter_uint32(value)); ATTRIBUTE_FLAG_MANAGED_INTERNALLY, esp_matter_uint32(value));
} }
} /* attribute */ } /* attribute */
} /* basic_information */ } /* basic_information */
@@ -558,7 +557,6 @@ attribute_t *create_test_event_triggers_enabled(cluster_t *cluster, bool value)
} /* attribute */ } /* attribute */
} /* general_diagnostics */ } /* general_diagnostics */
namespace software_diagnostics { namespace software_diagnostics {
namespace attribute { namespace attribute {
@@ -4920,7 +4918,6 @@ attribute_t *create_current_sessions(cluster_t *cluster, uint8_t *value, uint16_
} /* attribute */ } /* attribute */
}/*webrtc transport requestor*/ }/*webrtc transport requestor*/
namespace chime { namespace chime {
namespace attribute { namespace attribute {
attribute_t *create_installed_chime_sounds(cluster_t *cluster, uint8_t *value, uint16_t length, uint16_t count) attribute_t *create_installed_chime_sounds(cluster_t *cluster, uint8_t *value, uint16_t length, uint16_t count)
@@ -570,7 +570,6 @@ namespace activated_carbon_filter_monitoring {
namespace attribute = resource_monitoring::attribute; namespace attribute = resource_monitoring::attribute;
} /* activated_carbon_filter_monitoring */ } /* activated_carbon_filter_monitoring */
namespace concentration_measurement { namespace concentration_measurement {
namespace attribute { namespace attribute {
attribute_t *create_measured_value(cluster_t *cluster, nullable<float> value); attribute_t *create_measured_value(cluster_t *cluster, nullable<float> value);
@@ -93,13 +93,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
uint16_t min = 0, max = UINT16_MAX; uint16_t min = 0, max = UINT16_MAX;
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinLevel::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinLevel::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u16; min = min_val.val.u16;
} }
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxLevel::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxLevel::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u16; max = max_val.val.u16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -114,8 +112,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t min_val = esp_matter_invalid(NULL); esp_matter_attr_val_t min_val = esp_matter_invalid(NULL);
uint8_t min = 1, max = UINT8_MAX; uint8_t min = 1, max = UINT8_MAX;
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinLevel::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinLevel::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u8; min = min_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint8(min), esp_matter_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint8(min), esp_matter_uint8(max));
@@ -126,13 +123,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
uint16_t min = 0, max = UINT16_MAX; uint16_t min = 0, max = UINT16_MAX;
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinFrequency::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinFrequency::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u16; min = min_val.val.u16;
} }
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxFrequency::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxFrequency::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u16; max = max_val.val.u16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max));
@@ -142,8 +137,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
uint16_t min = 0, max = UINT16_MAX; uint16_t min = 0, max = UINT16_MAX;
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxFrequency::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxFrequency::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u16; max = max_val.val.u16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max));
@@ -153,8 +147,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t min_val = esp_matter_invalid(NULL); esp_matter_attr_val_t min_val = esp_matter_invalid(NULL);
uint16_t min = 0, max = UINT16_MAX; uint16_t min = 0, max = UINT16_MAX;
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinFrequency::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinFrequency::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u16; min = min_val.val.u16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max));
@@ -165,13 +158,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
uint8_t min = 0, max = UINT8_MAX; uint8_t min = 0, max = UINT8_MAX;
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinLevel::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MinLevel::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u8; min = min_val.val.u8;
} }
if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxLevel::Id, if (cluster::get_attribute_value(cluster, LevelControl::Attributes::MaxLevel::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -287,13 +278,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
uint16_t min = 0, max = UINT16_MAX; uint16_t min = 0, max = UINT16_MAX;
if (cluster::get_attribute_value(cluster, ColorControl::Attributes::ColorTempPhysicalMinMireds::Id, if (cluster::get_attribute_value(cluster, ColorControl::Attributes::ColorTempPhysicalMinMireds::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u16; min = min_val.val.u16;
} }
if (cluster::get_attribute_value(cluster, ColorControl::Attributes::ColorTemperatureMireds::Id, if (cluster::get_attribute_value(cluster, ColorControl::Attributes::ColorTemperatureMireds::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u16; max = max_val.val.u16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint16(min), esp_matter_uint16(max));
@@ -347,8 +336,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 100; nullable<uint8_t> min = 0, max = 100;
if (cluster::get_attribute_value(cluster, FanControl::Attributes::SpeedMax::Id, if (cluster::get_attribute_value(cluster, FanControl::Attributes::SpeedMax::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -358,8 +346,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
uint8_t min = 0, max = 100; uint8_t min = 0, max = 100;
if (cluster::get_attribute_value(cluster, FanControl::Attributes::SpeedMax::Id, if (cluster::get_attribute_value(cluster, FanControl::Attributes::SpeedMax::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint8(min), esp_matter_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_uint8(min), esp_matter_uint8(max));
@@ -401,13 +388,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
int16_t min = 1600, max = 3200; int16_t min = 1600, max = 3200;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinCoolSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinCoolSetpointLimit::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.i16; min = min_val.val.i16;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxCoolSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxCoolSetpointLimit::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.i16; max = max_val.val.i16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max));
@@ -419,13 +404,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
int16_t min = 700, max = 3000; int16_t min = 700, max = 3000;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinHeatSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinHeatSetpointLimit::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.i16; min = min_val.val.i16;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxHeatSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxHeatSetpointLimit::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.i16; max = max_val.val.i16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max));
@@ -436,13 +419,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
int16_t min = 700, max = 3000; int16_t min = 700, max = 3000;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMinHeatSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMinHeatSetpointLimit::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.i16; min = min_val.val.i16;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxHeatSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxHeatSetpointLimit::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.i16; max = max_val.val.i16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max));
@@ -453,13 +434,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
int16_t min = 1600, max = 3200; int16_t min = 1600, max = 3200;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinHeatSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinHeatSetpointLimit::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.i16; min = min_val.val.i16;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMaxHeatSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMaxHeatSetpointLimit::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.i16; max = max_val.val.i16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max));
@@ -470,13 +449,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
int16_t min = 700, max = 3000; int16_t min = 700, max = 3000;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMinCoolSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMinCoolSetpointLimit::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.i16; min = min_val.val.i16;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxCoolSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MaxCoolSetpointLimit::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.i16; max = max_val.val.i16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max));
@@ -487,13 +464,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
int16_t min = 700, max = 3000; int16_t min = 700, max = 3000;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinCoolSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::MinCoolSetpointLimit::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.i16; min = min_val.val.i16;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMaxCoolSetpointLimit::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::AbsMaxCoolSetpointLimit::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.i16; max = max_val.val.i16;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_int16(min), esp_matter_int16(max));
@@ -546,13 +521,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 254; nullable<uint8_t> min = 0, max = 254;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMin::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMin::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u8; min = min_val.val.u8;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMax::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMax::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -562,8 +535,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 254; nullable<uint8_t> min = 0, max = 254;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMax::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMax::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -573,8 +545,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t min_val = esp_matter_invalid(NULL); esp_matter_attr_val_t min_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 254; nullable<uint8_t> min = 0, max = 254;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMin::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::OccupiedSetbackMin::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u8; min = min_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -585,13 +556,11 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 254; nullable<uint8_t> min = 0, max = 254;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMin::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMin::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u8; min = min_val.val.u8;
} }
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMax::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMax::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -601,8 +570,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t max_val = esp_matter_invalid(NULL); esp_matter_attr_val_t max_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 254; nullable<uint8_t> min = 0, max = 254;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMax::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMax::Id,
&max_val) == ESP_OK) &max_val) == ESP_OK) {
{
max = max_val.val.u8; max = max_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -612,8 +580,7 @@ void add_bounds_cb(cluster_t *cluster)
esp_matter_attr_val_t min_val = esp_matter_invalid(NULL); esp_matter_attr_val_t min_val = esp_matter_invalid(NULL);
nullable<uint8_t> min = 0, max = 254; nullable<uint8_t> min = 0, max = 254;
if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMin::Id, if (cluster::get_attribute_value(cluster, Thermostat::Attributes::UnoccupiedSetbackMin::Id,
&min_val) == ESP_OK) &min_val) == ESP_OK) {
{
min = min_val.val.u8; min = min_val.val.u8;
} }
esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max)); esp_matter::attribute::add_bounds(current_attribute, esp_matter_nullable_uint8(min), esp_matter_nullable_uint8(max));
@@ -82,8 +82,7 @@ esp_matter_attr_val_t esp_matter_nullable_bool(nullable<bool> val)
}; };
if (val.is_null()) { if (val.is_null()) {
chip::app::NumericAttributeTraits<bool>::SetNull(*(uint8_t *)(&(attr_val.val.b))); chip::app::NumericAttributeTraits<bool>::SetNull(*(uint8_t *)(&(attr_val.val.b)));
} } else {
else {
attr_val.val.b = val.value(); attr_val.val.b = val.value();
} }
return attr_val; return attr_val;
@@ -521,7 +520,6 @@ esp_matter_attr_val_t esp_matter_array(uint8_t *val, uint16_t data_size, uint16_
namespace esp_matter { namespace esp_matter {
namespace attribute { namespace attribute {
bool val_is_null(esp_matter_attr_val_t *val) bool val_is_null(esp_matter_attr_val_t *val)
{ {
switch (val->type) { switch (val->type) {
@@ -223,8 +223,7 @@ private:
/** Template specialization for bool */ /** Template specialization for bool */
template <> template <>
class nullable<bool> class nullable<bool> {
{
using Traits = chip::app::NumericAttributeTraits<bool>; using Traits = chip::app::NumericAttributeTraits<bool>;
using StorageType = typename Traits::StorageType; // Resolves to uint8_t using StorageType = typename Traits::StorageType; // Resolves to uint8_t
@@ -233,12 +232,21 @@ class nullable<bool>
public: public:
/** Constructors */ /** Constructors */
nullable() { Traits::SetNull(storage); } nullable()
nullable(std::nullptr_t) { Traits::SetNull(storage); } {
Traits::SetNull(storage);
}
nullable(std::nullptr_t)
{
Traits::SetNull(storage);
}
constexpr nullable(bool v) : storage(static_cast<StorageType>(v)) {} constexpr nullable(bool v) : storage(static_cast<StorageType>(v)) {}
/** Observers */ /** Observers */
constexpr bool is_null() const { return Traits::IsNullValue(storage); } constexpr bool is_null() const
{
return Traits::IsNullValue(storage);
}
/** /**
* @brief Gets the stored bool value. * @brief Gets the stored bool value.
@@ -255,13 +263,25 @@ public:
* ``` * ```
* @return `true` if storage is non-zero (includes null state), `false` if storage is zero. * @return `true` if storage is non-zero (includes null state), `false` if storage is zero.
*/ */
constexpr bool value() const { return static_cast<bool>(storage); } constexpr bool value() const
{
return static_cast<bool>(storage);
}
constexpr bool value_or(bool d) const { return is_null() ? d : static_cast<bool>(storage); } constexpr bool value_or(bool d) const
{
return is_null() ? d : static_cast<bool>(storage);
}
/** Modifiers */ /** Modifiers */
void operator=(std::nullptr_t) { Traits::SetNull(storage); } void operator=(std::nullptr_t)
void operator=(bool v) { storage = static_cast<StorageType>(v); } {
Traits::SetNull(storage);
}
void operator=(bool v)
{
storage = static_cast<StorageType>(v);
}
private: private:
StorageType storage; // 1byte payload holding 0 / 1 / 0xFF StorageType storage; // 1byte payload holding 0 / 1 / 0xFF
@@ -54,8 +54,7 @@ namespace {
// this space is for feature validation functions // this space is for feature validation functions
enum class feature_policy enum class feature_policy {
{
k_exact_one = 0, // O.a k_exact_one = 0, // O.a
k_at_least_one = 1, // 0.a+ k_at_least_one = 1, // 0.a+
k_at_most_one = 2, // 0.a- k_at_most_one = 2, // 0.a-
@@ -768,7 +767,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
/* Attributes managed internally */ /* Attributes managed internally */
global::attribute::create_feature_map(cluster, 0); global::attribute::create_feature_map(cluster, 0);
/* Attributes not managed internally */ /* Attributes not managed internally */
global::attribute::create_cluster_revision(cluster, cluster_revision); global::attribute::create_cluster_revision(cluster, cluster_revision);
cluster::set_init_and_shutdown_callbacks(cluster, ESPMatterEthernetNetworkDiagnosticsClusterServerInitCallback, cluster::set_init_and_shutdown_callbacks(cluster, ESPMatterEthernetNetworkDiagnosticsClusterServerInitCallback,
@@ -2077,7 +2075,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
} }
} /* window_covering */ } /* window_covering */
namespace switch_cluster { namespace switch_cluster {
const function_generic_t *function_list = NULL; const function_generic_t *function_list = NULL;
const int function_flags = CLUSTER_FLAG_NONE; const int function_flags = CLUSTER_FLAG_NONE;
@@ -2355,7 +2352,8 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
namespace localization_configuration { namespace localization_configuration {
const function_generic_t function_list[] = { const function_generic_t function_list[] = {
(function_generic_t)emberAfLocalizationConfigurationClusterServerInitCallback, (function_generic_t)emberAfLocalizationConfigurationClusterServerInitCallback,
(function_generic_t)MatterLocalizationConfigurationClusterServerPreAttributeChangedCallback}; (function_generic_t)MatterLocalizationConfigurationClusterServerPreAttributeChangedCallback
};
const int function_flags = CLUSTER_FLAG_INIT_FUNCTION | CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION; const int function_flags = CLUSTER_FLAG_INIT_FUNCTION | CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION;
cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags) cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
@@ -2393,7 +2391,8 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
namespace time_format_localization { namespace time_format_localization {
const function_generic_t function_list[] = { const function_generic_t function_list[] = {
(function_generic_t)emberAfTimeFormatLocalizationClusterServerInitCallback, (function_generic_t)emberAfTimeFormatLocalizationClusterServerInitCallback,
(function_generic_t)MatterTimeFormatLocalizationClusterServerPreAttributeChangedCallback}; (function_generic_t)MatterTimeFormatLocalizationClusterServerPreAttributeChangedCallback
};
const int function_flags = CLUSTER_FLAG_INIT_FUNCTION | CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION; const int function_flags = CLUSTER_FLAG_INIT_FUNCTION | CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION;
cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags) cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
@@ -3044,7 +3043,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
/* Attributes managed internally */ /* Attributes managed internally */
global::attribute::create_feature_map(cluster, 0); global::attribute::create_feature_map(cluster, 0);
/* Attributes not managed internally */ /* Attributes not managed internally */
global::attribute::create_cluster_revision(cluster, cluster_revision); global::attribute::create_cluster_revision(cluster, cluster_revision);
} }
@@ -3827,7 +3825,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
attribute::create_supported_stream_usages(cluster, NULL, 0, 0); attribute::create_supported_stream_usages(cluster, NULL, 0, 0);
attribute::create_stream_usage_priorities(cluster, NULL, 0, 0); attribute::create_stream_usage_priorities(cluster, NULL, 0, 0);
// check against at least one feature conformance // check against at least one feature conformance
VALIDATE_FEATURES_AT_LEAST_ONE("Audio,Video,Snapshot", VALIDATE_FEATURES_AT_LEAST_ONE("Audio,Video,Snapshot",
feature::audio::get_id(), feature::video::get_id(), feature::snapshot::get_id()); feature::audio::get_id(), feature::video::get_id(), feature::snapshot::get_id());
@@ -3902,7 +3899,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
attribute::create_current_sessions(cluster, NULL, 0, 0); attribute::create_current_sessions(cluster, NULL, 0, 0);
command::create_solicit_offer(cluster); command::create_solicit_offer(cluster);
command::create_solicit_offer_response(cluster); command::create_solicit_offer_response(cluster);
command::create_provide_offer(cluster); command::create_provide_offer(cluster);
@@ -3944,7 +3940,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
attribute::create_current_sessions(cluster, NULL, 0, 0); attribute::create_current_sessions(cluster, NULL, 0, 0);
command::create_offer(cluster); command::create_offer(cluster);
command::create_answer(cluster); command::create_answer(cluster);
command::create_ice_candidates(cluster); command::create_ice_candidates(cluster);
@@ -3959,7 +3954,6 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags)
} }
} /*webrtc transport requestor*/ } /*webrtc transport requestor*/
// namespace binary_input_basic { // namespace binary_input_basic {
// // ToDo // // ToDo
// } /* binary_input_basic */ // } /* binary_input_basic */
@@ -969,7 +969,6 @@ using config_t = common::config_t;
cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags); cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags);
}/*webrtc transport requestor*/ }/*webrtc transport requestor*/
namespace chime { namespace chime {
typedef struct config { typedef struct config {
void *delegate; void *delegate;
@@ -2811,8 +2811,6 @@ command_t *create_capture_snapshot_response(cluster_t *cluster)
} /* command */ } /* command */
} /*camera av stream management*/ } /*camera av stream management*/
namespace webrtc_transport_provider { namespace webrtc_transport_provider {
namespace command { namespace command {
@@ -2880,7 +2878,6 @@ namespace webrtc_transport_requestor {
} /* command */ } /* command */
}/*webrtc_transport_requestor*/ }/*webrtc_transport_requestor*/
namespace chime { namespace chime {
namespace command { namespace command {
command_t *create_play_chime_sound(cluster_t *cluster) command_t *create_play_chime_sound(cluster_t *cluster)
@@ -382,7 +382,6 @@ namespace activated_carbon_filter_monitoring {
namespace command = resource_monitoring::command; namespace command = resource_monitoring::command;
} /* activated_carbon_filter_monitoring */ } /* activated_carbon_filter_monitoring */
namespace mode_base { namespace mode_base {
namespace command { namespace command {
command_t *create_change_to_mode(cluster_t *cluster); command_t *create_change_to_mode(cluster_t *cluster);
@@ -545,7 +544,6 @@ command_t *create_end(cluster_t *cluster);
} /* command */ } /* command */
}/*webrtc transport requestor*/ }/*webrtc transport requestor*/
namespace chime { namespace chime {
namespace command { namespace command {
command_t *create_play_chime_sound(cluster_t *cluster); command_t *create_play_chime_sound(cluster_t *cluster);
@@ -1921,11 +1921,13 @@ uint32_t get_cluster_count(uint32_t endpoint_id, uint32_t cluster_id, uint8_t cl
// lambda to count all matching clusters for an endpoint // lambda to count all matching clusters for an endpoint
auto get_count_on_all_clusters = [&check_cluster_flags](endpoint_t *endpoint) -> uint32_t { auto get_count_on_all_clusters = [&check_cluster_flags](endpoint_t *endpoint) -> uint32_t {
uint32_t result = 0; uint32_t result = 0;
if (!endpoint) if (!endpoint) {
return result; return result;
}
cluster_t *cluster = cluster::get_first(endpoint); cluster_t *cluster = cluster::get_first(endpoint);
while (cluster) { while (cluster)
{
result += check_cluster_flags(cluster); result += check_cluster_flags(cluster);
cluster = cluster::get_next(cluster); cluster = cluster::get_next(cluster);
} }
@@ -1935,8 +1937,9 @@ uint32_t get_cluster_count(uint32_t endpoint_id, uint32_t cluster_id, uint8_t cl
// lambda to find and count a specific cluster // lambda to find and count a specific cluster
auto get_count_on_specific_cluster = [&check_cluster_flags](const endpoint_t *endpoint, auto get_count_on_specific_cluster = [&check_cluster_flags](const endpoint_t *endpoint,
uint32_t cluster_id) -> uint32_t { uint32_t cluster_id) -> uint32_t {
if (!endpoint) if (!endpoint) {
return 0; return 0;
}
cluster_t *cluster = cluster::get((endpoint_t *)endpoint, cluster_id); cluster_t *cluster = cluster::get((endpoint_t *)endpoint, cluster_id);
return check_cluster_flags(cluster); return check_cluster_flags(cluster);
}; };
@@ -442,7 +442,6 @@ esp_err_t set_identify(uint16_t endpoint_id, void *identify);
*/ */
esp_err_t enable(endpoint_t *endpoint); esp_err_t enable(endpoint_t *endpoint);
/** Check if attribute is enabled /** Check if attribute is enabled
* *
* Check if the attribute of a cluster is enabled on an endpoint. * Check if the attribute of a cluster is enabled on an endpoint.
@@ -851,7 +850,6 @@ attribute_t *get(cluster_t *cluster, uint32_t attribute_id);
*/ */
attribute_t *get(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id); attribute_t *get(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id);
/** Get first attribute /** Get first attribute
* *
* Get the first attribute present on the cluster. * Get the first attribute present on the cluster.
@@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
#include <inttypes.h> #include <inttypes.h>
#include <esp_matter_delegate_callbacks.h> #include <esp_matter_delegate_callbacks.h>
#include <esp_matter_core.h> #include <esp_matter_core.h>
@@ -222,8 +221,7 @@ void MicrowaveOvenModeDelegateInitCB(void *delegate, uint16_t endpoint_id)
ModeBase::Delegate *mode_delegate = static_cast<ModeBase::Delegate*>(delegate); ModeBase::Delegate *mode_delegate = static_cast<ModeBase::Delegate*>(delegate);
ModeBase::Instance * modeInstance = nullptr; ModeBase::Instance * modeInstance = nullptr;
// Create new instance of MicrowaveOvenMode if not found in the map, otherwise use existing instance. // Create new instance of MicrowaveOvenMode if not found in the map, otherwise use existing instance.
if(s_microwave_oven_mode_instances.find(endpoint_id) == s_microwave_oven_mode_instances.end()) if (s_microwave_oven_mode_instances.find(endpoint_id) == s_microwave_oven_mode_instances.end()) {
{
uint32_t feature_map = get_feature_map_value(endpoint_id, MicrowaveOvenMode::Id); uint32_t feature_map = get_feature_map_value(endpoint_id, MicrowaveOvenMode::Id);
modeInstance = new ModeBase::Instance(mode_delegate, endpoint_id, MicrowaveOvenMode::Id, feature_map); modeInstance = new ModeBase::Instance(mode_delegate, endpoint_id, MicrowaveOvenMode::Id, feature_map);
s_microwave_oven_mode_instances[endpoint_id] = modeInstance; s_microwave_oven_mode_instances[endpoint_id] = modeInstance;
@@ -267,8 +265,7 @@ void MicrowaveOvenControlDelegateInitCB(void *delegate, uint16_t endpoint_id)
OperationalState::Instance* operationalStateInstance = nullptr; OperationalState::Instance* operationalStateInstance = nullptr;
// Create new instance of MicrowaveOvenMode if not found in the map, otherwise use existing instance. // Create new instance of MicrowaveOvenMode if not found in the map, otherwise use existing instance.
if(s_microwave_oven_mode_instances.find(endpoint_id) == s_microwave_oven_mode_instances.end()) if (s_microwave_oven_mode_instances.find(endpoint_id) == s_microwave_oven_mode_instances.end()) {
{
uint32_t feature_map = get_feature_map_value(endpoint_id, MicrowaveOvenMode::Id); uint32_t feature_map = get_feature_map_value(endpoint_id, MicrowaveOvenMode::Id);
microwaveOvenModeInstance = new ModeBase::Instance(microwave_oven_mode_delegate, endpoint_id, MicrowaveOvenMode::Id, feature_map); microwaveOvenModeInstance = new ModeBase::Instance(microwave_oven_mode_delegate, endpoint_id, MicrowaveOvenMode::Id, feature_map);
s_microwave_oven_mode_instances[endpoint_id] = microwaveOvenModeInstance; s_microwave_oven_mode_instances[endpoint_id] = microwaveOvenModeInstance;
@@ -277,8 +274,7 @@ void MicrowaveOvenControlDelegateInitCB(void *delegate, uint16_t endpoint_id)
} }
// Create new instance of OperationalState if not found in the map, otherwise use existing instance. // Create new instance of OperationalState if not found in the map, otherwise use existing instance.
if(s_operational_state_instances.find(endpoint_id) == s_operational_state_instances.end()) if (s_operational_state_instances.find(endpoint_id) == s_operational_state_instances.end()) {
{
operationalStateInstance = new OperationalState::Instance(operational_state_delegate, endpoint_id); operationalStateInstance = new OperationalState::Instance(operational_state_delegate, endpoint_id);
s_operational_state_instances[endpoint_id] = operationalStateInstance; s_operational_state_instances[endpoint_id] = operationalStateInstance;
} else { } else {
@@ -300,8 +296,7 @@ void OperationalStateDelegateInitCB(void *delegate, uint16_t endpoint_id)
static OperationalState::Instance * operationalStateInstance = nullptr; static OperationalState::Instance * operationalStateInstance = nullptr;
OperationalState::Delegate *operational_state_delegate = static_cast<OperationalState::Delegate*>(delegate); OperationalState::Delegate *operational_state_delegate = static_cast<OperationalState::Delegate*>(delegate);
// Create new instance of OperationalState if not found in the map, otherwise use existing instance. // Create new instance of OperationalState if not found in the map, otherwise use existing instance.
if(s_operational_state_instances.find(endpoint_id) == s_operational_state_instances.end()) if (s_operational_state_instances.find(endpoint_id) == s_operational_state_instances.end()) {
{
operationalStateInstance = new OperationalState::Instance(operational_state_delegate, endpoint_id); operationalStateInstance = new OperationalState::Instance(operational_state_delegate, endpoint_id);
s_operational_state_instances[endpoint_id] = operationalStateInstance; s_operational_state_instances[endpoint_id] = operationalStateInstance;
} else { } else {
@@ -466,8 +461,7 @@ void ServiceAreaDelegateInitCB(void *delegate, uint16_t endpoint_id)
void WaterHeaterManagementDelegateInitCB(void *delegate, uint16_t endpoint_id) void WaterHeaterManagementDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
if(delegate == nullptr) if (delegate == nullptr) {
{
return; return;
} }
static WaterHeaterManagement::Instance * wHtrInstance = nullptr; static WaterHeaterManagement::Instance * wHtrInstance = nullptr;
@@ -479,8 +473,7 @@ void WaterHeaterManagementDelegateInitCB(void *delegate, uint16_t endpoint_id)
void EnergyPreferenceDelegateInitCB(void *delegate, uint16_t endpoint_id) void EnergyPreferenceDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
if(delegate == nullptr) if (delegate == nullptr) {
{
return; return;
} }
EnergyPreference::Delegate *energy_preference_delegate = static_cast<EnergyPreference::Delegate*>(delegate); EnergyPreference::Delegate *energy_preference_delegate = static_cast<EnergyPreference::Delegate*>(delegate);
@@ -489,8 +482,7 @@ void EnergyPreferenceDelegateInitCB(void *delegate, uint16_t endpoint_id)
void CommissionerControlDelegateInitCB(void *delegate, uint16_t endpoint_id) void CommissionerControlDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
if(delegate == nullptr) if (delegate == nullptr) {
{
return; return;
} }
CommissionerControl::Delegate *commissioner_control_delegate = static_cast<CommissionerControl::Delegate*>(delegate); CommissionerControl::Delegate *commissioner_control_delegate = static_cast<CommissionerControl::Delegate*>(delegate);
@@ -509,7 +501,6 @@ void ActionsDelegateInitCB(void *delegate, uint16_t endpoint_id)
(void)actionsServer->Init(); (void)actionsServer->Init();
} }
void ThermostatDelegateInitCB(void *delegate, uint16_t endpoint_id) void ThermostatDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
@@ -548,7 +539,6 @@ void ClosureControlDelegateInitCB(void *delegate, uint16_t endpoint_id)
(void)server_interface->Init(); (void)server_interface->Init();
} }
void ClosureDimensionDelegateInitCB(void *delegate, uint16_t endpoint_id) void ClosureDimensionDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
@@ -559,7 +549,6 @@ void ClosureDimensionDelegateInitCB(void *delegate, uint16_t endpoint_id)
(void)server_interface->Init(); (void)server_interface->Init();
} }
void PushAvStreamTransportDelegateInitCB(void *delegate, uint16_t endpoint_id) void PushAvStreamTransportDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
@@ -567,7 +556,6 @@ void PushAvStreamTransportDelegateInitCB(void *delegate, uint16_t endpoint_id)
chip::app::Clusters::PushAvStreamTransport::SetDelegate(endpoint_id, push_av_stream_transport_delegate); chip::app::Clusters::PushAvStreamTransport::SetDelegate(endpoint_id, push_av_stream_transport_delegate);
} }
void CommodityTariffDelegateInitCB(void *delegate, uint16_t endpoint_id) void CommodityTariffDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
@@ -577,7 +565,6 @@ void CommodityTariffDelegateInitCB(void *delegate, uint16_t endpoint_id)
(void)commodity_tariff_instance->Init(); (void)commodity_tariff_instance->Init();
} }
void CommodityPriceDelegateInitCB(void *delegate, uint16_t endpoint_id) void CommodityPriceDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
@@ -587,7 +574,6 @@ void CommodityPriceDelegateInitCB(void *delegate, uint16_t endpoint_id)
(void)commodity_price_instance->Init(); (void)commodity_price_instance->Init();
} }
void ElectricalGridConditionsDelegateInitCB(void *delegate, uint16_t endpoint_id) void ElectricalGridConditionsDelegateInitCB(void *delegate, uint16_t endpoint_id)
{ {
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
@@ -1260,7 +1260,6 @@ uint8_t get_device_type_version()
return ESP_MATTER_ROOM_AIR_CONDITIONER_DEVICE_TYPE_VERSION; return ESP_MATTER_ROOM_AIR_CONDITIONER_DEVICE_TYPE_VERSION;
} }
endpoint_t *create(node_t *node, config_t *config, uint8_t flags, void *priv_data) endpoint_t *create(node_t *node, config_t *config, uint8_t flags, void *priv_data)
{ {
return common::create<config_t>(node, config, flags, priv_data, add); return common::create<config_t>(node, config, flags, priv_data, add);
@@ -274,7 +274,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace on_off_light { namespace on_off_light {
typedef struct config : on_off_with_lighting_config { typedef struct config : on_off_with_lighting_config {
config() { config()
{
/* For lighting product, the default identify type should be 0x01: LightOutput*/ /* For lighting product, the default identify type should be 0x01: LightOutput*/
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kLightOutput); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kLightOutput);
} }
@@ -331,7 +332,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace on_off_light_switch { namespace on_off_light_switch {
typedef struct config : app_client_config { typedef struct config : app_client_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -345,7 +347,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace dimmer_switch { namespace dimmer_switch {
typedef struct config : app_client_config { typedef struct config : app_client_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -359,7 +362,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace color_dimmer_switch { namespace color_dimmer_switch {
typedef struct config : app_client_config { typedef struct config : app_client_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -372,7 +376,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace generic_switch { namespace generic_switch {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::switch_cluster::config_t switch_cluster; cluster::switch_cluster::config_t switch_cluster;
@@ -387,7 +392,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace on_off_plug_in_unit { namespace on_off_plug_in_unit {
typedef struct config : on_off_with_lighting_config { typedef struct config : on_off_with_lighting_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -412,7 +418,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace fan { namespace fan {
typedef struct config : app_with_group_config { typedef struct config : app_with_group_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
cluster::fan_control::config_t fan_control; cluster::fan_control::config_t fan_control;
@@ -426,7 +433,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace thermostat { namespace thermostat {
typedef struct config : app_with_group_config { typedef struct config : app_with_group_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::scenes_management::config_t scenes_management; cluster::scenes_management::config_t scenes_management;
@@ -441,7 +449,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace air_quality_sensor { namespace air_quality_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::air_quality::config_t air_quality; cluster::air_quality::config_t air_quality;
@@ -455,7 +464,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace air_purifier { namespace air_purifier {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
cluster::fan_control::config_t fan_control; cluster::fan_control::config_t fan_control;
@@ -496,7 +506,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace smoke_co_alarm { namespace smoke_co_alarm {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kAudibleBeep); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kAudibleBeep);
} }
cluster::smoke_co_alarm::config_t smoke_co_alarm; cluster::smoke_co_alarm::config_t smoke_co_alarm;
@@ -543,7 +554,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace door_lock { namespace door_lock {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kAudibleBeep); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kAudibleBeep);
} }
cluster::door_lock::config_t door_lock; cluster::door_lock::config_t door_lock;
@@ -558,7 +570,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace window_covering { namespace window_covering {
typedef struct config : app_with_group_config { typedef struct config : app_with_group_config {
cluster::window_covering::config_t window_covering; cluster::window_covering::config_t window_covering;
config(uint8_t end_product_type = 0) : window_covering(end_product_type) { config(uint8_t end_product_type = 0) : window_covering(end_product_type)
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
} config_t; } config_t;
@@ -571,7 +584,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace temperature_sensor { namespace temperature_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::temperature_measurement::config_t temperature_measurement; cluster::temperature_measurement::config_t temperature_measurement;
@@ -585,7 +599,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace humidity_sensor { namespace humidity_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::relative_humidity_measurement::config_t relative_humidity_measurement; cluster::relative_humidity_measurement::config_t relative_humidity_measurement;
@@ -599,7 +614,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace occupancy_sensor { namespace occupancy_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kAudibleBeep); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kAudibleBeep);
} }
cluster::occupancy_sensing::config_t occupancy_sensing; cluster::occupancy_sensing::config_t occupancy_sensing;
@@ -614,7 +630,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace contact_sensor { namespace contact_sensor {
typedef struct config : app_with_bool_state_config { typedef struct config : app_with_bool_state_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -627,7 +644,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace light_sensor { namespace light_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::illuminance_measurement::config_t illuminance_measurement; cluster::illuminance_measurement::config_t illuminance_measurement;
@@ -641,7 +659,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace pressure_sensor { namespace pressure_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::pressure_measurement::config_t pressure_measurement; cluster::pressure_measurement::config_t pressure_measurement;
@@ -655,7 +674,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace flow_sensor { namespace flow_sensor {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
cluster::flow_measurement::config_t flow_measurement; cluster::flow_measurement::config_t flow_measurement;
@@ -675,7 +695,8 @@ typedef struct config : app_base_config {
nullable<int16_t> max_pressure = nullable<int16_t>(), nullable<int16_t> max_pressure = nullable<int16_t>(),
nullable<uint16_t> max_speed = nullable<uint16_t>(), nullable<uint16_t> max_speed = nullable<uint16_t>(),
nullable<uint16_t> max_flow = nullable<uint16_t>() nullable<uint16_t> max_flow = nullable<uint16_t>()
) : pump_configuration_and_control(max_pressure, max_speed, max_flow) { ) : pump_configuration_and_control(max_pressure, max_speed, max_flow)
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
} config_t; } config_t;
@@ -688,7 +709,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace pump_controller { namespace pump_controller {
typedef struct config : app_client_config { typedef struct config : app_client_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -713,7 +735,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace room_air_conditioner { namespace room_air_conditioner {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
cluster::on_off::config_t on_off; cluster::on_off::config_t on_off;
@@ -762,7 +785,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace robotic_vacuum_cleaner { namespace robotic_vacuum_cleaner {
typedef struct config : app_base_config { typedef struct config : app_base_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
cluster::rvc_run_mode::config_t rvc_run_mode; cluster::rvc_run_mode::config_t rvc_run_mode;
@@ -778,7 +802,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace water_leak_detector { namespace water_leak_detector {
typedef struct config : app_with_bool_state_config { typedef struct config : app_with_bool_state_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -792,7 +817,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace water_freeze_detector { namespace water_freeze_detector {
typedef struct config : app_with_bool_state_config { typedef struct config : app_with_bool_state_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -806,7 +832,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace rain_sensor { namespace rain_sensor {
typedef struct config : app_with_bool_state_config { typedef struct config : app_with_bool_state_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator);
} }
} config_t; } config_t;
@@ -895,7 +922,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace water_valve { namespace water_valve {
typedef struct config : app_base_config { typedef struct config : app_base_config {
cluster::valve_configuration_and_control::config_t valve_configuration_and_control; cluster::valve_configuration_and_control::config_t valve_configuration_and_control;
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
} config_t; } config_t;
@@ -946,7 +974,8 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
namespace mounted_on_off_control { namespace mounted_on_off_control {
typedef struct config : on_off_with_lighting_config { typedef struct config : on_off_with_lighting_config {
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
} config_t; } config_t;
@@ -1071,7 +1100,6 @@ esp_err_t add(endpoint_t *endpoint, config_t *config);
} /* chime */ } /* chime */
namespace thermostat_controller { namespace thermostat_controller {
using config_t = app_client_config; using config_t = app_client_config;
@@ -1094,7 +1122,8 @@ namespace closure {
typedef struct config : app_base_config { typedef struct config : app_base_config {
cluster::closure_control::config_t closure_control; cluster::closure_control::config_t closure_control;
config() { config()
{
identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator); identify.identify_type = chip::to_underlying(chip::app::Clusters::Identify::IdentifyTypeEnum::kActuator);
} }
} config_t; } config_t;
@@ -107,7 +107,6 @@ event_t *create_reachable_changed(cluster_t *cluster);
} // namespace event } // namespace event
} // namespace bridged_device_basic_information } // namespace bridged_device_basic_information
namespace power_source { namespace power_source {
namespace event { namespace event {
event_t *create_wired_fault_change(cluster_t *cluster); event_t *create_wired_fault_change(cluster_t *cluster);
@@ -1064,7 +1064,6 @@ esp_err_t add(cluster_t *cluster)
} /* feature */ } /* feature */
} /* ethernet_network_diagnostics */ } /* ethernet_network_diagnostics */
namespace air_quality { namespace air_quality {
namespace feature { namespace feature {
@@ -1835,7 +1834,6 @@ esp_err_t add(cluster_t *cluster, config_t *config)
} /* feature */ } /* feature */
} /* mode_select */ } /* mode_select */
namespace pressure_measurement { namespace pressure_measurement {
namespace feature { namespace feature {
@@ -2400,7 +2398,6 @@ esp_err_t add(cluster_t *cluster)
return ESP_ERR_NOT_SUPPORTED; return ESP_ERR_NOT_SUPPORTED;
} }
return ESP_OK; return ESP_OK;
} }
} /* polyphase_power */ } /* polyphase_power */
@@ -2426,7 +2423,6 @@ esp_err_t add(cluster_t *cluster)
return ESP_ERR_NOT_SUPPORTED; return ESP_ERR_NOT_SUPPORTED;
} }
return ESP_OK; return ESP_OK;
} }
} /* harmonics */ } /* harmonics */
@@ -2452,7 +2448,6 @@ esp_err_t add(cluster_t *cluster)
return ESP_ERR_NOT_SUPPORTED; return ESP_ERR_NOT_SUPPORTED;
} }
return ESP_OK; return ESP_OK;
} }
} /* power_quality */ } /* power_quality */
@@ -3208,7 +3203,6 @@ esp_err_t add(cluster_t *cluster)
event::create_power_adjust_start(cluster); event::create_power_adjust_start(cluster);
event::create_power_adjust_end(cluster); event::create_power_adjust_end(cluster);
return ESP_OK; return ESP_OK;
} }
} /* power_adjustment */ } /* power_adjustment */
@@ -3260,7 +3254,6 @@ esp_err_t add(cluster_t *cluster)
return ESP_ERR_NOT_SUPPORTED; return ESP_ERR_NOT_SUPPORTED;
} }
return ESP_OK; return ESP_OK;
} }
} /* state_forecast_reporting */ } /* state_forecast_reporting */
@@ -3494,7 +3487,6 @@ esp_err_t add(cluster_t *cluster)
return ESP_OK; return ESP_OK;
} }
} /* tank_percent */ } /* tank_percent */
} /* feature */ } /* feature */
@@ -4075,7 +4067,6 @@ esp_err_t add(cluster_t *cluster)
attribute::create_soft_recording_privacy_mode_enabled(cluster, 0); attribute::create_soft_recording_privacy_mode_enabled(cluster, 0);
attribute::create_soft_livestream_privacy_mode_enabled(cluster, 0); attribute::create_soft_livestream_privacy_mode_enabled(cluster, 0);
return ESP_OK; return ESP_OK;
} }
@@ -4099,7 +4090,6 @@ esp_err_t add(cluster_t *cluster)
attribute::create_speaker_max_level(cluster, 0); attribute::create_speaker_max_level(cluster, 0);
attribute::create_speaker_min_level(cluster, 0); attribute::create_speaker_min_level(cluster, 0);
return ESP_OK; return ESP_OK;
} }
@@ -4169,7 +4159,6 @@ esp_err_t add(cluster_t *cluster)
attribute::create_local_video_recording_enabled(cluster, 0); attribute::create_local_video_recording_enabled(cluster, 0);
attribute::create_local_snapshot_recording_enabled(cluster, 0); attribute::create_local_snapshot_recording_enabled(cluster, 0);
return ESP_OK; return ESP_OK;
} }
@@ -4220,7 +4209,6 @@ namespace webrtc_transport_provider {
namespace webrtc_transport_requestor { namespace webrtc_transport_requestor {
}/*webrtc_transport_requestor*/ }/*webrtc_transport_requestor*/
namespace closure_control { namespace closure_control {
namespace feature { namespace feature {
namespace positioning { namespace positioning {
@@ -1158,7 +1158,6 @@ esp_err_t add(cluster_t *cluster, config_t *config);
} /* feature */ } /* feature */
} /* boolean_state_configuration */ } /* boolean_state_configuration */
namespace power_topology { namespace power_topology {
namespace feature { namespace feature {
@@ -1891,7 +1890,6 @@ namespace webrtc_transport_provider {
namespace webrtc_transport_requestor { namespace webrtc_transport_requestor {
}/*webrtc_transport_requestor*/ }/*webrtc_transport_requestor*/
namespace closure_control { namespace closure_control {
namespace feature { namespace feature {
@@ -424,4 +424,3 @@ constexpr uint16_t cluster_revision = 1;
} // namespace soil_measurement } // namespace soil_measurement
} // namespace cluster } // namespace cluster
} // namespace esp_matter } // namespace esp_matter
@@ -85,37 +85,31 @@ static esp_err_t nvs_get_val(const char *nvs_namespace, const char *attribute_ke
// This switch case handles primitive data types // This switch case handles primitive data types
// if value is stored as primitive data type return it, else check if its stored as blob // if value is stored as primitive data type return it, else check if its stored as blob
// and convert it to primitive data type // and convert it to primitive data type
switch (val.type) switch (val.type) {
{ case ESP_MATTER_VAL_TYPE_BOOLEAN: {
case ESP_MATTER_VAL_TYPE_BOOLEAN:
{
uint8_t b_val; uint8_t b_val;
if ((err = nvs_get_u8(handle, attribute_key, &b_val)) == ESP_OK) if ((err = nvs_get_u8(handle, attribute_key, &b_val)) == ESP_OK) {
{
val.val.b = (b_val != 0); val.val.b = (b_val != 0);
} }
break; break;
} }
case ESP_MATTER_VAL_TYPE_INTEGER: case ESP_MATTER_VAL_TYPE_INTEGER:
case ESP_MATTER_VAL_TYPE_NULLABLE_INTEGER: case ESP_MATTER_VAL_TYPE_NULLABLE_INTEGER: {
{
err = nvs_get_i32(handle, attribute_key, reinterpret_cast<int32_t *>(&val.val.i)); err = nvs_get_i32(handle, attribute_key, reinterpret_cast<int32_t *>(&val.val.i));
break; break;
} }
// no nvs api to read float, since it is stored as blob, reading as blob // no nvs api to read float, since it is stored as blob, reading as blob
case ESP_MATTER_VAL_TYPE_FLOAT: case ESP_MATTER_VAL_TYPE_FLOAT:
case ESP_MATTER_VAL_TYPE_NULLABLE_FLOAT: case ESP_MATTER_VAL_TYPE_NULLABLE_FLOAT: {
{
size_t length = sizeof(val.val.f); size_t length = sizeof(val.val.f);
err = nvs_get_blob(handle, attribute_key, &val.val.f, &length); err = nvs_get_blob(handle, attribute_key, &val.val.f, &length);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT8: case ESP_MATTER_VAL_TYPE_INT8:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT8: case ESP_MATTER_VAL_TYPE_NULLABLE_INT8: {
{
err = nvs_get_i8(handle, attribute_key, &val.val.i8); err = nvs_get_i8(handle, attribute_key, &val.val.i8);
break; break;
} }
@@ -125,15 +119,13 @@ static esp_err_t nvs_get_val(const char *nvs_namespace, const char *attribute_ke
case ESP_MATTER_VAL_TYPE_BITMAP8: case ESP_MATTER_VAL_TYPE_BITMAP8:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT8: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT8:
case ESP_MATTER_VAL_TYPE_NULLABLE_ENUM8: case ESP_MATTER_VAL_TYPE_NULLABLE_ENUM8:
case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP8: case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP8: {
{
err = nvs_get_u8(handle, attribute_key, &val.val.u8); err = nvs_get_u8(handle, attribute_key, &val.val.u8);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT16: case ESP_MATTER_VAL_TYPE_INT16:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT16: case ESP_MATTER_VAL_TYPE_NULLABLE_INT16: {
{
err = nvs_get_i16(handle, attribute_key, &val.val.i16); err = nvs_get_i16(handle, attribute_key, &val.val.i16);
break; break;
} }
@@ -141,15 +133,13 @@ static esp_err_t nvs_get_val(const char *nvs_namespace, const char *attribute_ke
case ESP_MATTER_VAL_TYPE_UINT16: case ESP_MATTER_VAL_TYPE_UINT16:
case ESP_MATTER_VAL_TYPE_BITMAP16: case ESP_MATTER_VAL_TYPE_BITMAP16:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT16: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT16:
case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP16: case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP16: {
{
err = nvs_get_u16(handle, attribute_key, &val.val.u16); err = nvs_get_u16(handle, attribute_key, &val.val.u16);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT32: case ESP_MATTER_VAL_TYPE_INT32:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT32: case ESP_MATTER_VAL_TYPE_NULLABLE_INT32: {
{
err = nvs_get_i32(handle, attribute_key, &val.val.i32); err = nvs_get_i32(handle, attribute_key, &val.val.i32);
break; break;
} }
@@ -157,28 +147,24 @@ static esp_err_t nvs_get_val(const char *nvs_namespace, const char *attribute_ke
case ESP_MATTER_VAL_TYPE_UINT32: case ESP_MATTER_VAL_TYPE_UINT32:
case ESP_MATTER_VAL_TYPE_BITMAP32: case ESP_MATTER_VAL_TYPE_BITMAP32:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT32: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT32:
case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP32: case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP32: {
{
err = nvs_get_u32(handle, attribute_key, &val.val.u32); err = nvs_get_u32(handle, attribute_key, &val.val.u32);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT64: case ESP_MATTER_VAL_TYPE_INT64:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT64: case ESP_MATTER_VAL_TYPE_NULLABLE_INT64: {
{
err = nvs_get_i64(handle, attribute_key, &val.val.i64); err = nvs_get_i64(handle, attribute_key, &val.val.i64);
break; break;
} }
case ESP_MATTER_VAL_TYPE_UINT64: case ESP_MATTER_VAL_TYPE_UINT64:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT64: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT64: {
{
err = nvs_get_u64(handle, attribute_key, &val.val.u64); err = nvs_get_u64(handle, attribute_key, &val.val.u64);
break; break;
} }
default: default: {
{
// handle the case where the type is not recognized // handle the case where the type is not recognized
nvs_close(handle); nvs_close(handle);
ESP_LOGE(TAG, "Invalid attribute type: %u", val.type); ESP_LOGE(TAG, "Invalid attribute type: %u", val.type);
@@ -236,32 +222,27 @@ static esp_err_t nvs_store_val(const char *nvs_namespace, const char *attribute_
} else { } else {
// This switch case handles primitive data types // This switch case handles primitive data types
// always store values as primitive data type // always store values as primitive data type
switch (val.type) switch (val.type) {
{ case ESP_MATTER_VAL_TYPE_BOOLEAN: {
case ESP_MATTER_VAL_TYPE_BOOLEAN:
{
err = nvs_set_u8(handle, attribute_key, val.val.b != 0); err = nvs_set_u8(handle, attribute_key, val.val.b != 0);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INTEGER: case ESP_MATTER_VAL_TYPE_INTEGER:
case ESP_MATTER_VAL_TYPE_NULLABLE_INTEGER: case ESP_MATTER_VAL_TYPE_NULLABLE_INTEGER: {
{
err = nvs_set_i32(handle, attribute_key, val.val.i); err = nvs_set_i32(handle, attribute_key, val.val.i);
break; break;
} }
// no nvs api to store float, storing as blob // no nvs api to store float, storing as blob
case ESP_MATTER_VAL_TYPE_FLOAT: case ESP_MATTER_VAL_TYPE_FLOAT:
case ESP_MATTER_VAL_TYPE_NULLABLE_FLOAT: case ESP_MATTER_VAL_TYPE_NULLABLE_FLOAT: {
{
err = nvs_set_blob(handle, attribute_key, &val.val.f, sizeof(val.val.f)); err = nvs_set_blob(handle, attribute_key, &val.val.f, sizeof(val.val.f));
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT8: case ESP_MATTER_VAL_TYPE_INT8:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT8: case ESP_MATTER_VAL_TYPE_NULLABLE_INT8: {
{
err = nvs_set_i8(handle, attribute_key, val.val.i8); err = nvs_set_i8(handle, attribute_key, val.val.i8);
break; break;
} }
@@ -271,15 +252,13 @@ static esp_err_t nvs_store_val(const char *nvs_namespace, const char *attribute_
case ESP_MATTER_VAL_TYPE_BITMAP8: case ESP_MATTER_VAL_TYPE_BITMAP8:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT8: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT8:
case ESP_MATTER_VAL_TYPE_NULLABLE_ENUM8: case ESP_MATTER_VAL_TYPE_NULLABLE_ENUM8:
case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP8: case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP8: {
{
err = nvs_set_u8(handle, attribute_key, val.val.u8); err = nvs_set_u8(handle, attribute_key, val.val.u8);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT16: case ESP_MATTER_VAL_TYPE_INT16:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT16: case ESP_MATTER_VAL_TYPE_NULLABLE_INT16: {
{
err = nvs_set_i16(handle, attribute_key, val.val.i16); err = nvs_set_i16(handle, attribute_key, val.val.i16);
break; break;
} }
@@ -287,15 +266,13 @@ static esp_err_t nvs_store_val(const char *nvs_namespace, const char *attribute_
case ESP_MATTER_VAL_TYPE_UINT16: case ESP_MATTER_VAL_TYPE_UINT16:
case ESP_MATTER_VAL_TYPE_BITMAP16: case ESP_MATTER_VAL_TYPE_BITMAP16:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT16: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT16:
case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP16: case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP16: {
{
err = nvs_set_u16(handle, attribute_key, val.val.u16); err = nvs_set_u16(handle, attribute_key, val.val.u16);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT32: case ESP_MATTER_VAL_TYPE_INT32:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT32: case ESP_MATTER_VAL_TYPE_NULLABLE_INT32: {
{
err = nvs_set_i32(handle, attribute_key, val.val.i32); err = nvs_set_i32(handle, attribute_key, val.val.i32);
break; break;
} }
@@ -303,28 +280,24 @@ static esp_err_t nvs_store_val(const char *nvs_namespace, const char *attribute_
case ESP_MATTER_VAL_TYPE_UINT32: case ESP_MATTER_VAL_TYPE_UINT32:
case ESP_MATTER_VAL_TYPE_BITMAP32: case ESP_MATTER_VAL_TYPE_BITMAP32:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT32: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT32:
case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP32: case ESP_MATTER_VAL_TYPE_NULLABLE_BITMAP32: {
{
err = nvs_set_u32(handle, attribute_key, val.val.u32); err = nvs_set_u32(handle, attribute_key, val.val.u32);
break; break;
} }
case ESP_MATTER_VAL_TYPE_INT64: case ESP_MATTER_VAL_TYPE_INT64:
case ESP_MATTER_VAL_TYPE_NULLABLE_INT64: case ESP_MATTER_VAL_TYPE_NULLABLE_INT64: {
{
err = nvs_set_i64(handle, attribute_key, val.val.i64); err = nvs_set_i64(handle, attribute_key, val.val.i64);
break; break;
} }
case ESP_MATTER_VAL_TYPE_UINT64: case ESP_MATTER_VAL_TYPE_UINT64:
case ESP_MATTER_VAL_TYPE_NULLABLE_UINT64: case ESP_MATTER_VAL_TYPE_NULLABLE_UINT64: {
{
err = nvs_set_u64(handle, attribute_key, val.val.u64); err = nvs_set_u64(handle, attribute_key, val.val.u64);
break; break;
} }
default: default: {
{
// handle the case where the type is not recognized // handle the case where the type is not recognized
err = ESP_ERR_INVALID_ARG; err = ESP_ERR_INVALID_ARG;
ESP_LOGE(TAG, "Invalid attribute type: %u", val.type); ESP_LOGE(TAG, "Invalid attribute type: %u", val.type);
@@ -54,23 +54,35 @@ public:
* Sets the Enabled attribute. Note, this also handles writing the new value into non-volatile storage. * Sets the Enabled attribute. Note, this also handles writing the new value into non-volatile storage.
* @param Enabled The value to which the Enabled is to be set. * @param Enabled The value to which the Enabled is to be set.
*/ */
Protocols::InteractionModel::Status SetEnabled(bool enabled) { return mCluster.Cluster().SetEnabled(enabled); } Protocols::InteractionModel::Status SetEnabled(bool enabled)
{
return mCluster.Cluster().SetEnabled(enabled);
}
// Attribute Getters // Attribute Getters
/** /**
* @return The Current SelectedChime. * @return The Current SelectedChime.
*/ */
uint8_t GetSelectedChime() const { return mCluster.Cluster().GetSelectedChime(); } uint8_t GetSelectedChime() const
{
return mCluster.Cluster().GetSelectedChime();
}
/** /**
* @return The Enabled attribute.. * @return The Enabled attribute..
*/ */
bool GetEnabled() const { return mCluster.Cluster().GetEnabled(); } bool GetEnabled() const
{
return mCluster.Cluster().GetEnabled();
}
/** /**
* @return The endpoint ID. * @return The endpoint ID.
*/ */
EndpointId GetEndpointId() { return mCluster.Cluster().GetPaths()[0].mEndpointId; } EndpointId GetEndpointId()
{
return mCluster.Cluster().GetPaths()[0].mEndpointId;
}
// Cluster constants from the spec // Cluster constants from the spec
static constexpr uint8_t kMaxChimeSoundNameSize = ChimeCluster::kMaxChimeSoundNameSize; static constexpr uint8_t kMaxChimeSoundNameSize = ChimeCluster::kMaxChimeSoundNameSize;
@@ -35,8 +35,7 @@ namespace {
* emberAfSetDynamicEndpointWithEpUniqueId() by calling emberAfEndpointEnableDisable(), which calls initializeEndpoint(). The tag * emberAfSetDynamicEndpointWithEpUniqueId() by calling emberAfEndpointEnableDisable(), which calls initializeEndpoint(). The tag
* list is a fixed attribute, but to maintain backwards compatibility we get that information within the functions here. * list is a fixed attribute, but to maintain backwards compatibility we get that information within the functions here.
*/ */
class ESPMatterDescriptorCluster : public DescriptorCluster class ESPMatterDescriptorCluster : public DescriptorCluster {
{
public: public:
ESPMatterDescriptorCluster(EndpointId endpointId, DescriptorCluster::OptionalAttributesSet optionalAttributeSet) : ESPMatterDescriptorCluster(EndpointId endpointId, DescriptorCluster::OptionalAttributesSet optionalAttributeSet) :
DescriptorCluster(endpointId, optionalAttributeSet, Span<const SemanticTag>()) DescriptorCluster(endpointId, optionalAttributeSet, Span<const SemanticTag>())
@@ -44,8 +43,7 @@ public:
CHIP_ERROR Attributes(const ConcreteClusterPath &path, ReadOnlyBufferBuilder<DataModel::AttributeEntry> &builder) override CHIP_ERROR Attributes(const ConcreteClusterPath &path, ReadOnlyBufferBuilder<DataModel::AttributeEntry> &builder) override
{ {
if (!mFetchedSemanticTags) if (!mFetchedSemanticTags) {
{
ReturnErrorOnFailure(GetSemanticTag(path.mEndpointId, mSemanticTags)); ReturnErrorOnFailure(GetSemanticTag(path.mEndpointId, mSemanticTags));
mFetchedSemanticTags = true; mFetchedSemanticTags = true;
} }
@@ -55,8 +53,7 @@ public:
DataModel::ActionReturnStatus ReadAttribute(const DataModel::ReadAttributeRequest &request, DataModel::ActionReturnStatus ReadAttribute(const DataModel::ReadAttributeRequest &request,
AttributeValueEncoder &encoder) override AttributeValueEncoder &encoder) override
{ {
if (!mFetchedSemanticTags) if (!mFetchedSemanticTags) {
{
ReturnErrorOnFailure(GetSemanticTag(request.path.mEndpointId, mSemanticTags)); ReturnErrorOnFailure(GetSemanticTag(request.path.mEndpointId, mSemanticTags));
mFetchedSemanticTags = true; mFetchedSemanticTags = true;
} }
@@ -31,8 +31,7 @@ CHIP_ERROR Instance::Init()
{ {
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(mCluster.Registration()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(mCluster.Registration());
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(AppServer, "Failed to register cluster %u/" ChipLogFormatMEI ": %" CHIP_ERROR_FORMAT, ChipLogError(AppServer, "Failed to register cluster %u/" ChipLogFormatMEI ": %" CHIP_ERROR_FORMAT,
mCluster.Cluster().GetPaths()[0].mEndpointId, ChipLogValueMEI(DeviceEnergyManagement::Id), err.Format()); mCluster.Cluster().GetPaths()[0].mEndpointId, ChipLogValueMEI(DeviceEnergyManagement::Id), err.Format());
} }
@@ -43,8 +42,7 @@ void Instance::Shutdown()
{ {
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&mCluster.Cluster()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&mCluster.Cluster());
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(AppServer, "Failed to unregister cluster %u/" ChipLogFormatMEI ": %" CHIP_ERROR_FORMAT, ChipLogError(AppServer, "Failed to unregister cluster %u/" ChipLogFormatMEI ": %" CHIP_ERROR_FORMAT,
mCluster.Cluster().GetPaths()[0].mEndpointId, ChipLogValueMEI(DeviceEnergyManagement::Id), err.Format()); mCluster.Cluster().GetPaths()[0].mEndpointId, ChipLogValueMEI(DeviceEnergyManagement::Id), err.Format());
} }
@@ -19,8 +19,7 @@
namespace chip::app::Clusters::DeviceEnergyManagement { namespace chip::app::Clusters::DeviceEnergyManagement {
class Instance class Instance {
{
public: public:
Instance(EndpointId aEndpointId, Delegate &aDelegate, BitMask<Feature> aFeature); Instance(EndpointId aEndpointId, Delegate &aDelegate, BitMask<Feature> aFeature);
@@ -20,8 +20,7 @@
namespace chip::app::Clusters::ElectricalPowerMeasurement { namespace chip::app::Clusters::ElectricalPowerMeasurement {
enum class OptionalAttributes : uint32_t enum class OptionalAttributes : uint32_t {
{
kOptionalAttributeRanges = 0x1, kOptionalAttributeRanges = 0x1,
kOptionalAttributeVoltage = 0x2, kOptionalAttributeVoltage = 0x2,
kOptionalAttributeActiveCurrent = 0x4, kOptionalAttributeActiveCurrent = 0x4,
@@ -37,8 +36,7 @@ enum class OptionalAttributes : uint32_t
kOptionalAttributeNeutralCurrent = 0x1000, kOptionalAttributeNeutralCurrent = 0x1000,
}; };
class Instance class Instance {
{
public: public:
Instance(EndpointId aEndpointId, Delegate &aDelegate, BitMask<Feature> aFeature, Instance(EndpointId aEndpointId, Delegate &aDelegate, BitMask<Feature> aFeature,
BitMask<OptionalAttributes> aOptionalAttributes) : BitMask<OptionalAttributes> aOptionalAttributes) :
@@ -86,7 +86,10 @@ public:
} }
} }
} }
bool IsTriggerEffectEnabled() const override { return true; } bool IsTriggerEffectEnabled() const override
{
return true;
}
}; };
IdentifyLegacyDelegate gLegacyDelegate; IdentifyLegacyDelegate gLegacyDelegate;
@@ -52,8 +52,7 @@ static_assert(kNetworkCommissioningClusterCount > 0, "NetworkCommissioningCluste
LazyRegisteredServerCluster<NetworkCommissioningCluster> gServers[kNetworkCommissioningClusterCount]; LazyRegisteredServerCluster<NetworkCommissioningCluster> gServers[kNetworkCommissioningClusterCount];
class ESPMatterGeneralCommissioningBreadcrumbTracker : public BreadCrumbTracker class ESPMatterGeneralCommissioningBreadcrumbTracker : public BreadCrumbTracker {
{
public: public:
void SetBreadCrumb(uint64_t value) override void SetBreadCrumb(uint64_t value) override
{ {
@@ -67,7 +67,8 @@ void ESPMatterOccupancySensingClusterServerInitCallback(EndpointId endpointId)
// SetHoldTime() later to customize. Initial defaults come from typical values found in real devices on the // SetHoldTime() later to customize. Initial defaults come from typical values found in real devices on the
// market. // market.
constexpr chip::app::Clusters::OccupancySensing::Structs::HoldTimeLimitsStruct::Type kDefaultHoldTimeLimits = { constexpr chip::app::Clusters::OccupancySensing::Structs::HoldTimeLimitsStruct::Type kDefaultHoldTimeLimits = {
.holdTimeMin = 1, .holdTimeMax = 300, .holdTimeDefault = 30}; .holdTimeMin = 1, .holdTimeMax = 300, .holdTimeDefault = 30
};
config.WithHoldTime(kDefaultHoldTimeLimits.holdTimeDefault, kDefaultHoldTimeLimits, gDefaultTimerDelegate); config.WithHoldTime(kDefaultHoldTimeLimits.holdTimeDefault, kDefaultHoldTimeLimits, gDefaultTimerDelegate);
// Show deprecated attributes if enabled in Zap // Show deprecated attributes if enabled in Zap
@@ -34,7 +34,8 @@ void ESPMatterOperationalCredentialsClusterServerInitCallback(EndpointId endpoin
.sessionManager = Server::GetInstance().GetSecureSessionManager(), .sessionManager = Server::GetInstance().GetSecureSessionManager(),
.dnssdServer = app::DnssdServer::Instance(), .dnssdServer = app::DnssdServer::Instance(),
.commissioningWindowManager = .commissioningWindowManager =
Server::GetInstance().GetCommissioningWindowManager()}; Server::GetInstance().GetCommissioningWindowManager()
};
gServer.Create(endpoint, context); gServer.Create(endpoint, context);
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(gServer.Registration()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(gServer.Registration());
if (err != CHIP_NO_ERROR) { if (err != CHIP_NO_ERROR) {
@@ -38,8 +38,7 @@ CHIP_ERROR Instance::Init()
void Instance::Shutdown() void Instance::Shutdown()
{ {
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&mCluster.Cluster()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&mCluster.Cluster());
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(AppServer, "Failed to unregister Power Topology cluster: %" CHIP_ERROR_FORMAT, err.Format()); ChipLogError(AppServer, "Failed to unregister Power Topology cluster: %" CHIP_ERROR_FORMAT, err.Format());
} }
} }
@@ -20,8 +20,7 @@
namespace chip::app::Clusters::PowerTopology { namespace chip::app::Clusters::PowerTopology {
class Instance class Instance {
{
public: public:
Instance(EndpointId aEndpointId, Delegate &aDelegate, BitMask<Feature> aFeature) : Instance(EndpointId aEndpointId, Delegate &aDelegate, BitMask<Feature> aFeature) :
mCluster(PowerTopologyCluster::Config{ mCluster(PowerTopologyCluster::Config{
@@ -30,7 +29,10 @@ public:
.features = aFeature, .features = aFeature,
}) })
{} {}
~Instance() { Shutdown(); } ~Instance()
{
Shutdown();
}
CHIP_ERROR Init(); CHIP_ERROR Init();
void Shutdown(); void Shutdown();
@@ -65,22 +65,30 @@ typename app::NumericAttributeTraits<Type>::WorkingType ConvertDefaultValueToWor
bool IsExactlyOneValuePopulated(const AttributeValuePairType &type) bool IsExactlyOneValuePopulated(const AttributeValuePairType &type)
{ {
int count = 0; int count = 0;
if (type.valueUnsigned8.HasValue()) if (type.valueUnsigned8.HasValue()) {
count++; count++;
if (type.valueSigned8.HasValue()) }
if (type.valueSigned8.HasValue()) {
count++; count++;
if (type.valueUnsigned16.HasValue()) }
if (type.valueUnsigned16.HasValue()) {
count++; count++;
if (type.valueSigned16.HasValue()) }
if (type.valueSigned16.HasValue()) {
count++; count++;
if (type.valueUnsigned32.HasValue()) }
if (type.valueUnsigned32.HasValue()) {
count++; count++;
if (type.valueSigned32.HasValue()) }
if (type.valueSigned32.HasValue()) {
count++; count++;
if (type.valueUnsigned64.HasValue()) }
if (type.valueUnsigned64.HasValue()) {
count++; count++;
if (type.valueSigned64.HasValue()) }
if (type.valueSigned64.HasValue()) {
count++; count++;
}
return count == 1; return count == 1;
} }
@@ -40,9 +40,15 @@ public:
mEndpointId = endpointId; mEndpointId = endpointId;
mEndpointTableSize = endpointTableSize; mEndpointTableSize = endpointTableSize;
} }
EndpointId GetEndpointId() const { return mEndpointId; } EndpointId GetEndpointId() const
{
return mEndpointId;
}
ScenesManagementSceneTable *Take() override { return scenes::GetSceneTableImpl(mEndpointId, mEndpointTableSize); } ScenesManagementSceneTable *Take() override
{
return scenes::GetSceneTableImpl(mEndpointId, mEndpointTableSize);
}
void Release(ScenesManagementSceneTable *) override {} void Release(ScenesManagementSceneTable *) override {}
private: private:
@@ -21,8 +21,7 @@
namespace chip::app::Clusters::ScenesManagement { namespace chip::app::Clusters::ScenesManagement {
class ScenesServer class ScenesServer {
{
public: public:
static constexpr SceneId kGlobalSceneId = 0x00; static constexpr SceneId kGlobalSceneId = 0x00;
static constexpr GroupId kGlobalSceneGroupId = 0x0000; static constexpr GroupId kGlobalSceneGroupId = 0x0000;
@@ -123,8 +123,7 @@ void SetDefaultDelegate(Delegate * delegate)
VerifyOrReturn(delegate != nullptr); VerifyOrReturn(delegate != nullptr);
gDelegate = delegate; gDelegate = delegate;
auto timeSynchronization = GetClusterInstance(); auto timeSynchronization = GetClusterInstance();
if (timeSynchronization != nullptr) if (timeSynchronization != nullptr) {
{
timeSynchronization->SetDelegate(gDelegate); timeSynchronization->SetDelegate(gDelegate);
} }
} }
@@ -132,12 +131,10 @@ void SetDefaultDelegate(Delegate * delegate)
Delegate * GetDefaultDelegate() Delegate * GetDefaultDelegate()
{ {
auto timeSynchronization = GetClusterInstance(); auto timeSynchronization = GetClusterInstance();
if (timeSynchronization != nullptr) if (timeSynchronization != nullptr) {
{
return timeSynchronization->GetDelegate(); return timeSynchronization->GetDelegate();
} }
if (gDelegate == nullptr) if (gDelegate == nullptr) {
{
static DefaultTimeSyncDelegate delegate; static DefaultTimeSyncDelegate delegate;
gDelegate = &delegate; gDelegate = &delegate;
} }
@@ -18,8 +18,7 @@
namespace chip::app::Clusters::UnitLocalization { namespace chip::app::Clusters::UnitLocalization {
class UnitLocalizationServer : public UnitLocalizationCluster class UnitLocalizationServer : public UnitLocalizationCluster {
{
public: public:
static UnitLocalizationServer &Instance(); static UnitLocalizationServer &Instance();
}; };
@@ -71,8 +71,7 @@ void ESPMatterWiFiNetworkDiagnosticsClusterServerInitCallback(EndpointId endpoin
BitFlags<WiFiNetworkDiagnostics::Feature>(GetFeatureMap(endpointId))); BitFlags<WiFiNetworkDiagnostics::Feature>(GetFeatureMap(endpointId)));
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(gServers[endpointId].Registration()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(gServers[endpointId].Registration());
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(AppServer, "Failed to register WiFiNetworkDiagnostics on endpoint %u - Error: %" CHIP_ERROR_FORMAT, endpointId, ChipLogError(AppServer, "Failed to register WiFiNetworkDiagnostics on endpoint %u - Error: %" CHIP_ERROR_FORMAT, endpointId,
err.Format()); err.Format());
} }
@@ -83,8 +82,7 @@ void ESPMatterWiFiNetworkDiagnosticsClusterServerShutdownCallback(EndpointId end
{ {
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&gServers[endpointId].Cluster(), shutdownType); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&gServers[endpointId].Cluster(), shutdownType);
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(AppServer, "Failed to unregister WiFiNetworkDiagnostics on endpoint %u - Error: %" CHIP_ERROR_FORMAT, endpointId, ChipLogError(AppServer, "Failed to unregister WiFiNetworkDiagnostics on endpoint %u - Error: %" CHIP_ERROR_FORMAT, endpointId,
err.Format()); err.Format());
} }
@@ -44,7 +44,10 @@ public:
} }
} }
esp_matter_attr_val_t &get_attr_val() { return m_attr_val; } esp_matter_attr_val_t &get_attr_val()
{
return m_attr_val;
}
CHIP_ERROR Decode(chip::TLV::TLVReader &reader); CHIP_ERROR Decode(chip::TLV::TLVReader &reader);
@@ -47,12 +47,14 @@ namespace app {
* Accessor class for AttributeValueDecoder to get the TLV reader. * Accessor class for AttributeValueDecoder to get the TLV reader.
* This leverages the existing friend declaration in the SDK's AttributeValueDecoder. * This leverages the existing friend declaration in the SDK's AttributeValueDecoder.
*/ */
class TestOnlyAttributeValueDecoderAccessor class TestOnlyAttributeValueDecoderAccessor {
{
public: public:
TestOnlyAttributeValueDecoderAccessor(AttributeValueDecoder &decoder) : mDecoder(decoder) {} TestOnlyAttributeValueDecoderAccessor(AttributeValueDecoder &decoder) : mDecoder(decoder) {}
const TLV::TLVReader & GetReader() { return mDecoder.mReader; } const TLV::TLVReader &GetReader()
{
return mDecoder.mReader;
}
private: private:
AttributeValueDecoder &mDecoder; AttributeValueDecoder &mDecoder;
@@ -597,7 +599,8 @@ CHIP_ERROR provider::AcceptedCommands(const ConcreteClusterPath &path,
static constexpr AttributeId k_global_attributes_not_in_metadata[] = { static constexpr AttributeId k_global_attributes_not_in_metadata[] = {
Clusters::Globals::Attributes::AttributeList::Id, Clusters::Globals::Attributes::AcceptedCommandList::Id, Clusters::Globals::Attributes::AttributeList::Id, Clusters::Globals::Attributes::AcceptedCommandList::Id,
Clusters::Globals::Attributes::GeneratedCommandList::Id}; Clusters::Globals::Attributes::GeneratedCommandList::Id
};
static constexpr size_t k_global_attributes_count = static constexpr size_t k_global_attributes_count =
sizeof(k_global_attributes_not_in_metadata) / sizeof(k_global_attributes_not_in_metadata[0]); sizeof(k_global_attributes_not_in_metadata) / sizeof(k_global_attributes_not_in_metadata[0]);
@@ -631,8 +634,7 @@ CHIP_ERROR provider::Attributes(const ConcreteClusterPath &path, ReadOnlyBufferB
attribute = attribute::get_next(attribute); attribute = attribute::get_next(attribute);
} }
// Append the three Global attributes // Append the three Global attributes
for (size_t index = 0; index < k_global_attributes_count; ++index) for (size_t index = 0; index < k_global_attributes_count; ++index) {
{
AttributeEntry entry(k_global_attributes_not_in_metadata[index], AttributeEntry entry(k_global_attributes_not_in_metadata[index],
chip::BitFlags<DataModel::AttributeQualityFlags>(), chip::Access::Privilege::kView, chip::BitFlags<DataModel::AttributeQualityFlags>(), chip::Access::Privilege::kView,
std::nullopt); std::nullopt);
@@ -68,7 +68,10 @@ public:
// access to the typed global singleton of this class. // access to the typed global singleton of this class.
static provider &get_instance(); static provider &get_instance();
chip::app::ServerClusterInterfaceRegistry &registry() { return mRegistry; } chip::app::ServerClusterInterfaceRegistry &registry()
{
return mRegistry;
}
/// Generic model implementations /// Generic model implementations
CHIP_ERROR Startup(InteractionModelContext context) override; CHIP_ERROR Startup(InteractionModelContext context) override;
@@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Cluster init functions that don't have a cluster implementation to define // Cluster init functions that don't have a cluster implementation to define
// them in. // them in.
void MatterBallastConfigurationPluginServerInitCallback() {} void MatterBallastConfigurationPluginServerInitCallback() {}
+1 -2
View File
@@ -45,8 +45,7 @@ namespace DeviceEventType {
/** /**
* Enumerates platform-specific event types that are visible to the application. * Enumerates platform-specific event types that are visible to the application.
*/ */
enum enum {
{
/** Signals that Commissioning session has started */ /** Signals that Commissioning session has started */
kCommissioningSessionStarted = kRange_PublicPlatformSpecific + 0x1000, kCommissioningSessionStarted = kRange_PublicPlatformSpecific + 0x1000,
/** Signals that Commissioning session has stopped */ /** Signals that Commissioning session has stopped */
+12 -3
View File
@@ -294,9 +294,18 @@ public:
} }
private: private:
void OnReportBegin() override { m_callback.OnReportBegin(); } void OnReportBegin() override
void OnReportEnd() override { m_callback.OnReportEnd(); } {
void OnError(CHIP_ERROR aError) override { m_callback.OnError(aError); } m_callback.OnReportBegin();
}
void OnReportEnd() override
{
m_callback.OnReportEnd();
}
void OnError(CHIP_ERROR aError) override
{
m_callback.OnError(aError);
}
void OnAttributeData(const ConcreteDataAttributePath &aPath, TLVReader *apData, const StatusIB &aStatus) override void OnAttributeData(const ConcreteDataAttributePath &aPath, TLVReader *apData, const StatusIB &aStatus) override
{ {
+18 -9
View File
@@ -178,8 +178,7 @@ using chip::TLV::TLVReader;
using client::peer_device_t; using client::peer_device_t;
using chip::app::DataModel::EncodableToTLV; using chip::app::DataModel::EncodableToTLV;
class custom_encodable_type : public EncodableToTLV class custom_encodable_type : public EncodableToTLV {
{
public: public:
const char *k_empty_command_data = "{}"; const char *k_empty_command_data = "{}";
const char *k_null_attribute_data = "null"; const char *k_null_attribute_data = "null";
@@ -202,7 +201,10 @@ public:
assert(m_json_str); assert(m_json_str);
} }
~custom_encodable_type() { free(m_json_str); } ~custom_encodable_type()
{
free(m_json_str);
}
CHIP_ERROR EncodeTo(chip::TLV::TLVWriter &writer, chip::TLV::Tag tag) const override CHIP_ERROR EncodeTo(chip::TLV::TLVWriter &writer, chip::TLV::Tag tag) const override
{ {
@@ -215,15 +217,17 @@ private:
char *m_json_str = NULL; char *m_json_str = NULL;
}; };
class multiple_write_encodable_type class multiple_write_encodable_type {
{
public: public:
multiple_write_encodable_type(const char *json_str) multiple_write_encodable_type(const char *json_str)
{ {
json = cJSON_Parse(json_str); json = cJSON_Parse(json_str);
} }
~multiple_write_encodable_type() { cJSON_Delete(json); } ~multiple_write_encodable_type()
{
cJSON_Delete(json);
}
CHIP_ERROR EncodeTo(chip::TLV::TLVWriter &writer, chip::TLV::Tag tag, size_t index) CHIP_ERROR EncodeTo(chip::TLV::TLVWriter &writer, chip::TLV::Tag tag, size_t index)
{ {
@@ -242,7 +246,10 @@ public:
return CHIP_NO_ERROR; return CHIP_NO_ERROR;
} }
size_t GetJsonArraySize() { return static_cast<size_t>(cJSON_GetArraySize(json)); } size_t GetJsonArraySize()
{
return static_cast<size_t>(cJSON_GetArraySize(json));
}
private: private:
cJSON *json = NULL; cJSON *json = NULL;
@@ -269,7 +276,10 @@ public:
, context(ctx) , context(ctx)
{ {
} }
void set_on_done_callback(on_done_callback_t on_done) { on_done_cb = on_done; } void set_on_done_callback(on_done_callback_t on_done)
{
on_done_cb = on_done;
}
private: private:
void OnResponse(CommandSender *command_sender, const ConcreteCommandPath &command_path, const StatusIB &status, void OnResponse(CommandSender *command_sender, const ConcreteCommandPath &command_path, const StatusIB &status,
@@ -328,7 +338,6 @@ esp_err_t send_request(void *ctx, peer_device_t *remote_device, const CommandPat
const Optional<uint16_t> &timed_invoke_timeout_ms, const Optional<uint16_t> &timed_invoke_timeout_ms,
const Optional<Timeout> &response_timeout = chip::NullOptional); const Optional<Timeout> &response_timeout = chip::NullOptional);
esp_err_t send_group_request(const uint8_t fabric_index, const CommandPathParams &command_path, esp_err_t send_group_request(const uint8_t fabric_index, const CommandPathParams &command_path,
const chip::app::DataModel::EncodableToTLV &encodable); const chip::app::DataModel::EncodableToTLV &encodable);
+7 -9
View File
@@ -84,8 +84,7 @@ void PostEvent(uint16_t eventType)
VerifyOrReturn(error == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to post event for event type:%" PRIu16 ", err:%" CHIP_ERROR_FORMAT, eventType, error.Format())); VerifyOrReturn(error == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to post event for event type:%" PRIu16 ", err:%" CHIP_ERROR_FORMAT, eventType, error.Format()));
} }
class AppDelegateImpl : public AppDelegate class AppDelegateImpl : public AppDelegate {
{
public: public:
void OnCommissioningSessionStarted() void OnCommissioningSessionStarted()
{ {
@@ -108,8 +107,7 @@ public:
} }
}; };
class FabricDelegateImpl : public chip::FabricTable::Delegate class FabricDelegateImpl : public chip::FabricTable::Delegate {
{
public: public:
void FabricWillBeRemoved(const chip::FabricTable &fabricTable, chip::FabricIndex fabricIndex) void FabricWillBeRemoved(const chip::FabricTable &fabricTable, chip::FabricIndex fabricIndex)
{ {
@@ -220,8 +218,7 @@ static void esp_matter_chip_init_task(intptr_t context)
#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL #endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
CHIP_ERROR ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(&s_fabric_delegate); CHIP_ERROR ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(&s_fabric_delegate);
if (ret != CHIP_NO_ERROR) if (ret != CHIP_NO_ERROR) {
{
ESP_LOGE(TAG, "Failed to add fabric delegate, err:%" CHIP_ERROR_FORMAT, ret.Format()); ESP_LOGE(TAG, "Failed to add fabric delegate, err:%" CHIP_ERROR_FORMAT, ret.Format());
} }
ret = chip::Server::GetInstance().Init(initParams); ret = chip::Server::GetInstance().Init(initParams);
@@ -256,8 +253,7 @@ static void esp_matter_chip_init_task(intptr_t context)
static void device_callback_internal(const ChipDeviceEvent * event, intptr_t arg) static void device_callback_internal(const ChipDeviceEvent * event, intptr_t arg)
{ {
switch (event->Type) switch (event->Type) {
{
case chip::DeviceLayer::DeviceEventType::kInterfaceIpAddressChanged: case chip::DeviceLayer::DeviceEventType::kInterfaceIpAddressChanged:
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET #if CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET
if (event->InterfaceIpAddressChanged.Type == chip::DeviceLayer::InterfaceIpChangeType::kIpV6_Assigned || if (event->InterfaceIpAddressChanged.Type == chip::DeviceLayer::InterfaceIpChangeType::kIpV6_Assigned ||
@@ -393,7 +389,9 @@ esp_err_t start(event_callback_t callback, intptr_t callback_arg)
// If Thread is Provisioned, publish the dns service // If Thread is Provisioned, publish the dns service
if (chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned() && if (chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned() &&
(chip::Server::GetInstance().GetFabricTable().FabricCount() != 0)) { (chip::Server::GetInstance().GetFabricTable().FabricCount() != 0)) {
PlatformMgr().ScheduleWork([](intptr_t){ chip::app::DnssdServer::Instance().StartServer(); }, PlatformMgr().ScheduleWork([](intptr_t) {
chip::app::DnssdServer::Instance().StartServer();
},
reinterpret_cast<intptr_t>(nullptr)); reinterpret_cast<intptr_t>(nullptr));
} }
#endif // CONFIG_ESP_MATTER_ENABLE_OPENTHREAD #endif // CONFIG_ESP_MATTER_ENABLE_OPENTHREAD
+4 -2
View File
@@ -134,10 +134,12 @@ typedef enum status {
*/ */
class ScopedChipStackLock { class ScopedChipStackLock {
public: public:
ScopedChipStackLock(uint32_t ticks_to_wait) { ScopedChipStackLock(uint32_t ticks_to_wait)
{
status = chip_stack_lock(ticks_to_wait); status = chip_stack_lock(ticks_to_wait);
} }
~ScopedChipStackLock() { ~ScopedChipStackLock()
{
if (status == SUCCESS) { if (status == SUCCESS) {
chip_stack_unlock(); chip_stack_unlock();
} }
-1
View File
@@ -120,7 +120,6 @@ esp_err_t esp_matter_ota_requestor_encrypted_init(const char *key, uint16_t size
} }
#endif // CONFIG_ENABLE_ENCRYPTED_OTA #endif // CONFIG_ENABLE_ENCRYPTED_OTA
esp_err_t esp_matter_ota_requestor_set_config(const esp_matter_ota_config_t &config) esp_err_t esp_matter_ota_requestor_set_config(const esp_matter_ota_config_t &config)
{ {
#if CONFIG_ENABLE_OTA_REQUESTOR #if CONFIG_ENABLE_OTA_REQUESTOR
-2
View File
@@ -34,7 +34,6 @@ __attribute__((weak)) const SupportedModesManager * getSupportedModesManager(voi
} /* namespace Clusters */ } /* namespace Clusters */
} /* namespace ModeSelect */ } /* namespace ModeSelect */
// Provide weak defaults for attribute changed callbacks so apps // Provide weak defaults for attribute changed callbacks so apps
// Strong definitions in an app will override these. // Strong definitions in an app will override these.
@@ -51,4 +50,3 @@ __attribute__((weak)) void MatterClosureDimensionClusterServerAttributeChangedCa
ESP_LOGI(TAG, "Attribute Changed Callback: Endpoint: %d, Cluster: %ld, Attribute: %ld", ESP_LOGI(TAG, "Attribute Changed Callback: Endpoint: %d, Cluster: %ld, Attribute: %ld",
attributePath.mEndpointId, attributePath.mClusterId, attributePath.mAttributeId); attributePath.mEndpointId, attributePath.mClusterId, attributePath.mAttributeId);
} }
@@ -256,8 +256,9 @@ esp_err_t set_device_type(device_t *bridged_device, uint32_t device_type_id, voi
return ESP_ERR_INVALID_ARG; return ESP_ERR_INVALID_ARG;
} }
err = device_type_callback(bridged_device->endpoint, device_type_id, priv_data); err = device_type_callback(bridged_device->endpoint, device_type_id, priv_data);
if (err != ESP_OK) if (err != ESP_OK) {
return err; return err;
}
return plugin_init_callback_endpoint(bridged_device->endpoint); return plugin_init_callback_endpoint(bridged_device->endpoint);
} }
@@ -61,7 +61,8 @@ const device_type_handler device_handlers[] = {
{"temperature_sensor", ESP_MATTER_TEMPERATURE_SENSOR_DEVICE_TYPE_ID, ADD_DEVICE_FUN(temperature_sensor)}, {"temperature_sensor", ESP_MATTER_TEMPERATURE_SENSOR_DEVICE_TYPE_ID, ADD_DEVICE_FUN(temperature_sensor)},
}; };
static bool is_device_type_supported(uint32_t device_type_id) { static bool is_device_type_supported(uint32_t device_type_id)
{
for (const auto &handler : device_handlers) { for (const auto &handler : device_handlers) {
if (handler.device_type_id == device_type_id) { if (handler.device_type_id == device_type_id) {
return true; return true;
@@ -274,7 +275,8 @@ esp_err_t bridge_register_commands()
.name = "reset", .name = "reset",
.description = "reset bridge. Usage: matter esp bridge reset.", .description = "reset bridge. Usage: matter esp bridge reset.",
.handler = reset_bridge_handler, .handler = reset_bridge_handler,
}}; }
};
bridge_console.register_commands(bridge_commands, sizeof(bridge_commands) / sizeof(command_t)); bridge_console.register_commands(bridge_commands, sizeof(bridge_commands) / sizeof(command_t));
return add_commands(&command, 1); return add_commands(&command, 1);
} }
@@ -88,7 +88,6 @@ esp_err_t print_description(const command_t *command, void *arg)
return ESP_OK; return ESP_OK;
} }
static esp_err_t help_handler(int argc, char **argv) static esp_err_t help_handler(int argc, char **argv)
{ {
base_engine.for_each_command(print_description, NULL); base_engine.for_each_command(print_description, NULL);
@@ -50,8 +50,7 @@ typedef struct {
*/ */
typedef esp_err_t command_iterator_t(const command_t *command, void *arg); typedef esp_err_t command_iterator_t(const command_t *command, void *arg);
class engine class engine {
{
protected: protected:
const command_t *_command_set[CONSOLE_MAX_COMMAND_SETS]; const command_t *_command_set[CONSOLE_MAX_COMMAND_SETS];
unsigned _command_set_size[CONSOLE_MAX_COMMAND_SETS]; unsigned _command_set_size[CONSOLE_MAX_COMMAND_SETS];
@@ -215,5 +215,3 @@ esp_err_t attribute_register_commands()
} // namespace console } // namespace console
} // namespace esp_matter } // namespace esp_matter
@@ -102,7 +102,8 @@ void paa_der_cert_iterator::release()
esp_err_t spiffs_attestation_trust_store::init() esp_err_t spiffs_attestation_trust_store::init()
{ {
esp_vfs_spiffs_conf_t conf = { esp_vfs_spiffs_conf_t conf = {
.base_path = "/paa", .partition_label = nullptr, .max_files = 5, .format_if_mount_failed = false}; .base_path = "/paa", .partition_label = nullptr, .max_files = 5, .format_if_mount_failed = false
};
ESP_RETURN_ON_ERROR(esp_vfs_spiffs_register(&conf), TAG, "Failed to initialize SPIFFS"); ESP_RETURN_ON_ERROR(esp_vfs_spiffs_register(&conf), TAG, "Failed to initialize SPIFFS");
size_t total = 0, used = 0; size_t total = 0, used = 0;
ESP_RETURN_ON_ERROR(esp_spiffs_info(conf.partition_label, &total, &used), TAG, "Failed to get SPIFFS info"); ESP_RETURN_ON_ERROR(esp_spiffs_info(conf.partition_label, &total, &used), TAG, "Failed to get SPIFFS info");
@@ -31,8 +31,14 @@ typedef struct paa_der_cert {
class paa_der_cert_iterator { class paa_der_cert_iterator {
public: public:
paa_der_cert_iterator(const char *path); paa_der_cert_iterator(const char *path);
~paa_der_cert_iterator() { release(); }; ~paa_der_cert_iterator()
size_t count() { return m_count; } {
release();
};
size_t count()
{
return m_count;
}
bool next(paa_der_cert_t &item); bool next(paa_der_cert_t &item);
void release(); void release();
@@ -84,7 +90,10 @@ public:
CHIP_ERROR GetProductAttestationAuthorityCert(const ByteSpan &skid, CHIP_ERROR GetProductAttestationAuthorityCert(const ByteSpan &skid,
MutableByteSpan &outPaaDerBuffer) const override; MutableByteSpan &outPaaDerBuffer) const override;
void SetDCLNetType(dcl_net_type_t type) { dcl_net_type = type; } void SetDCLNetType(dcl_net_type_t type)
{
dcl_net_type = type;
}
private: private:
dcl_net_type_t dcl_net_type = DCL_MAIN_NET; dcl_net_type_t dcl_net_type = DCL_MAIN_NET;
@@ -147,7 +147,8 @@ void cluster_command::on_device_connected_fcn(void *context, ExchangeManager &ex
cluster_command *cmd = reinterpret_cast<cluster_command *>(context); cluster_command *cmd = reinterpret_cast<cluster_command *>(context);
chip::OperationalDeviceProxy device_proxy(&exchangeMgr, sessionHandle); chip::OperationalDeviceProxy device_proxy(&exchangeMgr, sessionHandle);
chip::app::CommandPathParams command_path = {cmd->m_endpoint_id, 0, cmd->m_cluster_id, cmd->m_command_id, chip::app::CommandPathParams command_path = {cmd->m_endpoint_id, 0, cmd->m_cluster_id, cmd->m_command_id,
chip::app::CommandPathFlags::kEndpointIdValid}; chip::app::CommandPathFlags::kEndpointIdValid
};
interaction::invoke::send_request(context, &device_proxy, command_path, cmd->m_command_data_field, interaction::invoke::send_request(context, &device_proxy, command_path, cmd->m_command_data_field,
cmd->on_success_cb, cmd->on_error_cb, cmd->m_timed_invoke_timeout_ms); cmd->on_success_cb, cmd->on_error_cb, cmd->m_timed_invoke_timeout_ms);
chip::Platform::Delete(cmd); chip::Platform::Delete(cmd);
@@ -166,11 +167,11 @@ void cluster_command::default_success_fcn(void *ctx, const ConcreteCommandPath &
{ {
ESP_LOGI(TAG, "Send command success"); ESP_LOGI(TAG, "Send command success");
ESP_LOGI(TAG, ESP_LOGI(TAG,
"Some commands of specific clusters will have a reponse which is not NullObject, so we need to handle the " "Some commands of specific clusters will have a response which is not NullObject, so we need to handle the "
"response data for those commands. Here we print the reponse data."); "response data for those commands. Here we print the response data.");
ESP_LOGI(TAG, ESP_LOGI(TAG,
"If your command's reponse is not printed here, please register another success callback when creating " "If your command's response is not printed here, please register another success callback when creating "
"the cluster_command object to handle the reponse data."); "the cluster_command object to handle the response data.");
switch (command_path.mClusterId) { switch (command_path.mClusterId) {
case GroupKeyManagement::Id: case GroupKeyManagement::Id:
cluster::group_key_management::command::decode_response(command_path, response_data); cluster::group_key_management::command::decode_response(command_path, response_data);
@@ -208,7 +209,8 @@ esp_err_t cluster_command::dispatch_group_command(void *context)
uint8_t fabric_index = matter_controller_client::get_instance().get_fabric_index(); uint8_t fabric_index = matter_controller_client::get_instance().get_fabric_index();
#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER #endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
chip::app::CommandPathParams command_path = {cmd->m_endpoint_id, group_id, cmd->m_cluster_id, cmd->m_command_id, chip::app::CommandPathParams command_path = {cmd->m_endpoint_id, group_id, cmd->m_cluster_id, cmd->m_command_id,
chip::app::CommandPathFlags::kGroupIdValid}; chip::app::CommandPathFlags::kGroupIdValid
};
err = interaction::invoke::send_group_request(fabric_index, command_path, cmd->m_command_data_field); err = interaction::invoke::send_group_request(fabric_index, command_path, cmd->m_command_data_field);
chip::Platform::Delete(cmd); chip::Platform::Delete(cmd);
return err; return err;
@@ -58,7 +58,10 @@ public:
esp_err_t send_command(); esp_err_t send_command();
bool is_group_command() { return chip::IsGroupId(m_destination_id); } bool is_group_command()
{
return chip::IsGroupId(m_destination_id);
}
private: private:
uint64_t m_destination_id; uint64_t m_destination_id;
@@ -44,7 +44,7 @@ esp_err_t commissioning_window_opener::send_open_commissioning_window_command(ui
return ESP_ERR_INVALID_ARG; return ESP_ERR_INVALID_ARG;
} }
m_is_enhanced = is_enhanced; m_is_enhanced = is_enhanced;
m_timout = timeout; m_timeout = timeout;
m_iteration = iteration; m_iteration = iteration;
m_discriminator = discriminator; m_discriminator = discriminator;
m_timed_invoke_timeout_ms = timed_invoke_timeout_ms; m_timed_invoke_timeout_ms = timed_invoke_timeout_ms;
@@ -125,7 +125,7 @@ void commissioning_window_opener::on_device_connected_fcn(void *context, Exchang
return; return;
} }
AdministratorCommissioning::Commands::OpenCommissioningWindow::Type command_data; AdministratorCommissioning::Commands::OpenCommissioningWindow::Type command_data;
command_data.commissioningTimeout = window_opener->m_timout; command_data.commissioningTimeout = window_opener->m_timeout;
command_data.PAKEPasscodeVerifier = serialized_verifier_span; command_data.PAKEPasscodeVerifier = serialized_verifier_span;
command_data.discriminator = window_opener->m_discriminator; command_data.discriminator = window_opener->m_discriminator;
command_data.iterations = window_opener->m_iteration; command_data.iterations = window_opener->m_iteration;
@@ -136,7 +136,7 @@ void commissioning_window_opener::on_device_connected_fcn(void *context, Exchang
chip::MakeOptional(window_opener->m_timed_invoke_timeout_ms)); chip::MakeOptional(window_opener->m_timed_invoke_timeout_ms));
} else { } else {
AdministratorCommissioning::Commands::OpenBasicCommissioningWindow::Type command_data; AdministratorCommissioning::Commands::OpenBasicCommissioningWindow::Type command_data;
command_data.commissioningTimeout = window_opener->m_timout; command_data.commissioningTimeout = window_opener->m_timeout;
chip::Controller::ClusterBase cluster(exchangeMgr, sessionHandle, window_opener->m_default_remote_endpoint_id); chip::Controller::ClusterBase cluster(exchangeMgr, sessionHandle, window_opener->m_default_remote_endpoint_id);
cluster.InvokeCommand(command_data, window_opener, send_command_success_callback, send_command_failure_callback, cluster.InvokeCommand(command_data, window_opener, send_command_success_callback, send_command_failure_callback,
chip::MakeOptional(window_opener->m_timed_invoke_timeout_ms)); chip::MakeOptional(window_opener->m_timed_invoke_timeout_ms));
@@ -148,7 +148,7 @@ void commissioning_window_opener::on_device_connection_failure_fcn(void *context
{ {
commissioning_window_opener *window_opener = reinterpret_cast<commissioning_window_opener *>(context); commissioning_window_opener *window_opener = reinterpret_cast<commissioning_window_opener *>(context);
if (window_opener) { if (window_opener) {
ESP_LOGE(TAG, "Failed to establish CASE session for open %s commisioning window command", ESP_LOGE(TAG, "Failed to establish CASE session for open %s commissioning window command",
window_opener->m_is_enhanced ? "enhanced" : "basic"); window_opener->m_is_enhanced ? "enhanced" : "basic");
} }
} }
@@ -176,7 +176,7 @@ void commissioning_window_opener::send_command_failure_callback(void *context, C
{ {
commissioning_window_opener *window_opener = reinterpret_cast<commissioning_window_opener *>(context); commissioning_window_opener *window_opener = reinterpret_cast<commissioning_window_opener *>(context);
if (window_opener) { if (window_opener) {
ESP_LOGE(TAG, "Failed to send open %s commisioning window command", ESP_LOGE(TAG, "Failed to send open %s commissioning window command",
window_opener->m_is_enhanced ? "enhanced" : "basic"); window_opener->m_is_enhanced ? "enhanced" : "basic");
} }
} }
@@ -38,7 +38,10 @@ public:
return instance; return instance;
} }
void set_callback(commissioning_window_open_callback_t callback) { m_callback = callback; } void set_callback(commissioning_window_open_callback_t callback)
{
m_callback = callback;
}
esp_err_t send_open_commissioning_window_command(uint64_t node_id, bool is_enhanced, uint16_t timeout, esp_err_t send_open_commissioning_window_command(uint64_t node_id, bool is_enhanced, uint16_t timeout,
uint32_t iteration, uint16_t discriminator, uint32_t iteration, uint16_t discriminator,
@@ -68,7 +71,7 @@ private:
uint32_t m_discriminator = 0; uint32_t m_discriminator = 0;
bool m_is_enhanced = false; bool m_is_enhanced = false;
uint32_t m_pincode = 0; uint32_t m_pincode = 0;
uint16_t m_timout = 0; uint16_t m_timeout = 0;
uint32_t m_iteration = 0; uint32_t m_iteration = 0;
uint16_t m_timed_invoke_timeout_ms = 0; uint16_t m_timed_invoke_timeout_ms = 0;
commissioning_window_open_callback_t m_callback = nullptr; commissioning_window_open_callback_t m_callback = nullptr;
@@ -68,9 +68,15 @@ public:
return s_instance; return s_instance;
} }
void set_callbacks(pairing_command_callbacks_t callbacks) { m_callbacks = callbacks; } void set_callbacks(pairing_command_callbacks_t callbacks)
{
m_callbacks = callbacks;
}
void set_icd_registration(bool icd_registration) { m_icd_registration = icd_registration; } void set_icd_registration(bool icd_registration)
{
m_icd_registration = icd_registration;
}
/** /**
* Pairing a Matter end-device on the same IP network * Pairing a Matter end-device on the same IP network
@@ -54,8 +54,9 @@ void subscribe_command::on_device_connection_failure_fcn(void *context, const Sc
{ {
subscribe_command *cmd = (subscribe_command *)context; subscribe_command *cmd = (subscribe_command *)context;
if (cmd->subscribe_failure_cb) if (cmd->subscribe_failure_cb) {
cmd->subscribe_failure_cb((void *)cmd); cmd->subscribe_failure_cb((void *)cmd);
}
chip::Platform::Delete(cmd); chip::Platform::Delete(cmd);
return; return;
@@ -120,7 +120,10 @@ public:
CHIP_ERROR OnResubscriptionNeeded(ReadClient *apReadClient, CHIP_ERROR aTerminationCause) override; CHIP_ERROR OnResubscriptionNeeded(ReadClient *apReadClient, CHIP_ERROR aTerminationCause) override;
uint32_t get_subscription_id() { return m_subscription_id; } uint32_t get_subscription_id()
{
return m_subscription_id;
}
private: private:
uint64_t m_node_id; uint64_t m_node_id;
@@ -200,7 +203,7 @@ esp_err_t send_subscribe_event_command(uint64_t node_id, ScopedMemoryBufferWithS
* @param[in] node_id Remote NodeId * @param[in] node_id Remote NodeId
* @param[in] endpoint_id EndpointId of the attribute path * @param[in] endpoint_id EndpointId of the attribute path
* @param[in] cluster_id ClusterId of the attribute path * @param[in] cluster_id ClusterId of the attribute path
* @param[in] attribute_id AttributeId of the attribue path * @param[in] attribute_id AttributeId of the attribute path
* @param[in] min_interval Minimum interval of the subscription * @param[in] min_interval Minimum interval of the subscription
* @param[in] max_interval Maximum interval of the subscription * @param[in] max_interval Maximum interval of the subscription
* @param[in] auto_resubscribe Auto re-subscribe flag * @param[in] auto_resubscribe Auto re-subscribe flag
@@ -170,7 +170,10 @@ public:
} }
esp_err_t init(NodeId node_id, FabricId fabric_id, uint16_t listen_port); esp_err_t init(NodeId node_id, FabricId fabric_id, uint16_t listen_port);
chip::app::DefaultICDClientStorage &get_icd_client_storage() { return m_icd_client_storage; } chip::app::DefaultICDClientStorage &get_icd_client_storage()
{
return m_icd_client_storage;
}
void set_icd_client_callback(controller_check_in_delegate::check_in_complete_callback check_in_complete_cb, void set_icd_client_callback(controller_check_in_delegate::check_in_complete_callback check_in_complete_cb,
controller_check_in_delegate::key_refresh_done_callback key_refresh_done_cb) controller_check_in_delegate::key_refresh_done_callback key_refresh_done_cb)
{ {
@@ -179,17 +182,26 @@ public:
#ifdef CONFIG_ESP_MATTER_COMMISSIONER_ENABLE #ifdef CONFIG_ESP_MATTER_COMMISSIONER_ENABLE
esp_err_t setup_commissioner(); esp_err_t setup_commissioner();
MatterDeviceCommissioner *get_commissioner() { return &m_device_commissioner; } MatterDeviceCommissioner *get_commissioner()
{
return &m_device_commissioner;
}
esp_err_t unpair(NodeId remote_node, remove_fabric_callback callback = nullptr) esp_err_t unpair(NodeId remote_node, remove_fabric_callback callback = nullptr)
{ {
return auto_fabric_remover::remove_fabric(&m_device_commissioner, remote_node, callback); return auto_fabric_remover::remove_fabric(&m_device_commissioner, remote_node, callback);
} }
#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
CommissionerDiscoveryController *get_discovery_controller() { return &m_commissioner_discovery_controller; } CommissionerDiscoveryController *get_discovery_controller()
{
return &m_commissioner_discovery_controller;
}
#endif #endif
#else #else
esp_err_t setup_controller(chip::MutableByteSpan &ipk); esp_err_t setup_controller(chip::MutableByteSpan &ipk);
MatterDeviceController *get_controller() { return &m_device_controller; } MatterDeviceController *get_controller()
{
return &m_device_controller;
}
#endif #endif
chip::FabricIndex get_fabric_index() chip::FabricIndex get_fabric_index()
{ {
@@ -25,7 +25,10 @@ class example_credentials_issuer : public credentials_issuer {
return m_operational_creds_issuer.Initialize(storage) == CHIP_NO_ERROR ? ESP_OK : ESP_FAIL; return m_operational_creds_issuer.Initialize(storage) == CHIP_NO_ERROR ? ESP_OK : ESP_FAIL;
} }
chip::Controller::OperationalCredentialsDelegate *get_delegate() override { return &m_operational_creds_issuer; } chip::Controller::OperationalCredentialsDelegate *get_delegate() override
{
return &m_operational_creds_issuer;
}
esp_err_t generate_controller_noc_chain(chip::NodeId node_id, chip::FabricId fabric_id, esp_err_t generate_controller_noc_chain(chip::NodeId node_id, chip::FabricId fabric_id,
chip::Crypto::P256Keypair &keypair, chip::MutableByteSpan &rcac, chip::Crypto::P256Keypair &keypair, chip::MutableByteSpan &rcac,
@@ -76,7 +76,10 @@ public:
return instance; return instance;
} }
CHIP_ERROR Shutdown() override { return CHIP_NO_ERROR; } CHIP_ERROR Shutdown() override
{
return CHIP_NO_ERROR;
}
ActionReturnStatus ReadAttribute(const ReadAttributeRequest &request, AttributeValueEncoder &encoder) override ActionReturnStatus ReadAttribute(const ReadAttributeRequest &request, AttributeValueEncoder &encoder) override
{ {
@@ -51,7 +51,10 @@ public:
strncpy(mOtaImageUrl, otaImageUrl, strnlen(otaImageUrl, OTA_URL_MAX_LEN)); strncpy(mOtaImageUrl, otaImageUrl, strnlen(otaImageUrl, OTA_URL_MAX_LEN));
} }
const char *GetOtaImageUrl() const { return mOtaImageUrl; } const char *GetOtaImageUrl() const
{
return mOtaImageUrl;
}
private: private:
void HandleTransferSessionOutput(chip::bdx::TransferSession::OutputEvent &event) override; void HandleTransferSessionOutput(chip::bdx::TransferSession::OutputEvent &event) override;
@@ -75,10 +75,22 @@ public:
} }
esp_err_t Init(bool otaAllowedDefault, chip::System::Layer *system_layer, esp_err_t Init(bool otaAllowedDefault, chip::System::Layer *system_layer,
chip::Messaging::ExchangeManager *exchange_mgr, chip::FabricTable *fabric_table); chip::Messaging::ExchangeManager *exchange_mgr, chip::FabricTable *fabric_table);
void SetApplyUpdateAction(OTAApplyUpdateAction action) { mUpdateAction = action; } void SetApplyUpdateAction(OTAApplyUpdateAction action)
void SetDelayedQueryActionTimeSec(uint32_t time) { mDelayedQueryActionTimeSec = time; } {
void SetDelayedApplyActionTimeSec(uint32_t time) { mDelayedApplyActionTimeSec = time; } mUpdateAction = action;
void SetPollInterval(uint32_t interval) { mPollInterval = (interval != 0) ? interval : mPollInterval; } }
void SetDelayedQueryActionTimeSec(uint32_t time)
{
mDelayedQueryActionTimeSec = time;
}
void SetDelayedApplyActionTimeSec(uint32_t time)
{
mDelayedApplyActionTimeSec = time;
}
void SetPollInterval(uint32_t interval)
{
mPollInterval = (interval != 0) ? interval : mPollInterval;
}
static void FetchImageDoneCallback(OTAQueryStatus status, const char *imageUrl, size_t imageSize, static void FetchImageDoneCallback(OTAQueryStatus status, const char *imageUrl, size_t imageSize,
uint32_t softwareVersion, const char *softwareVersionStr, void *arg); uint32_t softwareVersion, const char *softwareVersionStr, void *arg);
@@ -86,7 +98,10 @@ public:
// When the OTA Provider receives a QueryImage command from an OTA Requestor and there is no existing entry for the // When the OTA Provider receives a QueryImage command from an OTA Requestor and there is no existing entry for the
// Requestor node, the Provider will create an OTA Requestor Entry for the requestor, and set the entry's // Requestor node, the Provider will create an OTA Requestor Entry for the requestor, and set the entry's
// mOtaAllowed to mOtaAllowedDefault. // mOtaAllowed to mOtaAllowedDefault.
void SetOtaAllowedDefault(bool otaAllowed) { mOtaAllowedDefault = otaAllowed; } void SetOtaAllowedDefault(bool otaAllowed)
{
mOtaAllowedDefault = otaAllowed;
}
// When there is a Requestor entry for the nodeId, we can call the EnableOtaForNode/DisableOtaForNode to make the // When there is a Requestor entry for the nodeId, we can call the EnableOtaForNode/DisableOtaForNode to make the
// provider allow whether the requestor proceed the OTA process. // provider allow whether the requestor proceed the OTA process.
esp_err_t EnableOtaForNode(const chip::ScopedNodeId &nodeId, bool forOnlyOnce); esp_err_t EnableOtaForNode(const chip::ScopedNodeId &nodeId, bool forOnlyOnce);
@@ -462,7 +462,8 @@ esp_err_t init_ota_candidates()
// start a timer which will update the candidates cache everyday. // start a timer which will update the candidates cache everyday.
esp_timer_init(); esp_timer_init();
const esp_timer_create_args_t timer_args = { const esp_timer_create_args_t timer_args = {
.callback = _ota_candidates_periodic_update_handler, .arg = nullptr, .name = "ota_candidates_update_timer"}; .callback = _ota_candidates_periodic_update_handler, .arg = nullptr, .name = "ota_candidates_update_timer"
};
esp_timer_create(&timer_args, &_ota_candidates_update_timer); esp_timer_create(&timer_args, &_ota_candidates_update_timer);
esp_timer_start_periodic(_ota_candidates_update_timer, esp_timer_start_periodic(_ota_candidates_update_timer,
(uint64_t)CONFIG_ESP_MATTER_OTA_CANDIDATES_UPDATE_PERIOD * 3600 * 1000 * 1000); (uint64_t)CONFIG_ESP_MATTER_OTA_CANDIDATES_UPDATE_PERIOD * 3600 * 1000 * 1000);
@@ -408,8 +408,7 @@ static esp_err_t custom_cluster_create()
return ESP_OK; return ESP_OK;
} }
class RainmakerAttrAccess : public AttributeAccessInterface class RainmakerAttrAccess : public AttributeAccessInterface {
{
public: public:
// Register for the RainMaker cluster on endpoint 0. // Register for the RainMaker cluster on endpoint 0.
RainmakerAttrAccess() : AttributeAccessInterface(chip::Optional<chip::EndpointId>(cluster::rainmaker::endpoint_id), RainmakerAttrAccess() : AttributeAccessInterface(chip::Optional<chip::EndpointId>(cluster::rainmaker::endpoint_id),
@@ -425,12 +424,10 @@ public:
ConcreteDataAttributePath challengeAttrPath(cluster::rainmaker::endpoint_id, cluster::rainmaker::Id, ConcreteDataAttributePath challengeAttrPath(cluster::rainmaker::endpoint_id, cluster::rainmaker::Id,
cluster::rainmaker::attribute::challenge::Id); cluster::rainmaker::attribute::challenge::Id);
if (challengeAttrPath.MatchesConcreteAttributePath(aPath)) if (challengeAttrPath.MatchesConcreteAttributePath(aPath)) {
{
chip::CharSpan challenge; chip::CharSpan challenge;
CHIP_ERROR c_err = aDecoder.Decode(challenge); CHIP_ERROR c_err = aDecoder.Decode(challenge);
if (c_err != CHIP_NO_ERROR) if (c_err != CHIP_NO_ERROR) {
{
ESP_LOGE(TAG, "Failed to decode challenge, err:%" CHIP_ERROR_FORMAT, c_err.Format()); ESP_LOGE(TAG, "Failed to decode challenge, err:%" CHIP_ERROR_FORMAT, c_err.Format());
return c_err; return c_err;
} }
@@ -21,7 +21,6 @@
#define LED_CHANNEL 0 /* RMT_CHANNEL_0 */ #define LED_CHANNEL 0 /* RMT_CHANNEL_0 */
#define BUTTON_GPIO_PIN GPIO_NUM_9 #define BUTTON_GPIO_PIN GPIO_NUM_9
led_driver_config_t led_driver_get_config() led_driver_config_t led_driver_get_config()
{ {
led_driver_config_t config = { led_driver_config_t config = {
+20 -7
View File
@@ -83,7 +83,8 @@ const HS_color_t temp_table[] = {
{0, 0}, {294, 2}, {265, 3}, {251, 4}, {242, 5}, {237, 6}, {233, 7}, {231, 8}, {229, 9}, {228, 10}, {0, 0}, {294, 2}, {265, 3}, {251, 4}, {242, 5}, {237, 6}, {233, 7}, {231, 8}, {229, 9}, {228, 10},
{227, 11}, {226, 11}, {226, 12}, {225, 13}, {225, 13}, {224, 14}, {224, 14}, {224, 15}, {224, 15}, {223, 16}, {227, 11}, {226, 11}, {226, 12}, {225, 13}, {225, 13}, {224, 14}, {224, 14}, {224, 15}, {224, 15}, {223, 16},
{223, 16}, {223, 17}, {223, 17}, {223, 17}, {222, 18}, {222, 18}, {222, 19}, {222, 19}, {222, 19}, {222, 19}, {223, 16}, {223, 17}, {223, 17}, {223, 17}, {222, 18}, {222, 18}, {222, 19}, {222, 19}, {222, 19}, {222, 19},
{222, 20}, {222, 20}, {222, 20}, {222, 21}, {222, 21}}; {222, 20}, {222, 20}, {222, 20}, {222, 21}, {222, 21}
};
void temp_to_hs(uint32_t temperature, HS_color_t *HS) void temp_to_hs(uint32_t temperature, HS_color_t *HS)
{ {
@@ -146,12 +147,24 @@ void xy_to_rgb(XY_color_t XY, uint8_t brightness, RGB_color_t *RGB)
} }
// Clamp values to [0, 1] range // Clamp values to [0, 1] range
if (r < 0.0f) r = 0.0f; if (r < 0.0f) {
if (r > 1.0f) r = 1.0f; r = 0.0f;
if (g < 0.0f) g = 0.0f; }
if (g > 1.0f) g = 1.0f; if (r > 1.0f) {
if (b < 0.0f) b = 0.0f; r = 1.0f;
if (b > 1.0f) b = 1.0f; }
if (g < 0.0f) {
g = 0.0f;
}
if (g > 1.0f) {
g = 1.0f;
}
if (b < 0.0f) {
b = 0.0f;
}
if (b > 1.0f) {
b = 1.0f;
}
// Convert to 0-255 range // Convert to 0-255 range
RGB->red = (uint8_t)(r * 255.0f); RGB->red = (uint8_t)(r * 255.0f);
+6 -2
View File
@@ -155,8 +155,12 @@ esp_err_t led_driver_set_power(led_driver_handle_t handle, bool power)
esp_err_t led_driver_set_RGB(led_driver_handle_t handle) esp_err_t led_driver_set_RGB(led_driver_handle_t handle)
{ {
TFT_fillWindow(TFT_BLACK); TFT_fillWindow(TFT_BLACK);
TFT_fillCircle(DisplayWidth / 2, DisplayHeight / 2, DisplayWidth / 4, (color_t){mRGB.red, mRGB.green, mRGB.blue}); TFT_fillCircle(DisplayWidth / 2, DisplayHeight / 2, DisplayWidth / 4, (color_t) {
TFT_drawCircle(DisplayWidth / 2, DisplayHeight / 2, DisplayWidth / 4, (color_t){255, 255, 255}); mRGB.red, mRGB.green, mRGB.blue
});
TFT_drawCircle(DisplayWidth / 2, DisplayHeight / 2, DisplayWidth / 4, (color_t) {
255, 255, 255
});
return ESP_OK; return ESP_OK;
} }
@@ -58,10 +58,11 @@ chip::Protocols::InteractionModel::Status FanDelegateImpl::HandleStep(chip::app:
ESP_LOGI(TAG, "Step received value: %d %d %d", (uint8_t)aDirection, aWrap, aLowestOff); ESP_LOGI(TAG, "Step received value: %d %d %d", (uint8_t)aDirection, aWrap, aLowestOff);
/* Update percent-setting when speed is changed by the step command */ /* Update percent-setting when speed is changed by the step command */
if (aLowestOff) if (aLowestOff) {
lowest = 0; lowest = 0;
else } else {
lowest = 1; lowest = 1;
}
if ((uint8_t)aDirection == 0) { if ((uint8_t)aDirection == 0) {
tmp += 1; tmp += 1;
if (aWrap == 0) { if (aWrap == 0) {
@@ -299,4 +300,3 @@ esp_err_t app_driver_init()
return err; return err;
} }
@@ -108,22 +108,18 @@ static void app_event_cb(const ChipDeviceEvent *event, intptr_t arg)
ESP_LOGI(TAG, "Commissioning window closed"); ESP_LOGI(TAG, "Commissioning window closed");
break; break;
case chip::DeviceLayer::DeviceEventType::kFabricRemoved: case chip::DeviceLayer::DeviceEventType::kFabricRemoved: {
{
ESP_LOGI(TAG, "Fabric removed successfully"); ESP_LOGI(TAG, "Fabric removed successfully");
if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) {
{
chip::CommissioningWindowManager &commissionMgr = chip::Server::GetInstance().GetCommissioningWindowManager(); chip::CommissioningWindowManager &commissionMgr = chip::Server::GetInstance().GetCommissioningWindowManager();
constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds16(k_timeout_seconds); constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds16(k_timeout_seconds);
if (!commissionMgr.IsCommissioningWindowOpen()) if (!commissionMgr.IsCommissioningWindowOpen()) {
{
/* After removing last fabric, this example does not remove the Wi-Fi credentials /* After removing last fabric, this example does not remove the Wi-Fi credentials
* and still has IP connectivity so, only advertising on DNS-SD. * and still has IP connectivity so, only advertising on DNS-SD.
*/ */
CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds, CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds,
chip::CommissioningWindowAdvertisement::kDnssdOnly); chip::CommissioningWindowAdvertisement::kDnssdOnly);
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ESP_LOGE(TAG, "Failed to open commissioning window, err:%" CHIP_ERROR_FORMAT, err.Format()); ESP_LOGE(TAG, "Failed to open commissioning window, err:%" CHIP_ERROR_FORMAT, err.Format());
} }
} }
@@ -138,8 +138,7 @@ esp_err_t app_driver_init();
#endif // CONFIG_OPENTHREAD_BORDER_ROUTER #endif // CONFIG_OPENTHREAD_BORDER_ROUTER
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S3 #if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S3
class FanDelegateImpl:public chip::app::Clusters::FanControl::Delegate class FanDelegateImpl: public chip::app::Clusters::FanControl::Delegate {
{
public: public:
// Constructor to match the base class design, however endpoint_id set here is not being using at all. // Constructor to match the base class design, however endpoint_id set here is not being using at all.
// FanControlDelegateInitCB sets the delegate on correct endpoint while initialization. // FanControlDelegateInitCB sets the delegate on correct endpoint while initialization.
@@ -430,14 +430,12 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetPowerMode(PowerModeEnum newVal
{ {
PowerModeEnum oldValue = mPowerMode; PowerModeEnum oldValue = mPowerMode;
if (EnsureKnownEnumValue(newValue) == PowerModeEnum::kUnknownEnumValue) if (EnsureKnownEnumValue(newValue) == PowerModeEnum::kUnknownEnumValue) {
{
return CHIP_IM_GLOBAL_STATUS(ConstraintError); return CHIP_IM_GLOBAL_STATUS(ConstraintError);
} }
mPowerMode = newValue; mPowerMode = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
ChipLogDetail(AppServer, "mPowerMode updated to %d", static_cast<int>(mPowerMode)); ChipLogDetail(AppServer, "mPowerMode updated to %d", static_cast<int>(mPowerMode));
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, PowerMode::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, PowerMode::Id);
} }
@@ -450,8 +448,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetVoltage(DataModel::Nullable<in
DataModel::Nullable<int64_t> oldValue = mVoltage; DataModel::Nullable<int64_t> oldValue = mVoltage;
mVoltage = newValue; mVoltage = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, Voltage::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, Voltage::Id);
} }
@@ -464,8 +461,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetActiveCurrent(DataModel::Nulla
DataModel::Nullable<int64_t> oldValue = mActiveCurrent; DataModel::Nullable<int64_t> oldValue = mActiveCurrent;
mActiveCurrent = newValue; mActiveCurrent = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ActiveCurrent::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ActiveCurrent::Id);
} }
@@ -478,8 +474,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetReactiveCurrent(DataModel::Nul
DataModel::Nullable<int64_t> oldValue = mReactiveCurrent; DataModel::Nullable<int64_t> oldValue = mReactiveCurrent;
mReactiveCurrent = newValue; mReactiveCurrent = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ReactiveCurrent::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ReactiveCurrent::Id);
} }
@@ -492,8 +487,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetApparentCurrent(DataModel::Nul
DataModel::Nullable<int64_t> oldValue = mApparentCurrent; DataModel::Nullable<int64_t> oldValue = mApparentCurrent;
mApparentCurrent = newValue; mApparentCurrent = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ApparentCurrent::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ApparentCurrent::Id);
} }
@@ -506,8 +500,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetActivePower(DataModel::Nullabl
DataModel::Nullable<int64_t> oldValue = mActivePower; DataModel::Nullable<int64_t> oldValue = mActivePower;
mActivePower = newValue; mActivePower = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ActivePower::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ActivePower::Id);
} }
@@ -520,8 +513,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetReactivePower(DataModel::Nulla
DataModel::Nullable<int64_t> oldValue = mReactivePower; DataModel::Nullable<int64_t> oldValue = mReactivePower;
mReactivePower = newValue; mReactivePower = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ReactivePower::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ReactivePower::Id);
} }
@@ -534,8 +526,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetApparentPower(DataModel::Nulla
DataModel::Nullable<int64_t> oldValue = mApparentPower; DataModel::Nullable<int64_t> oldValue = mApparentPower;
mApparentPower = newValue; mApparentPower = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ApparentPower::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, ApparentPower::Id);
} }
@@ -548,8 +539,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetRMSVoltage(DataModel::Nullable
DataModel::Nullable<int64_t> oldValue = mRMSVoltage; DataModel::Nullable<int64_t> oldValue = mRMSVoltage;
mRMSVoltage = newValue; mRMSVoltage = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, RMSVoltage::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, RMSVoltage::Id);
} }
@@ -562,8 +552,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetRMSCurrent(DataModel::Nullable
DataModel::Nullable<int64_t> oldValue = mRMSCurrent; DataModel::Nullable<int64_t> oldValue = mRMSCurrent;
mRMSCurrent = newValue; mRMSCurrent = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, RMSCurrent::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, RMSCurrent::Id);
} }
@@ -576,8 +565,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetRMSPower(DataModel::Nullable<i
DataModel::Nullable<int64_t> oldValue = mRMSPower; DataModel::Nullable<int64_t> oldValue = mRMSPower;
mRMSPower = newValue; mRMSPower = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, RMSPower::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, RMSPower::Id);
} }
@@ -590,8 +578,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetFrequency(DataModel::Nullable<
DataModel::Nullable<int64_t> oldValue = mFrequency; DataModel::Nullable<int64_t> oldValue = mFrequency;
mFrequency = newValue; mFrequency = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, Frequency::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, Frequency::Id);
} }
@@ -604,8 +591,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetPowerFactor(DataModel::Nullabl
DataModel::Nullable<int64_t> oldValue = mPowerFactor; DataModel::Nullable<int64_t> oldValue = mPowerFactor;
mPowerFactor = newValue; mPowerFactor = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, PowerFactor::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, PowerFactor::Id);
} }
@@ -618,8 +604,7 @@ CHIP_ERROR ElectricalPowerMeasurementDelegate::SetNeutralCurrent(DataModel::Null
DataModel::Nullable<int64_t> oldValue = mNeutralCurrent; DataModel::Nullable<int64_t> oldValue = mNeutralCurrent;
mNeutralCurrent = newValue; mNeutralCurrent = newValue;
if (oldValue != newValue) if (oldValue != newValue) {
{
// We won't log raw values since these could change frequently // We won't log raw values since these could change frequently
MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, NeutralCurrent::Id); MatterReportingAttributeChangeCallback(mEndpointId, ElectricalPowerMeasurement::Id, NeutralCurrent::Id);
} }
@@ -56,8 +56,7 @@ namespace app {
namespace Clusters { namespace Clusters {
namespace PowerTopology { namespace PowerTopology {
class PowerTopologyDelegate : public Delegate class PowerTopologyDelegate : public Delegate {
{
public: public:
~PowerTopologyDelegate() = default; ~PowerTopologyDelegate() = default;
@@ -65,8 +64,6 @@ public:
CHIP_ERROR GetActiveEndpointAtIndex(size_t index, EndpointId &endpointId) override; CHIP_ERROR GetActiveEndpointAtIndex(size_t index, EndpointId &endpointId) override;
}; };
} // namespace PowerTopology } // namespace PowerTopology
} // namespace Clusters } // namespace Clusters
} // namespace app } // namespace app
@@ -80,8 +77,7 @@ namespace app {
namespace Clusters { namespace Clusters {
namespace ElectricalPowerMeasurement { namespace ElectricalPowerMeasurement {
class ElectricalPowerMeasurementDelegate : public ElectricalPowerMeasurement::Delegate class ElectricalPowerMeasurementDelegate : public ElectricalPowerMeasurement::Delegate {
{
public: public:
~ElectricalPowerMeasurementDelegate() = default; ~ElectricalPowerMeasurementDelegate() = default;
@@ -89,7 +85,10 @@ public:
static constexpr uint8_t kDefaultNumberOfMeasurementTypes = 1; static constexpr uint8_t kDefaultNumberOfMeasurementTypes = 1;
// Attribute Accessors // Attribute Accessors
PowerModeEnum GetPowerMode() override { return mPowerMode; } PowerModeEnum GetPowerMode() override
{
return mPowerMode;
}
uint8_t GetNumberOfMeasurementTypes() override; uint8_t GetNumberOfMeasurementTypes() override;
/* These functions are called by the ReadAttribute handler to iterate through lists /* These functions are called by the ReadAttribute handler to iterate through lists
@@ -114,19 +113,58 @@ public:
CHIP_ERROR GetHarmonicPhasesByIndex(uint8_t, Structs::HarmonicMeasurementStruct::Type &) override; CHIP_ERROR GetHarmonicPhasesByIndex(uint8_t, Structs::HarmonicMeasurementStruct::Type &) override;
CHIP_ERROR EndHarmonicPhasesRead() override; CHIP_ERROR EndHarmonicPhasesRead() override;
DataModel::Nullable<int64_t> GetVoltage() override { return mVoltage; } DataModel::Nullable<int64_t> GetVoltage() override
DataModel::Nullable<int64_t> GetActiveCurrent() override { return mActiveCurrent; } {
DataModel::Nullable<int64_t> GetReactiveCurrent() override { return mReactiveCurrent; } return mVoltage;
DataModel::Nullable<int64_t> GetApparentCurrent() override { return mApparentCurrent; } }
DataModel::Nullable<int64_t> GetActivePower() override { return mActivePower; } DataModel::Nullable<int64_t> GetActiveCurrent() override
DataModel::Nullable<int64_t> GetReactivePower() override { return mReactivePower; } {
DataModel::Nullable<int64_t> GetApparentPower() override { return mApparentPower; } return mActiveCurrent;
DataModel::Nullable<int64_t> GetRMSVoltage() override { return mRMSVoltage; } }
DataModel::Nullable<int64_t> GetRMSCurrent() override { return mRMSCurrent; } DataModel::Nullable<int64_t> GetReactiveCurrent() override
DataModel::Nullable<int64_t> GetRMSPower() override { return mRMSPower; } {
DataModel::Nullable<int64_t> GetFrequency() override { return mFrequency; } return mReactiveCurrent;
DataModel::Nullable<int64_t> GetPowerFactor() override { return mPowerFactor; } }
DataModel::Nullable<int64_t> GetNeutralCurrent() override { return mNeutralCurrent; }; DataModel::Nullable<int64_t> GetApparentCurrent() override
{
return mApparentCurrent;
}
DataModel::Nullable<int64_t> GetActivePower() override
{
return mActivePower;
}
DataModel::Nullable<int64_t> GetReactivePower() override
{
return mReactivePower;
}
DataModel::Nullable<int64_t> GetApparentPower() override
{
return mApparentPower;
}
DataModel::Nullable<int64_t> GetRMSVoltage() override
{
return mRMSVoltage;
}
DataModel::Nullable<int64_t> GetRMSCurrent() override
{
return mRMSCurrent;
}
DataModel::Nullable<int64_t> GetRMSPower() override
{
return mRMSPower;
}
DataModel::Nullable<int64_t> GetFrequency() override
{
return mFrequency;
}
DataModel::Nullable<int64_t> GetPowerFactor() override
{
return mPowerFactor;
}
DataModel::Nullable<int64_t> GetNeutralCurrent() override
{
return mNeutralCurrent;
};
// Internal Application API to set attribute values // Internal Application API to set attribute values
CHIP_ERROR SetPowerMode(PowerModeEnum); CHIP_ERROR SetPowerMode(PowerModeEnum);
@@ -162,8 +200,7 @@ private:
DataModel::Nullable<int64_t> mNeutralCurrent; DataModel::Nullable<int64_t> mNeutralCurrent;
}; };
class ElectricalPowerMeasurementInstance : public Instance class ElectricalPowerMeasurementInstance : public Instance {
{
public: public:
ElectricalPowerMeasurementInstance(EndpointId aEndpointId, ElectricalPowerMeasurementDelegate &aDelegate, Feature aFeature, ElectricalPowerMeasurementInstance(EndpointId aEndpointId, ElectricalPowerMeasurementDelegate &aDelegate, Feature aFeature,
OptionalAttributes aOptionalAttributes) : OptionalAttributes aOptionalAttributes) :
@@ -180,7 +217,10 @@ public:
CHIP_ERROR Init(); CHIP_ERROR Init();
void Shutdown(); void Shutdown();
ElectricalPowerMeasurementDelegate * GetDelegate() { return mDelegate; }; ElectricalPowerMeasurementDelegate * GetDelegate()
{
return mDelegate;
};
private: private:
ElectricalPowerMeasurementDelegate * mDelegate; ElectricalPowerMeasurementDelegate * mDelegate;
@@ -778,7 +778,6 @@ void init(void)
#endif //CONFIG_LOG_COLORS #endif //CONFIG_LOG_COLORS
} }
/* Main loop */ /* Main loop */
while (true) { while (true) {
/* Get a line using linenoise. /* Get a line using linenoise.
@@ -786,7 +785,6 @@ void init(void)
*/ */
char* line = linenoise(prompt); char* line = linenoise(prompt);
if (line == NULL) { /* Break on EOF or error */ if (line == NULL) { /* Break on EOF or error */
continue; continue;
} }
+1 -2
View File
@@ -8,7 +8,6 @@
#pragma once #pragma once
namespace esp_matter { namespace esp_matter {
namespace data_model { namespace data_model {
@@ -50,4 +49,4 @@ void init(void);
void deinit(void); void deinit(void);
} /* namespace console */ } /* namespace console */
} /* namepsace example */ } /* namespace example */
@@ -27,8 +27,7 @@ namespace app {
namespace Clusters { namespace Clusters {
namespace AccountLogin { namespace AccountLogin {
class MockAccountLoginDelegate : public Delegate class MockAccountLoginDelegate : public Delegate {
{
public: public:
MockAccountLoginDelegate() = default; MockAccountLoginDelegate() = default;
@@ -23,8 +23,7 @@ namespace app {
namespace Clusters { namespace Clusters {
namespace Chime { namespace Chime {
class MockChimeDelegate : public ChimeDelegate class MockChimeDelegate : public ChimeDelegate {
{
public: public:
MockChimeDelegate() = default; MockChimeDelegate() = default;
~MockChimeDelegate() override; ~MockChimeDelegate() override;
@@ -20,8 +20,7 @@ esp_err_t set_device_type_in_nvs(uint8_t device_type_index)
return err; return err;
} }
err = nvs_set_u8(handle, "device_name", device_type_index); err = nvs_set_u8(handle, "device_name", device_type_index);
if(err == ESP_OK) if (err == ESP_OK) {
{
nvs_commit(handle); nvs_commit(handle);
} }
nvs_close(handle); nvs_close(handle);
@@ -40,4 +39,4 @@ esp_err_t get_device_type_from_nvs(uint8_t *device_type_index)
return err; return err;
} }
} /* namespace nvs_helpers */ } /* namespace nvs_helpers */
} /* namepsace esp_matter */ } /* namespace esp_matter */
@@ -25,7 +25,6 @@ using namespace esp_matter;
using namespace esp_matter::cluster; using namespace esp_matter::cluster;
extern uint16_t aggregator_endpoint_id; extern uint16_t aggregator_endpoint_id;
/** Mesh Spec 4.2.1: "The Composition Data state contains information about a node, /** Mesh Spec 4.2.1: "The Composition Data state contains information about a node,
* the elements it includes, and the supported models. Composition Data Page 0 is mandatory." * the elements it includes, and the supported models. Composition Data Page 0 is mandatory."
* Composition Data Page 0 can be used to determine device type. * Composition Data Page 0 can be used to determine device type.
@@ -41,7 +40,8 @@ extern uint16_t aggregator_endpoint_id;
static uint8_t expect_composition[] = {/* CID */0XE5, 0x02, /* PID */0x00, 0x00, /* VID */0x00, 0x00, static uint8_t expect_composition[] = {/* CID */0XE5, 0x02, /* PID */0x00, 0x00, /* VID */0x00, 0x00,
/* CRPL */0X0A, 0x00, /* Features */0x03, 0x00, /* Loc */0x00, 0x00, /* CRPL */0X0A, 0x00, /* Features */0x03, 0x00, /* Loc */0x00, 0x00,
/* NumS */0x02, /* NumV */0x00, /* Config Server Model */0x00, 0x00, /* NumS */0x02, /* NumV */0x00, /* Config Server Model */0x00, 0x00,
/* Generic OnOff Server Model */0x00, 0x10}; /* Generic OnOff Server Model */0x00, 0x10
};
esp_err_t blemesh_bridge_match_bridged_onoff_light(uint8_t *composition_data, uint16_t blemesh_addr) esp_err_t blemesh_bridge_match_bridged_onoff_light(uint8_t *composition_data, uint16_t blemesh_addr)
{ {
@@ -79,8 +79,7 @@ esp_err_t blemesh_bridge_attribute_update(uint16_t endpoint_id, uint32_t cluster
app_ble_mesh_onoff_set(bridged_device->dev_addr.blemesh_addr, val->val.b); app_ble_mesh_onoff_set(bridged_device->dev_addr.blemesh_addr, val->val.b);
} }
} }
} } else {
else{
ESP_LOGE(TAG, "Unable to Update Bridge Device, ep: 0x%x, cluster: 0x%lx, att: 0x%lx", endpoint_id, cluster_id, ESP_LOGE(TAG, "Unable to Update Bridge Device, ep: 0x%x, cluster: 0x%lx, att: 0x%lx", endpoint_id, cluster_id,
attribute_id); attribute_id);
} }
@@ -57,8 +57,7 @@ static esp_err_t app_driver_bound_console_handler(int argc, char **argv)
} }
client::cluster_update(local_endpoint_id, &req_handle); client::cluster_update(local_endpoint_id, &req_handle);
} } else {
else {
ESP_LOGE(TAG, "Incorrect arguments. Check help for more details."); ESP_LOGE(TAG, "Incorrect arguments. Check help for more details.");
return ESP_ERR_INVALID_ARG; return ESP_ERR_INVALID_ARG;
} }
@@ -85,7 +84,8 @@ static esp_err_t app_driver_client_console_handler(int argc, char **argv)
req_handle.command_path = {(chip::EndpointId)strtoul((const char *)&argv[3][2], NULL, 16) /* EndpointId */, req_handle.command_path = {(chip::EndpointId)strtoul((const char *)&argv[3][2], NULL, 16) /* EndpointId */,
0 /* GroupId */, strtoul((const char *)&argv[4][2], NULL, 16) /* ClusterId */, 0 /* GroupId */, strtoul((const char *)&argv[4][2], NULL, 16) /* ClusterId */,
strtoul((const char *)&argv[5][2], NULL, 16) /* CommandId */, strtoul((const char *)&argv[5][2], NULL, 16) /* CommandId */,
chip::app::CommandPathFlags::kEndpointIdValid}; chip::app::CommandPathFlags::kEndpointIdValid
};
if (argc > 6) { if (argc > 6) {
console_buffer[0] = argc - 6; console_buffer[0] = argc - 6;
@@ -109,7 +109,8 @@ static esp_err_t app_driver_client_console_handler(int argc, char **argv)
req_handle.command_path = { req_handle.command_path = {
0 /* EndpointId */, (chip::GroupId)strtoul((const char *)&argv[2][2], NULL, 16) /* GroupId */, 0 /* EndpointId */, (chip::GroupId)strtoul((const char *)&argv[2][2], NULL, 16) /* GroupId */,
strtoul((const char *)&argv[3][2], NULL, 16) /* ClusterId */, strtoul((const char *)&argv[3][2], NULL, 16) /* ClusterId */,
strtoul((const char *)&argv[4][2], NULL, 16) /* CommandId */, chip::app::CommandPathFlags::kGroupIdValid}; strtoul((const char *)&argv[4][2], NULL, 16) /* CommandId */, chip::app::CommandPathFlags::kGroupIdValid
};
if (argc > 5) { if (argc > 5) {
console_buffer[0] = argc - 5; console_buffer[0] = argc - 5;
@@ -234,7 +234,6 @@ static esp_err_t get_device_service_name(char *service_name, size_t max)
return ESP_OK; return ESP_OK;
} }
static char *get_device_pop(app_network_pop_type_t pop_type) static char *get_device_pop(app_network_pop_type_t pop_type)
{ {
if (pop_type == POP_TYPE_NONE) { if (pop_type == POP_TYPE_NONE) {
@@ -29,20 +29,26 @@ static const char* rainmaker_node_mapping_payload_remove = "{\"node_id\":\"%s\",
#define RAINMAKER_URL_LEN 256 #define RAINMAKER_URL_LEN 256
/* RAII wrapper for HTTP client */ /* RAII wrapper for HTTP client */
class HttpClientWrapper class HttpClientWrapper {
{
public: public:
explicit HttpClientWrapper(const esp_http_client_config_t &config) explicit HttpClientWrapper(const esp_http_client_config_t &config)
: client_(esp_http_client_init(&config)) {} : client_(esp_http_client_init(&config)) {}
~HttpClientWrapper() { ~HttpClientWrapper()
{
if (client_) { if (client_) {
esp_http_client_cleanup(client_); esp_http_client_cleanup(client_);
} }
} }
esp_http_client_handle_t get() const { return client_; } esp_http_client_handle_t get() const
bool is_valid() const { return client_ != nullptr; } {
return client_;
}
bool is_valid() const
{
return client_ != nullptr;
}
/* Non-copyable */ /* Non-copyable */
HttpClientWrapper(const HttpClientWrapper &) = delete; HttpClientWrapper(const HttpClientWrapper &) = delete;
@@ -53,14 +59,22 @@ private:
}; };
/* RAII wrapper for JSON objects */ /* RAII wrapper for JSON objects */
class JsonWrapper class JsonWrapper {
{
public: public:
explicit JsonWrapper(cJSON* json) : json_(json) {} explicit JsonWrapper(cJSON* json) : json_(json) {}
~JsonWrapper() { if (json_) cJSON_Delete(json_); } ~JsonWrapper()
{
if (json_) {
cJSON_Delete(json_);
}
}
cJSON* get() const { return json_; } cJSON* get() const
cJSON* release() { {
return json_;
}
cJSON* release()
{
cJSON* temp = json_; cJSON* temp = json_;
json_ = nullptr; json_ = nullptr;
return temp; return temp;
@@ -75,14 +89,22 @@ private:
}; };
/* RAII wrapper for malloc'd memory */ /* RAII wrapper for malloc'd memory */
class MallocWrapper class MallocWrapper {
{
public: public:
explicit MallocWrapper(void* ptr) : ptr_(ptr) {} explicit MallocWrapper(void* ptr) : ptr_(ptr) {}
~MallocWrapper() { if (ptr_) free(ptr_); } ~MallocWrapper()
{
if (ptr_) {
free(ptr_);
}
}
void* get() const { return ptr_; } void* get() const
void* release() { {
return ptr_;
}
void* release()
{
void* temp = ptr_; void* temp = ptr_;
ptr_ = nullptr; ptr_ = nullptr;
return temp; return temp;
@@ -190,14 +190,14 @@ esp_err_t esp_rainmaker_api_get_node_connection_status(const char *node_id, bool
* This class provides a unified interface for interacting with ESP Rainmaker cloud services. * This class provides a unified interface for interacting with ESP Rainmaker cloud services.
* It handles authentication, node management, and group operations. * It handles authentication, node management, and group operations.
*/ */
class RainmakerApi class RainmakerApi {
{
public: public:
/** /**
* @brief Get singleton instance * @brief Get singleton instance
* @return Reference to the singleton instance * @return Reference to the singleton instance
*/ */
static RainmakerApi& GetInstance() { static RainmakerApi &GetInstance()
{
static RainmakerApi instance; static RainmakerApi instance;
return instance; return instance;
} }
@@ -391,4 +391,3 @@ private:
}; };
#endif /* __cplusplus */ #endif /* __cplusplus */
@@ -258,8 +258,7 @@ static esp_err_t rainmaker_bridge_get_param_from_device(const char* node_id, uin
case ESP_MATTER_EXTENDED_COLOR_LIGHT_DEVICE_TYPE_ID: case ESP_MATTER_EXTENDED_COLOR_LIGHT_DEVICE_TYPE_ID:
case ESP_MATTER_COLOR_TEMPERATURE_LIGHT_DEVICE_TYPE_ID: case ESP_MATTER_COLOR_TEMPERATURE_LIGHT_DEVICE_TYPE_ID:
case ESP_MATTER_DIMMABLE_LIGHT_DEVICE_TYPE_ID: case ESP_MATTER_DIMMABLE_LIGHT_DEVICE_TYPE_ID:
case ESP_MATTER_ON_OFF_LIGHT_DEVICE_TYPE_ID: case ESP_MATTER_ON_OFF_LIGHT_DEVICE_TYPE_ID: {
{
get_attribute_value_from_rainmaker_device(endpoint_id, node_id, app_bridge_get_rainmaker_node_name_by_matter_endpointid(endpoint_id)); get_attribute_value_from_rainmaker_device(endpoint_id, node_id, app_bridge_get_rainmaker_node_name_by_matter_endpointid(endpoint_id));
} }
break; break;
@@ -483,7 +482,8 @@ static esp_err_t init_spiffs()
esp_err_t err = ESP_OK; esp_err_t err = ESP_OK;
esp_vfs_spiffs_conf_t rcp_fw_conf = {.base_path = "/" CONFIG_RCP_PARTITION_NAME, esp_vfs_spiffs_conf_t rcp_fw_conf = {.base_path = "/" CONFIG_RCP_PARTITION_NAME,
.partition_label = CONFIG_RCP_PARTITION_NAME, .partition_label = CONFIG_RCP_PARTITION_NAME,
.max_files = 10, .format_if_mount_failed = false}; .max_files = 10, .format_if_mount_failed = false
};
err = esp_vfs_spiffs_register(&rcp_fw_conf); err = esp_vfs_spiffs_register(&rcp_fw_conf);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to mount rcp firmware storage"); ESP_LOGE(TAG, "Failed to mount rcp firmware storage");
@@ -541,4 +541,3 @@ void rainmaker_init()
/* create task to get node and params from rainmaker side */ /* create task to get node and params from rainmaker side */
xTaskCreate(rainmaker_bridge_task, "rainmaker_main", CONFIG_RAINMAKER_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), 5, NULL); xTaskCreate(rainmaker_bridge_task, "rainmaker_main", CONFIG_RAINMAKER_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), 5, NULL);
} }
@@ -69,8 +69,7 @@ esp_err_t zigbee_bridge_attribute_update(uint16_t endpoint_id, uint32_t cluster_
} }
} }
} }
} } else {
else{
ESP_LOGE(TAG, "Unable to Update Bridge Device, ep: %" PRId16 ", cluster: %" PRId32 ", att: %" PRId32 "", endpoint_id, cluster_id, attribute_id); ESP_LOGE(TAG, "Unable to Update Bridge Device, ep: %" PRId16 ", cluster: %" PRId32 ", att: %" PRId32 "", endpoint_id, cluster_id, attribute_id);
} }
return ESP_OK; return ESP_OK;
+6 -3
View File
@@ -25,11 +25,13 @@ extern uint16_t camera_endpoint_id;
bool deferred_offer = false; bool deferred_offer = false;
static void app_driver_button_toggle_cb(void *arg, void *data) { static void app_driver_button_toggle_cb(void *arg, void *data)
{
ESP_LOGI(TAG, "Toggle button pressed"); ESP_LOGI(TAG, "Toggle button pressed");
uint16_t endpoint_id = camera_endpoint_id; uint16_t endpoint_id = camera_endpoint_id;
} }
static void app_driver_button_double_click_cb(void *arg, void *data) { static void app_driver_button_double_click_cb(void *arg, void *data)
{
ESP_LOGI(TAG, "Double Click"); ESP_LOGI(TAG, "Double Click");
if (deferred_offer) { if (deferred_offer) {
ESP_LOGI(TAG, "Moving out of Standby Mode."); ESP_LOGI(TAG, "Moving out of Standby Mode.");
@@ -40,7 +42,8 @@ static void app_driver_button_double_click_cb(void *arg, void *data) {
} }
} }
app_driver_handle_t app_driver_button_init() { app_driver_handle_t app_driver_button_init()
{
/* Initialize button */ /* Initialize button */
button_handle_t handle = NULL; button_handle_t handle = NULL;
const button_config_t btn_cfg = {0}; const button_config_t btn_cfg = {0};
+14 -7
View File
@@ -49,7 +49,8 @@ CameraDevice gCameraDevice;
constexpr auto k_timeout_seconds = 300; constexpr auto k_timeout_seconds = 300;
static void app_event_cb(const ChipDeviceEvent *event, intptr_t arg) { static void app_event_cb(const ChipDeviceEvent *event, intptr_t arg)
{
switch (event->Type) { switch (event->Type) {
case chip::DeviceLayer::DeviceEventType::kInterfaceIpAddressChanged: case chip::DeviceLayer::DeviceEventType::kInterfaceIpAddressChanged:
ESP_LOGI(TAG, "Interface IP Address changed"); ESP_LOGI(TAG, "Interface IP Address changed");
@@ -133,7 +134,8 @@ static void app_event_cb(const ChipDeviceEvent *event, intptr_t arg) {
static esp_err_t app_identification_cb(identification::callback_type_t type, static esp_err_t app_identification_cb(identification::callback_type_t type,
uint16_t endpoint_id, uint8_t effect_id, uint16_t endpoint_id, uint8_t effect_id,
uint8_t effect_variant, uint8_t effect_variant,
void *priv_data) { void *priv_data)
{
ESP_LOGI(TAG, "Identification callback: type: %u, effect: %u, variant: %u", ESP_LOGI(TAG, "Identification callback: type: %u, effect: %u, variant: %u",
type, effect_id, effect_variant); type, effect_id, effect_variant);
return ESP_OK; return ESP_OK;
@@ -146,7 +148,8 @@ static esp_err_t app_identification_cb(identification::callback_type_t type,
static esp_err_t static esp_err_t
app_attribute_update_cb(attribute::callback_type_t type, uint16_t endpoint_id, app_attribute_update_cb(attribute::callback_type_t type, uint16_t endpoint_id,
uint32_t cluster_id, uint32_t attribute_id, uint32_t cluster_id, uint32_t attribute_id,
esp_matter_attr_val_t *val, void *priv_data) { esp_matter_attr_val_t *val, void *priv_data)
{
esp_err_t err = ESP_OK; esp_err_t err = ESP_OK;
if (type == PRE_UPDATE) { if (type == PRE_UPDATE) {
@@ -158,7 +161,8 @@ app_attribute_update_cb(attribute::callback_type_t type, uint16_t endpoint_id,
} }
#ifdef CONFIG_SLAVE_LWIP_ENABLED #ifdef CONFIG_SLAVE_LWIP_ENABLED
static void create_slave_sta_netif(uint8_t dhcp_at_slave) { static void create_slave_sta_netif(uint8_t dhcp_at_slave)
{
/* Create "almost" default station, but with un-flagged DHCP client */ /* Create "almost" default station, but with un-flagged DHCP client */
esp_netif_inherent_config_t netif_cfg; esp_netif_inherent_config_t netif_cfg;
memcpy(&netif_cfg, ESP_NETIF_BASE_DEFAULT_WIFI_STA, sizeof(netif_cfg)); memcpy(&netif_cfg, ESP_NETIF_BASE_DEFAULT_WIFI_STA, sizeof(netif_cfg));
@@ -178,14 +182,16 @@ static void create_slave_sta_netif(uint8_t dhcp_at_slave) {
ESP_ERROR_CHECK(esp_netif_attach_wifi_station(netif_sta)); ESP_ERROR_CHECK(esp_netif_attach_wifi_station(netif_sta));
ESP_ERROR_CHECK(esp_wifi_set_default_wifi_sta_handlers()); ESP_ERROR_CHECK(esp_wifi_set_default_wifi_sta_handlers());
if (!dhcp_at_slave) if (!dhcp_at_slave) {
ESP_ERROR_CHECK(esp_netif_dhcpc_stop(netif_sta)); ESP_ERROR_CHECK(esp_netif_dhcpc_stop(netif_sta));
}
// slave_sta_netif = netif_sta; // slave_sta_netif = netif_sta;
} }
#endif #endif
void sdp_mem_dump() { void sdp_mem_dump()
{
printf("\tDescription\tInternal\tSPIRAM\n"); printf("\tDescription\tInternal\tSPIRAM\n");
printf("Total Memory\t\t%d\t\t%d\n", printf("Total Memory\t\t%d\t\t%d\n",
heap_caps_get_total_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL), heap_caps_get_total_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL),
@@ -203,7 +209,8 @@ void sdp_mem_dump() {
heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM)); heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM));
} }
extern "C" void app_main() { extern "C" void app_main()
{
esp_err_t err = ESP_OK; esp_err_t err = ESP_OK;
/* Initialize the ESP NVS layer */ /* Initialize the ESP NVS layer */
+45 -55
View File
@@ -67,31 +67,27 @@ bool CameraDevice::MatchClosestSnapshotParams(const VideoResolutionStruct & requ
const SnapshotStream * bestStream = nullptr; const SnapshotStream * bestStream = nullptr;
const SnapshotStream * bestGEQStream = nullptr; const SnapshotStream * bestGEQStream = nullptr;
for (const auto & stream : mSnapshotStreams) for (const auto &stream : mSnapshotStreams) {
{
int64_t streamPixels = static_cast<int64_t>(stream.snapshotStreamParams.minResolution.width) * int64_t streamPixels = static_cast<int64_t>(stream.snapshotStreamParams.minResolution.width) *
stream.snapshotStreamParams.minResolution.height; stream.snapshotStreamParams.minResolution.height;
int64_t diff = streamPixels - requestedPixels; int64_t diff = streamPixels - requestedPixels;
int64_t absDiff = std::abs(diff); int64_t absDiff = std::abs(diff);
// Candidate 1: First stream with resolution >= requested // Candidate 1: First stream with resolution >= requested
if (diff >= 0 && diff < bestGEQDiff) if (diff >= 0 && diff < bestGEQDiff) {
{
bestGEQDiff = diff; bestGEQDiff = diff;
bestGEQStream = &stream; bestGEQStream = &stream;
} }
// Candidate 2: Closest stream (absolute difference) // Candidate 2: Closest stream (absolute difference)
if (absDiff < bestDiff) if (absDiff < bestDiff) {
{
bestDiff = absDiff; bestDiff = absDiff;
bestStream = &stream; bestStream = &stream;
} }
} }
const SnapshotStream * chosen = bestGEQStream ? bestGEQStream : bestStream; const SnapshotStream * chosen = bestGEQStream ? bestGEQStream : bestStream;
if (chosen) if (chosen) {
{
matchedResolution = chosen->snapshotStreamParams.minResolution; matchedResolution = chosen->snapshotStreamParams.minResolution;
matchedCodec = chosen->snapshotStreamParams.imageCodec; matchedCodec = chosen->snapshotStreamParams.imageCodec;
return true; return true;
@@ -105,23 +101,18 @@ CameraError CameraDevice::CaptureSnapshot(const chip::app::DataModel::Nullable<u
VideoResolutionStruct matchedRes; VideoResolutionStruct matchedRes;
ImageCodecEnum matchedCodec; ImageCodecEnum matchedCodec;
if (streamID.IsNull()) if (streamID.IsNull()) {
{ if (!MatchClosestSnapshotParams(resolution, matchedRes, matchedCodec)) {
if (!MatchClosestSnapshotParams(resolution, matchedRes, matchedCodec))
{
ChipLogError(Camera, "No matching snapshot stream found for requested resolution %ux%u", resolution.width, ChipLogError(Camera, "No matching snapshot stream found for requested resolution %ux%u", resolution.width,
resolution.height); resolution.height);
return CameraError::ERROR_CAPTURE_SNAPSHOT_FAILED; return CameraError::ERROR_CAPTURE_SNAPSHOT_FAILED;
} }
} } else {
else
{
uint16_t streamId = streamID.Value(); uint16_t streamId = streamID.Value();
auto it = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [streamId](const SnapshotStream & s) { auto it = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [streamId](const SnapshotStream & s) {
return s.snapshotStreamParams.snapshotStreamID == streamId; return s.snapshotStreamParams.snapshotStreamID == streamId;
}); });
if (it == mSnapshotStreams.end()) if (it == mSnapshotStreams.end()) {
{
ChipLogError(Camera, "Snapshot stream not found for stream ID %u", streamId); ChipLogError(Camera, "Snapshot stream not found for stream ID %u", streamId);
return CameraError::ERROR_CAPTURE_SNAPSHOT_FAILED; return CameraError::ERROR_CAPTURE_SNAPSHOT_FAILED;
} }
@@ -156,13 +147,11 @@ CameraError CameraDevice::AllocateSnapshotStream(const CameraAVStreamManagementD
uint16_t &outStreamID) uint16_t &outStreamID)
{ {
if (AddSnapshotStream(args, outStreamID)) if (AddSnapshotStream(args, outStreamID)) {
{
auto it = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [outStreamID](const SnapshotStream & s) { auto it = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [outStreamID](const SnapshotStream & s) {
return s.snapshotStreamParams.snapshotStreamID == outStreamID; return s.snapshotStreamParams.snapshotStreamID == outStreamID;
}); });
if (it == mSnapshotStreams.end()) if (it == mSnapshotStreams.end()) {
{
ChipLogError(Camera, "Snapshot stream with ID %u not found", outStreamID); ChipLogError(Camera, "Snapshot stream with ID %u not found", outStreamID);
return CameraError::ERROR_RESOURCE_EXHAUSTED; return CameraError::ERROR_RESOURCE_EXHAUSTED;
} }
@@ -186,7 +175,8 @@ uint32_t CameraDevice::GetMaxEncodedPixelRate()
VideoSensorParamsStruct &CameraDevice::GetVideoSensorParams() VideoSensorParamsStruct &CameraDevice::GetVideoSensorParams()
{ {
static VideoSensorParamsStruct videoSensorParams = { kVideoSensorWidthPixels, kVideoSensorHeightPixels, kMaxVideoFrameRate, static VideoSensorParamsStruct videoSensorParams = { kVideoSensorWidthPixels, kVideoSensorHeightPixels, kMaxVideoFrameRate,
chip::Optional<uint16_t>(30) }; // Typical numbers for Pi camera. chip::Optional<uint16_t>(30)
}; // Typical numbers for Pi camera.
return videoSensorParams; return videoSensorParams;
} }
@@ -235,7 +225,8 @@ std::vector<RateDistortionTradeOffStruct> & CameraDevice::GetRateDistortionTrade
{ {
static std::vector<RateDistortionTradeOffStruct> rateDistTradeOffs = { { static std::vector<RateDistortionTradeOffStruct> rateDistTradeOffs = { {
VideoCodecEnum::kH264, { kMinResolutionWidth, kMinResolutionHeight }, 10000 /* bitrate */ VideoCodecEnum::kH264, { kMinResolutionWidth, kMinResolutionHeight }, 10000 /* bitrate */
} }; }
};
return rateDistTradeOffs; return rateDistTradeOffs;
} }
@@ -250,7 +241,8 @@ AudioCapabilitiesStruct & CameraDevice::GetMicrophoneCapabilities()
static std::array<uint32_t, 2> sampleRates = { 48000, 32000 }; // Sample rates in Hz static std::array<uint32_t, 2> sampleRates = { 48000, 32000 }; // Sample rates in Hz
static std::array<uint8_t, 2> bitDepths = { 24, 32 }; static std::array<uint8_t, 2> bitDepths = { 24, 32 };
static AudioCapabilitiesStruct audioCapabilities = { kMicrophoneMaxChannelCount, chip::Span<AudioCodecEnum>(audioCodecs), static AudioCapabilitiesStruct audioCapabilities = { kMicrophoneMaxChannelCount, chip::Span<AudioCodecEnum>(audioCodecs),
chip::Span<uint32_t>(sampleRates), chip::Span<uint8_t>(bitDepths) }; chip::Span<uint32_t>(sampleRates), chip::Span<uint8_t>(bitDepths)
};
return audioCapabilities; return audioCapabilities;
} }
@@ -260,7 +252,8 @@ AudioCapabilitiesStruct & CameraDevice::GetSpeakerCapabilities()
static std::array<uint32_t, 2> sampleRates = { 48000, 32000 }; // Sample rates in Hz static std::array<uint32_t, 2> sampleRates = { 48000, 32000 }; // Sample rates in Hz
static std::array<uint8_t, 2> bitDepths = { 24, 32 }; static std::array<uint8_t, 2> bitDepths = { 24, 32 };
static AudioCapabilitiesStruct speakerCapabilities = { kSpeakerMaxChannelCount, chip::Span<AudioCodecEnum>(audioCodecs), static AudioCapabilitiesStruct speakerCapabilities = { kSpeakerMaxChannelCount, chip::Span<AudioCodecEnum>(audioCodecs),
chip::Span<uint32_t>(sampleRates), chip::Span<uint8_t>(bitDepths) }; chip::Span<uint32_t>(sampleRates), chip::Span<uint8_t>(bitDepths)
};
return speakerCapabilities; return speakerCapabilities;
} }
@@ -270,7 +263,9 @@ std::vector<SnapshotCapabilitiesStruct> & CameraDevice::GetSnapshotCapabilities(
kSnapshotStreamFrameRate, kSnapshotStreamFrameRate,
ImageCodecEnum::kJpeg, ImageCodecEnum::kJpeg,
false, false,
chip::MakeOptional(static_cast<bool>(false)) } }; chip::MakeOptional(static_cast<bool>(false))
}
};
return snapshotCapabilities; return snapshotCapabilities;
} }
@@ -448,7 +443,8 @@ void CameraDevice::InitializeVideoStreams()
}, },
false, false,
{ mViewport.x1, mViewport.y1, mViewport.x2, mViewport.y2 }, { mViewport.x1, mViewport.y1, mViewport.x2, mViewport.y2 },
nullptr }; nullptr
};
mVideoStreams.push_back(videoStream1); mVideoStreams.push_back(videoStream1);
// Create a video stream for the full range(fps, resolution, bitrate) // Create a video stream for the full range(fps, resolution, bitrate)
@@ -470,7 +466,8 @@ void CameraDevice::InitializeVideoStreams()
}, },
false, false,
{ mViewport.x1, mViewport.y1, mViewport.x2, mViewport.y2 }, { mViewport.x1, mViewport.y1, mViewport.x2, mViewport.y2 },
nullptr }; nullptr
};
mVideoStreams.push_back(videoStream2); mVideoStreams.push_back(videoStream2);
@@ -491,7 +488,8 @@ void CameraDevice::InitializeVideoStreams()
}, },
false, false,
{ mViewport.x1, mViewport.y1, mViewport.x2, mViewport.y2 }, { mViewport.x1, mViewport.y1, mViewport.x2, mViewport.y2 },
nullptr }; nullptr
};
mVideoStreams.push_back(videoStream3); mVideoStreams.push_back(videoStream3);
} }
@@ -505,7 +503,8 @@ void CameraDevice::InitializeAudioStreams()
48000 /* SampleRate */, 20000 /* BitRate */, 24 /* BitDepth */, 0 /* RefCount */ 48000 /* SampleRate */, 20000 /* BitRate */, 24 /* BitDepth */, 0 /* RefCount */
}, },
false, false,
nullptr }; nullptr
};
mAudioStreams.push_back(monoStream); mAudioStreams.push_back(monoStream);
// Stereo stream // Stereo stream
@@ -514,7 +513,8 @@ void CameraDevice::InitializeAudioStreams()
48000 /* SampleRate */, 32000 /* BitRate */, 24 /* BitDepth */, 0 /* RefCount */ 48000 /* SampleRate */, 32000 /* BitRate */, 24 /* BitDepth */, 0 /* RefCount */
}, },
false, false,
nullptr }; nullptr
};
mAudioStreams.push_back(stereoStream); mAudioStreams.push_back(stereoStream);
// Max channel count stream (from spec constant) // Max channel count stream (from spec constant)
@@ -524,7 +524,8 @@ void CameraDevice::InitializeAudioStreams()
64000 /* BitRate */, 24 /* BitDepth */, 0 /* RefCount */ 64000 /* BitRate */, 24 /* BitDepth */, 0 /* RefCount */
}, },
false, false,
nullptr }; nullptr
};
mAudioStreams.push_back(maxChannelStream); mAudioStreams.push_back(maxChannelStream);
} }
@@ -545,8 +546,7 @@ bool CameraDevice::AddSnapshotStream(
{ {
constexpr uint16_t kMaxSnapshotStreams = std::numeric_limits<uint16_t>::max(); constexpr uint16_t kMaxSnapshotStreams = std::numeric_limits<uint16_t>::max();
if (mSnapshotStreams.size() >= kMaxSnapshotStreams) if (mSnapshotStreams.size() >= kMaxSnapshotStreams) {
{
ChipLogError(Camera, "Maximum number of snapshot streams reached. Cannot allocate new one"); ChipLogError(Camera, "Maximum number of snapshot streams reached. Cannot allocate new one");
return false; return false;
} }
@@ -556,30 +556,24 @@ bool CameraDevice::AddSnapshotStream(
// the ID that was passed in. A valid streamID would be passed in when the // the ID that was passed in. A valid streamID would be passed in when the
// stream list is being constructed from the persisted list of allocated // stream list is being constructed from the persisted list of allocated
// streams that was loaded at Init() // streams that was loaded at Init()
if (outStreamID == kInvalidStreamID) if (outStreamID == kInvalidStreamID) {
{ for (const auto &s : mSnapshotStreams) {
for (const auto & s : mSnapshotStreams)
{
// Find the highest existing stream ID. // Find the highest existing stream ID.
if (s.snapshotStreamParams.snapshotStreamID > streamId) if (s.snapshotStreamParams.snapshotStreamID > streamId) {
{
streamId = s.snapshotStreamParams.snapshotStreamID; streamId = s.snapshotStreamParams.snapshotStreamID;
} }
} }
// Find a unique stream id, starting from the last used one above, // Find a unique stream id, starting from the last used one above,
// incrementing and wrapping at 65535. // incrementing and wrapping at 65535.
for (uint16_t attempts = 0; attempts < kMaxSnapshotStreams; ++attempts) for (uint16_t attempts = 0; attempts < kMaxSnapshotStreams; ++attempts) {
{
auto found = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [streamId](const SnapshotStream & s) { auto found = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [streamId](const SnapshotStream & s) {
return s.snapshotStreamParams.snapshotStreamID == streamId; return s.snapshotStreamParams.snapshotStreamID == streamId;
}); });
if (found == mSnapshotStreams.end()) if (found == mSnapshotStreams.end()) {
{
break; break;
} }
if (attempts == kMaxSnapshotStreams - 1) if (attempts == kMaxSnapshotStreams - 1) {
{
ChipLogError(Camera, "No available slot for stream allocation"); ChipLogError(Camera, "No available slot for stream allocation");
return false; return false;
} }
@@ -587,21 +581,16 @@ bool CameraDevice::AddSnapshotStream(
} }
outStreamID = streamId; outStreamID = streamId;
} } else {
else
{
// Have a sanity check that the passed streamID does not already exist // Have a sanity check that the passed streamID does not already exist
// in the list // in the list
auto found = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [outStreamID](const SnapshotStream & s) { auto found = std::find_if(mSnapshotStreams.begin(), mSnapshotStreams.end(), [outStreamID](const SnapshotStream & s) {
return s.snapshotStreamParams.snapshotStreamID == outStreamID; return s.snapshotStreamParams.snapshotStreamID == outStreamID;
}); });
if (found == mSnapshotStreams.end()) if (found == mSnapshotStreams.end()) {
{
streamId = outStreamID; streamId = outStreamID;
} } else {
else
{
ChipLogError(Camera, "StreamID %d already exists in the available snapshot stream list", outStreamID); ChipLogError(Camera, "StreamID %d already exists in the available snapshot stream list", outStreamID);
return false; return false;
} }
@@ -613,7 +602,8 @@ bool CameraDevice::AddSnapshotStream(
snapshotStreamAllocateArgs.quality, 0 /* RefCount */ snapshotStreamAllocateArgs.quality, 0 /* RefCount */
}, },
false, false,
nullptr }; nullptr
};
mSnapshotStreams.push_back(snapshotStream); mSnapshotStreams.push_back(snapshotStream);
return true; return true;
+121 -32
View File
@@ -62,8 +62,7 @@ static constexpr uint16_t kInvalidStreamID = 65500;
namespace Camera { namespace Camera {
class CameraDevice : public CameraDeviceInterface, public CameraDeviceInterface::CameraHALInterface class CameraDevice : public CameraDeviceInterface, public CameraDeviceInterface::CameraHALInterface {
{
public: public:
chip::app::Clusters::WebRTCTransportProvider::Delegate &GetWebRTCProviderDelegate() override; chip::app::Clusters::WebRTCTransportProvider::Delegate &GetWebRTCProviderDelegate() override;
void void
@@ -73,7 +72,10 @@ public:
CameraDevice(); CameraDevice();
~CameraDevice(); ~CameraDevice();
CameraDeviceInterface::CameraHALInterface & GetCameraHALInterface() override { return *this; } CameraDeviceInterface::CameraHALInterface &GetCameraHALInterface() override
{
return *this;
}
void Init(); void Init();
@@ -127,22 +129,37 @@ public:
uint16_t GetCurrentFrameRate() override; uint16_t GetCurrentFrameRate() override;
CameraError SetHDRMode(bool hdrMode) override; CameraError SetHDRMode(bool hdrMode) override;
bool GetHDRMode() override { return mHDREnabled; } bool GetHDRMode() override
{
return mHDREnabled;
}
CameraError SetHardPrivacyMode(bool hardPrivacyMode) override; CameraError SetHardPrivacyMode(bool hardPrivacyMode) override;
bool GetHardPrivacyMode() override { return mHardPrivacyModeOn; } bool GetHardPrivacyMode() override
{
return mHardPrivacyModeOn;
}
CameraError SetNightVision(chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum nightVision) override; CameraError SetNightVision(chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum nightVision) override;
chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum GetNightVision() override { return mNightVision; } chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum GetNightVision() override
{
return mNightVision;
}
std::vector<StreamUsageEnum> &GetSupportedStreamUsages() override; std::vector<StreamUsageEnum> &GetSupportedStreamUsages() override;
std::vector<StreamUsageEnum> & GetStreamUsagePriorities() override { return mStreamUsagePriorities; } std::vector<StreamUsageEnum> &GetStreamUsagePriorities() override
{
return mStreamUsagePriorities;
}
CameraError SetStreamUsagePriorities(std::vector<StreamUsageEnum> streamUsagePriorities) override; CameraError SetStreamUsagePriorities(std::vector<StreamUsageEnum> streamUsagePriorities) override;
// Sets the Default Camera Viewport // Sets the Default Camera Viewport
CameraError SetViewport(const chip::app::Clusters::Globals::Structs::ViewportStruct::Type &viewPort) override; CameraError SetViewport(const chip::app::Clusters::Globals::Structs::ViewportStruct::Type &viewPort) override;
const chip::app::Clusters::Globals::Structs::ViewportStruct::Type & GetViewport() override { return mViewport; } const chip::app::Clusters::Globals::Structs::ViewportStruct::Type &GetViewport() override
{
return mViewport;
}
/** /**
* Sets the Viewport for a specific stream. The implementation of this HAL API * Sets the Viewport for a specific stream. The implementation of this HAL API
@@ -160,78 +177,150 @@ public:
// Get/Set SoftRecordingPrivacyMode. // Get/Set SoftRecordingPrivacyMode.
CameraError SetSoftRecordingPrivacyModeEnabled(bool softRecordingPrivacyMode) override; CameraError SetSoftRecordingPrivacyModeEnabled(bool softRecordingPrivacyMode) override;
bool GetSoftRecordingPrivacyModeEnabled() override { return mSoftRecordingPrivacyModeEnabled; } bool GetSoftRecordingPrivacyModeEnabled() override
{
return mSoftRecordingPrivacyModeEnabled;
}
// Get/Set SoftLivestreamPrivacyMode. // Get/Set SoftLivestreamPrivacyMode.
CameraError SetSoftLivestreamPrivacyModeEnabled(bool softLivestreamPrivacyMode) override; CameraError SetSoftLivestreamPrivacyModeEnabled(bool softLivestreamPrivacyMode) override;
bool GetSoftLivestreamPrivacyModeEnabled() override { return mSoftLivestreamPrivacyModeEnabled; } bool GetSoftLivestreamPrivacyModeEnabled() override
{
return mSoftLivestreamPrivacyModeEnabled;
}
// Currently, defaulting to not supporting hard privacy switch. // Currently, defaulting to not supporting hard privacy switch.
bool HasHardPrivacySwitch() override { return false; } bool HasHardPrivacySwitch() override
{
return false;
}
// Currently, defaulting to not supporting speaker. // Currently, defaulting to not supporting speaker.
bool HasSpeaker() override { return false; } bool HasSpeaker() override
{
return false;
}
// Mute/Unmute speaker. // Mute/Unmute speaker.
CameraError SetSpeakerMuted(bool muteSpeaker) override; CameraError SetSpeakerMuted(bool muteSpeaker) override;
bool GetSpeakerMuted() override { return mSpeakerMuted; } bool GetSpeakerMuted() override
{
return mSpeakerMuted;
}
// Get/Set speaker volume level. // Get/Set speaker volume level.
CameraError SetSpeakerVolume(uint8_t speakerVol) override; CameraError SetSpeakerVolume(uint8_t speakerVol) override;
uint8_t GetSpeakerVolume() override { return mSpeakerVol; } uint8_t GetSpeakerVolume() override
{
return mSpeakerVol;
}
// Get the speaker max and min levels. // Get the speaker max and min levels.
uint8_t GetSpeakerMaxLevel() override { return INVALID_SPKR_LEVEL; } uint8_t GetSpeakerMaxLevel() override
uint8_t GetSpeakerMinLevel() override { return INVALID_SPKR_LEVEL; } {
return INVALID_SPKR_LEVEL;
}
uint8_t GetSpeakerMinLevel() override
{
return INVALID_SPKR_LEVEL;
}
// Does camera have a microphone // Does camera have a microphone
bool HasMicrophone() override { return true; } bool HasMicrophone() override
{
return true;
}
// Mute/Unmute microphone. // Mute/Unmute microphone.
CameraError SetMicrophoneMuted(bool muteMicrophone) override; CameraError SetMicrophoneMuted(bool muteMicrophone) override;
bool GetMicrophoneMuted() override { return mMicrophoneMuted; } bool GetMicrophoneMuted() override
{
return mMicrophoneMuted;
}
// Set microphone volume level. // Set microphone volume level.
CameraError SetMicrophoneVolume(uint8_t microphoneVol) override; CameraError SetMicrophoneVolume(uint8_t microphoneVol) override;
uint8_t GetMicrophoneVolume() override { return mMicrophoneVol; } uint8_t GetMicrophoneVolume() override
{
return mMicrophoneVol;
}
// Get the microphone max and min levels. // Get the microphone max and min levels.
uint8_t GetMicrophoneMaxLevel() override { return mMicrophoneMaxLevel; } uint8_t GetMicrophoneMaxLevel() override
uint8_t GetMicrophoneMinLevel() override { return mMicrophoneMinLevel; } {
return mMicrophoneMaxLevel;
}
uint8_t GetMicrophoneMinLevel() override
{
return mMicrophoneMinLevel;
}
// Get/Set image control attributes // Get/Set image control attributes
CameraError SetImageRotation(uint16_t imageRotation) override; CameraError SetImageRotation(uint16_t imageRotation) override;
uint16_t GetImageRotation() override { return mImageRotation; } uint16_t GetImageRotation() override
{
return mImageRotation;
}
CameraError SetImageFlipHorizontal(bool imageFlipHorizontal) override; CameraError SetImageFlipHorizontal(bool imageFlipHorizontal) override;
bool GetImageFlipHorizontal() override { return mImageFlipHorizontal; } bool GetImageFlipHorizontal() override
{
return mImageFlipHorizontal;
}
CameraError SetImageFlipVertical(bool imageFlipVertical) override; CameraError SetImageFlipVertical(bool imageFlipVertical) override;
bool GetImageFlipVertical() override { return mImageFlipVertical; } bool GetImageFlipVertical() override
{
return mImageFlipVertical;
}
// Does camera have local storage // Does camera have local storage
bool HasLocalStorage() override { return false; } bool HasLocalStorage() override
{
return false;
}
// Set/Get LocalVideoRecordingEnabled // Set/Get LocalVideoRecordingEnabled
CameraError SetLocalVideoRecordingEnabled(bool localVideoRecordingEnabled) override; CameraError SetLocalVideoRecordingEnabled(bool localVideoRecordingEnabled) override;
bool GetLocalVideoRecordingEnabled() override { return mLocalVideoRecordingEnabled; } bool GetLocalVideoRecordingEnabled() override
{
return mLocalVideoRecordingEnabled;
}
// Set/Get LocalSnapshotRecordingEnabled // Set/Get LocalSnapshotRecordingEnabled
CameraError SetLocalSnapshotRecordingEnabled(bool localSnapshotRecordingEnabled) override; CameraError SetLocalSnapshotRecordingEnabled(bool localSnapshotRecordingEnabled) override;
bool GetLocalSnapshotRecordingEnabled() override { return mLocalSnapshotRecordingEnabled; } bool GetLocalSnapshotRecordingEnabled() override
{
return mLocalSnapshotRecordingEnabled;
}
// Does camera have a status light // Does camera have a status light
bool HasStatusLight() override { return true; } bool HasStatusLight() override
{
return true;
}
// Set/Get StatusLightEnabled // Set/Get StatusLightEnabled
CameraError SetStatusLightEnabled(bool statusLightEnabled) override; CameraError SetStatusLightEnabled(bool statusLightEnabled) override;
bool GetStatusLightEnabled() override { return mStatusLightEnabled; } bool GetStatusLightEnabled() override
{
return mStatusLightEnabled;
}
std::vector<VideoStream> & GetAvailableVideoStreams() override { return mVideoStreams; } std::vector<VideoStream> &GetAvailableVideoStreams() override
{
return mVideoStreams;
}
std::vector<AudioStream> & GetAvailableAudioStreams() override { return mAudioStreams; } std::vector<AudioStream> &GetAvailableAudioStreams() override
{
return mAudioStreams;
}
std::vector<SnapshotStream> & GetAvailableSnapshotStreams() override { return mSnapshotStreams; } std::vector<SnapshotStream> &GetAvailableSnapshotStreams() override
{
return mSnapshotStreams;
}
private: private:
std::vector<VideoStream> mVideoStreams; // Vector to hold available video streams std::vector<VideoStream> mVideoStreams; // Vector to hold available video streams
@@ -63,25 +63,20 @@ CHIP_ERROR CameraAVStreamManager::ValidateStreamUsage(StreamUsageEnum streamUsag
// Is the requested stream usage supported by the camera? // Is the requested stream usage supported by the camera?
auto myStreamUsages = GetCameraAVStreamManagementCluster()->GetSupportedStreamUsages(); auto myStreamUsages = GetCameraAVStreamManagementCluster()->GetSupportedStreamUsages();
auto it = std::find(myStreamUsages.begin(), myStreamUsages.end(), streamUsage); auto it = std::find(myStreamUsages.begin(), myStreamUsages.end(), streamUsage);
if (it == myStreamUsages.end()) if (it == myStreamUsages.end()) {
{
ChipLogError(Camera, "Requested stream usage not found in supported stream usages"); ChipLogError(Camera, "Requested stream usage not found in supported stream usages");
return CHIP_ERROR_NOT_FOUND; return CHIP_ERROR_NOT_FOUND;
} }
if (videoStreamId.HasValue()) if (videoStreamId.HasValue()) {
{
const std::vector<VideoStreamStruct> &allocatedVideoStreams = const std::vector<VideoStreamStruct> &allocatedVideoStreams =
GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams(); GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams();
// If no Video ID is provided, match to an allocated ID. Exact is preferred // If no Video ID is provided, match to an allocated ID. Exact is preferred
// if found. We know the stream requested is in supported streams. // if found. We know the stream requested is in supported streams.
if (videoStreamId.Value().IsNull()) if (videoStreamId.Value().IsNull()) {
{ for (const auto &stream : allocatedVideoStreams) {
for (const auto & stream : allocatedVideoStreams) if (stream.streamUsage == streamUsage) {
{
if (stream.streamUsage == streamUsage)
{
videoStreamId.Emplace(stream.videoStreamID); videoStreamId.Emplace(stream.videoStreamID);
exactlyMatchedVideoStream = true; exactlyMatchedVideoStream = true;
break; break;
@@ -90,28 +85,22 @@ CHIP_ERROR CameraAVStreamManager::ValidateStreamUsage(StreamUsageEnum streamUsag
looselyMatchedVideoStream = true; looselyMatchedVideoStream = true;
looseVideoStreamID = stream.videoStreamID; looseVideoStreamID = stream.videoStreamID;
} }
} } else {
else
{
// We've been provided with a stream ID, and we know the stream usage is // We've been provided with a stream ID, and we know the stream usage is
// supported by the camera, classify as an exact match // supported by the camera, classify as an exact match
exactlyMatchedVideoStream = true; exactlyMatchedVideoStream = true;
} }
} }
if (audioStreamId.HasValue()) if (audioStreamId.HasValue()) {
{
const std::vector<AudioStreamStruct> &allocatedAudioStreams = const std::vector<AudioStreamStruct> &allocatedAudioStreams =
GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams(); GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams();
// If no Audio ID is provided, match to an allocated ID. Exact is preferred // If no Audio ID is provided, match to an allocated ID. Exact is preferred
// if found. We know the stream requested is in supported streams. // if found. We know the stream requested is in supported streams.
if (audioStreamId.Value().IsNull()) if (audioStreamId.Value().IsNull()) {
{ for (const auto &stream : allocatedAudioStreams) {
for (const auto & stream : allocatedAudioStreams) if (stream.streamUsage == streamUsage) {
{
if (stream.streamUsage == streamUsage)
{
audioStreamId.Emplace(stream.audioStreamID); audioStreamId.Emplace(stream.audioStreamID);
exactlyMatchedAudioStream = true; exactlyMatchedAudioStream = true;
break; break;
@@ -120,9 +109,7 @@ CHIP_ERROR CameraAVStreamManager::ValidateStreamUsage(StreamUsageEnum streamUsag
looselyMatchedAudioStream = true; looselyMatchedAudioStream = true;
looseAudioStreamID = stream.audioStreamID; looseAudioStreamID = stream.audioStreamID;
} }
} } else {
else
{
// We've been provided with a stream ID, and we know the stream usage is // We've been provided with a stream ID, and we know the stream usage is
// supported by the camera, classify as an exact match // supported by the camera, classify as an exact match
exactlyMatchedAudioStream = true; exactlyMatchedAudioStream = true;
@@ -132,13 +119,11 @@ CHIP_ERROR CameraAVStreamManager::ValidateStreamUsage(StreamUsageEnum streamUsag
// If we have a loose match and no exact match, update the provided stream IDs // If we have a loose match and no exact match, update the provided stream IDs
// with the loose match values // with the loose match values
// //
if (looselyMatchedAudioStream && !exactlyMatchedAudioStream) if (looselyMatchedAudioStream && !exactlyMatchedAudioStream) {
{
audioStreamId.Emplace(looseAudioStreamID); audioStreamId.Emplace(looseAudioStreamID);
} }
if (looselyMatchedVideoStream && !exactlyMatchedVideoStream) if (looselyMatchedVideoStream && !exactlyMatchedVideoStream) {
{
videoStreamId.Emplace(looseVideoStreamID); videoStreamId.Emplace(looseVideoStreamID);
} }
@@ -163,28 +148,22 @@ void CameraAVStreamManager::GetBandwidthForStreams(const Optional<DataModel::Nul
{ {
outBandwidthbps = 0; outBandwidthbps = 0;
if (videoStreamId.HasValue() && !videoStreamId.Value().IsNull()) if (videoStreamId.HasValue() && !videoStreamId.Value().IsNull()) {
{
uint16_t vStreamId = videoStreamId.Value().Value(); uint16_t vStreamId = videoStreamId.Value().Value();
auto &allocatedVideoStreams = GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams(); auto &allocatedVideoStreams = GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams();
for (const chip::app::Clusters::CameraAvStreamManagement::Structs::VideoStreamStruct::Type & stream : allocatedVideoStreams) for (const chip::app::Clusters::CameraAvStreamManagement::Structs::VideoStreamStruct::Type &stream : allocatedVideoStreams) {
{ if (stream.videoStreamID == vStreamId) {
if (stream.videoStreamID == vStreamId)
{
outBandwidthbps += stream.maxBitRate; outBandwidthbps += stream.maxBitRate;
ChipLogProgress(Camera, "GetBandwidthForStreams: VideoStream %u maxBitRate: %lu bps", vStreamId, stream.maxBitRate); ChipLogProgress(Camera, "GetBandwidthForStreams: VideoStream %u maxBitRate: %lu bps", vStreamId, stream.maxBitRate);
break; break;
} }
} }
} }
if (audioStreamId.HasValue() && !audioStreamId.Value().IsNull()) if (audioStreamId.HasValue() && !audioStreamId.Value().IsNull()) {
{
uint16_t aStreamId = audioStreamId.Value().Value(); uint16_t aStreamId = audioStreamId.Value().Value();
auto &allocatedAudioStreams = GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams(); auto &allocatedAudioStreams = GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams();
for (const chip::app::Clusters::CameraAvStreamManagement::Structs::AudioStreamStruct::Type & stream : allocatedAudioStreams) for (const chip::app::Clusters::CameraAvStreamManagement::Structs::AudioStreamStruct::Type &stream : allocatedAudioStreams) {
{ if (stream.audioStreamID == aStreamId) {
if (stream.audioStreamID == aStreamId)
{
outBandwidthbps += stream.bitRate; outBandwidthbps += stream.bitRate;
ChipLogProgress(Camera, "GetBandwidthForStreams: AudioStream %u bitRate: %lu bps", aStreamId, stream.bitRate); ChipLogProgress(Camera, "GetBandwidthForStreams: AudioStream %u bitRate: %lu bps", aStreamId, stream.bitRate);
break; break;
@@ -200,10 +179,8 @@ CameraAVStreamManager::ValidateVideoStreamID(uint16_t videoStreamId)
const std::vector<VideoStreamStruct> &allocatedVideoStreams = GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams(); const std::vector<VideoStreamStruct> &allocatedVideoStreams = GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams();
// Check if the videoStreamId exists in allocated streams // Check if the videoStreamId exists in allocated streams
for (const auto & stream : allocatedVideoStreams) for (const auto &stream : allocatedVideoStreams) {
{ if (stream.videoStreamID == videoStreamId) {
if (stream.videoStreamID == videoStreamId)
{
ChipLogProgress(Camera, "Video stream ID %u is valid and allocated", videoStreamId); ChipLogProgress(Camera, "Video stream ID %u is valid and allocated", videoStreamId);
return CHIP_NO_ERROR; return CHIP_NO_ERROR;
} }
@@ -219,10 +196,8 @@ CameraAVStreamManager::ValidateAudioStreamID(uint16_t audioStreamId)
const std::vector<AudioStreamStruct> &allocatedAudioStreams = GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams(); const std::vector<AudioStreamStruct> &allocatedAudioStreams = GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams();
// Check if the audioStreamId exists in allocated streams // Check if the audioStreamId exists in allocated streams
for (const auto & stream : allocatedAudioStreams) for (const auto &stream : allocatedAudioStreams) {
{ if (stream.audioStreamID == audioStreamId) {
if (stream.audioStreamID == audioStreamId)
{
ChipLogProgress(Camera, "Audio stream ID %u is valid and allocated", audioStreamId); ChipLogProgress(Camera, "Audio stream ID %u is valid and allocated", audioStreamId);
return CHIP_NO_ERROR; return CHIP_NO_ERROR;
} }
@@ -279,25 +254,21 @@ Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamAllocate(c
bool isRequestSupportedByAnyAvailableStream = false; bool isRequestSupportedByAnyAvailableStream = false;
// Check if allocation request can be supported // Check if allocation request can be supported
for (const auto & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (const auto &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (stream.IsCompatible(allocateArgs)) {
if (stream.IsCompatible(allocateArgs))
{
isRequestSupportedByAnyAvailableStream = true; isRequestSupportedByAnyAvailableStream = true;
break; break;
} }
} }
if (!isRequestSupportedByAnyAvailableStream) if (!isRequestSupportedByAnyAvailableStream) {
{
return Status::DynamicConstraintError; return Status::DynamicConstraintError;
} }
// Try to reuse an allocated stream // Try to reuse an allocated stream
std::optional<uint16_t> reusableStreamId = GetCameraAVStreamManagementCluster()->GetReusableVideoStreamId(allocateArgs); std::optional<uint16_t> reusableStreamId = GetCameraAVStreamManagementCluster()->GetReusableVideoStreamId(allocateArgs);
if (reusableStreamId.has_value()) if (reusableStreamId.has_value()) {
{
// Found a stream that can be reused // Found a stream that can be reused
outStreamID = reusableStreamId.value(); outStreamID = reusableStreamId.value();
ChipLogProgress(Camera, "Matching pre-allocated stream with ID: %d exists", outStreamID); ChipLogProgress(Camera, "Matching pre-allocated stream with ID: %d exists", outStreamID);
@@ -305,16 +276,13 @@ Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamAllocate(c
} }
// Try to find an unused compatible available stream // Try to find an unused compatible available stream
for (auto & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (auto &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (!stream.isAllocated && stream.IsCompatible(allocateArgs)) {
if (!stream.isAllocated && stream.IsCompatible(allocateArgs))
{
uint32_t candidateEncodedPixelRate = uint32_t candidateEncodedPixelRate =
allocateArgs.maxFrameRate * allocateArgs.maxResolution.height * allocateArgs.maxResolution.width; allocateArgs.maxFrameRate * allocateArgs.maxResolution.height * allocateArgs.maxResolution.width;
bool encoderRequired = true; bool encoderRequired = true;
if (!GetCameraAVStreamManagementCluster()->IsResourceAvailableForStreamAllocation(candidateEncodedPixelRate, if (!GetCameraAVStreamManagementCluster()->IsResourceAvailableForStreamAllocation(candidateEncodedPixelRate,
encoderRequired)) encoderRequired)) {
{
return Status::ResourceExhausted; return Status::ResourceExhausted;
} }
stream.isAllocated = true; stream.isAllocated = true;
@@ -337,8 +305,7 @@ Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamAllocate(c
void CameraAVStreamManager::OnVideoStreamAllocated(const VideoStreamStruct &allocatedStream, StreamAllocationAction action) void CameraAVStreamManager::OnVideoStreamAllocated(const VideoStreamStruct &allocatedStream, StreamAllocationAction action)
{ {
switch (action) switch (action) {
{
case StreamAllocationAction::kNewAllocation: case StreamAllocationAction::kNewAllocation:
ChipLogProgress(Camera, "Starting new video stream with ID: %u", allocatedStream.videoStreamID); ChipLogProgress(Camera, "Starting new video stream with ID: %u", allocatedStream.videoStreamID);
// mCameraDeviceHAL->GetCameraHALInterface().StartVideoStream(allocatedStream); // mCameraDeviceHAL->GetCameraHALInterface().StartVideoStream(allocatedStream);
@@ -349,10 +316,8 @@ void CameraAVStreamManager::OnVideoStreamAllocated(const VideoStreamStruct & all
case StreamAllocationAction::kModification: case StreamAllocationAction::kModification:
// Find the stream and restart it with new parameters // Find the stream and restart it with new parameters
for (VideoStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (VideoStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (stream.videoStreamParams.videoStreamID == allocatedStream.videoStreamID && stream.isAllocated) {
if (stream.videoStreamParams.videoStreamID == allocatedStream.videoStreamID && stream.isAllocated)
{
// For modifications, we always stop and restart the stream to ensure // For modifications, we always stop and restart the stream to ensure
// new parameters are applied // new parameters are applied
ChipLogProgress(Camera, "Restarting video stream with ID: %u due to modifications", allocatedStream.videoStreamID); ChipLogProgress(Camera, "Restarting video stream with ID: %u due to modifications", allocatedStream.videoStreamID);
@@ -371,17 +336,13 @@ Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamModify(con
const chip::Optional<bool> waterMarkEnabled, const chip::Optional<bool> waterMarkEnabled,
const chip::Optional<bool> osdEnabled) const chip::Optional<bool> osdEnabled)
{ {
for (VideoStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (VideoStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (stream.videoStreamParams.videoStreamID == streamID && stream.isAllocated) {
if (stream.videoStreamParams.videoStreamID == streamID && stream.isAllocated)
{
// TODO: Link with HAL APIs to return error // TODO: Link with HAL APIs to return error
if (waterMarkEnabled.HasValue()) if (waterMarkEnabled.HasValue()) {
{
stream.videoStreamParams.watermarkEnabled = waterMarkEnabled; stream.videoStreamParams.watermarkEnabled = waterMarkEnabled;
} }
if (osdEnabled.HasValue()) if (osdEnabled.HasValue()) {
{
stream.videoStreamParams.OSDEnabled = osdEnabled; stream.videoStreamParams.OSDEnabled = osdEnabled;
} }
ChipLogError(Camera, "Modified video stream with ID: %d", streamID); ChipLogError(Camera, "Modified video stream with ID: %d", streamID);
@@ -396,10 +357,8 @@ Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamModify(con
Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamDeallocate(const uint16_t streamID) Protocols::InteractionModel::Status CameraAVStreamManager::VideoStreamDeallocate(const uint16_t streamID)
{ {
for (VideoStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (VideoStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (stream.videoStreamParams.videoStreamID == streamID && stream.isAllocated) {
if (stream.videoStreamParams.videoStreamID == streamID && stream.isAllocated)
{
stream.isAllocated = false; stream.isAllocated = false;
return Status::Success; return Status::Success;
} }
@@ -415,18 +374,13 @@ Protocols::InteractionModel::Status CameraAVStreamManager::AudioStreamAllocate(c
{ {
outStreamID = kInvalidStreamID; outStreamID = kInvalidStreamID;
for (AudioStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) for (AudioStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) {
{ if (stream.IsCompatible(allocateArgs)) {
if (stream.IsCompatible(allocateArgs))
{
outStreamID = stream.audioStreamParams.audioStreamID; outStreamID = stream.audioStreamParams.audioStreamID;
if (!stream.isAllocated) if (!stream.isAllocated) {
{
stream.isAllocated = true; stream.isAllocated = true;
return Status::Success; return Status::Success;
} } else {
else
{
ChipLogProgress(Camera, "Matching pre-allocated stream with ID: %d exists", outStreamID); ChipLogProgress(Camera, "Matching pre-allocated stream with ID: %d exists", outStreamID);
} }
return Status::Success; return Status::Success;
@@ -438,10 +392,8 @@ Protocols::InteractionModel::Status CameraAVStreamManager::AudioStreamAllocate(c
Protocols::InteractionModel::Status CameraAVStreamManager::AudioStreamDeallocate(const uint16_t streamID) Protocols::InteractionModel::Status CameraAVStreamManager::AudioStreamDeallocate(const uint16_t streamID)
{ {
for (AudioStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) for (AudioStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) {
{ if (stream.audioStreamParams.audioStreamID == streamID && stream.isAllocated) {
if (stream.audioStreamParams.audioStreamID == streamID && stream.isAllocated)
{
stream.isAllocated = false; stream.isAllocated = false;
return Status::Success; return Status::Success;
} }
@@ -459,25 +411,21 @@ Protocols::InteractionModel::Status CameraAVStreamManager::SnapshotStreamAllocat
bool isRequestSupportedByAnyAvailableStream = false; bool isRequestSupportedByAnyAvailableStream = false;
// Check if allocation request can be supported // Check if allocation request can be supported
for (const auto & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) for (const auto &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) {
{ if (stream.IsCompatible(allocateArgs)) {
if (stream.IsCompatible(allocateArgs))
{
isRequestSupportedByAnyAvailableStream = true; isRequestSupportedByAnyAvailableStream = true;
break; break;
} }
} }
if (!isRequestSupportedByAnyAvailableStream) if (!isRequestSupportedByAnyAvailableStream) {
{
return Status::DynamicConstraintError; return Status::DynamicConstraintError;
} }
// Try to reuse an allocated stream. // Try to reuse an allocated stream.
std::optional<uint16_t> reusableStreamId = GetCameraAVStreamManagementCluster()->GetReusableSnapshotStreamId(allocateArgs); std::optional<uint16_t> reusableStreamId = GetCameraAVStreamManagementCluster()->GetReusableSnapshotStreamId(allocateArgs);
if (reusableStreamId.has_value()) if (reusableStreamId.has_value()) {
{
// Found a stream that can be reused // Found a stream that can be reused
outStreamID = reusableStreamId.value(); outStreamID = reusableStreamId.value();
ChipLogProgress(Camera, "Matching pre-allocated stream with ID: %d exists", outStreamID); ChipLogProgress(Camera, "Matching pre-allocated stream with ID: %d exists", outStreamID);
@@ -486,32 +434,26 @@ Protocols::InteractionModel::Status CameraAVStreamManager::SnapshotStreamAllocat
uint32_t candidateEncodedPixelRate = 0; uint32_t candidateEncodedPixelRate = 0;
bool encoderRequired = false; bool encoderRequired = false;
if (allocateArgs.encodedPixels) if (allocateArgs.encodedPixels) {
{
candidateEncodedPixelRate += candidateEncodedPixelRate +=
allocateArgs.maxFrameRate * allocateArgs.maxResolution.height * allocateArgs.maxResolution.width; allocateArgs.maxFrameRate * allocateArgs.maxResolution.height * allocateArgs.maxResolution.width;
if (allocateArgs.hardwareEncoder) if (allocateArgs.hardwareEncoder) {
{
encoderRequired = true; encoderRequired = true;
} }
} }
if (!GetCameraAVStreamManagementCluster()->IsResourceAvailableForStreamAllocation(candidateEncodedPixelRate, encoderRequired)) if (!GetCameraAVStreamManagementCluster()->IsResourceAvailableForStreamAllocation(candidateEncodedPixelRate, encoderRequired)) {
{
return Status::ResourceExhausted; return Status::ResourceExhausted;
} }
// If no pre-allocated stream matches, try allocating a new one. // If no pre-allocated stream matches, try allocating a new one.
if (mCameraDeviceHAL->GetCameraHALInterface().AllocateSnapshotStream(allocateArgs, outStreamID) == CameraError::SUCCESS) if (mCameraDeviceHAL->GetCameraHALInterface().AllocateSnapshotStream(allocateArgs, outStreamID) == CameraError::SUCCESS) {
{
return Status::Success; return Status::Success;
} }
// Try to find an unused compatible available stream // Try to find an unused compatible available stream
for (auto & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) for (auto &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) {
{ if (!stream.isAllocated && stream.IsCompatible(allocateArgs)) {
if (!stream.isAllocated && stream.IsCompatible(allocateArgs))
{
stream.isAllocated = true; stream.isAllocated = true;
outStreamID = stream.snapshotStreamParams.snapshotStreamID; outStreamID = stream.snapshotStreamParams.snapshotStreamID;
@@ -534,17 +476,13 @@ Protocols::InteractionModel::Status CameraAVStreamManager::SnapshotStreamModify(
const chip::Optional<bool> waterMarkEnabled, const chip::Optional<bool> waterMarkEnabled,
const chip::Optional<bool> osdEnabled) const chip::Optional<bool> osdEnabled)
{ {
for (SnapshotStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) for (SnapshotStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) {
{ if (stream.snapshotStreamParams.snapshotStreamID == streamID && stream.isAllocated) {
if (stream.snapshotStreamParams.snapshotStreamID == streamID && stream.isAllocated)
{
// TODO: Link with HAL APIs to return error // TODO: Link with HAL APIs to return error
if (waterMarkEnabled.HasValue()) if (waterMarkEnabled.HasValue()) {
{
stream.snapshotStreamParams.watermarkEnabled = waterMarkEnabled; stream.snapshotStreamParams.watermarkEnabled = waterMarkEnabled;
} }
if (osdEnabled.HasValue()) if (osdEnabled.HasValue()) {
{
stream.snapshotStreamParams.OSDEnabled = osdEnabled; stream.snapshotStreamParams.OSDEnabled = osdEnabled;
} }
ChipLogError(Camera, "Modified snapshot stream with ID: %d", streamID); ChipLogError(Camera, "Modified snapshot stream with ID: %d", streamID);
@@ -559,12 +497,9 @@ Protocols::InteractionModel::Status CameraAVStreamManager::SnapshotStreamModify(
Protocols::InteractionModel::Status CameraAVStreamManager::SnapshotStreamDeallocate(const uint16_t streamID) Protocols::InteractionModel::Status CameraAVStreamManager::SnapshotStreamDeallocate(const uint16_t streamID)
{ {
for (SnapshotStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) for (SnapshotStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableSnapshotStreams()) {
{ if (stream.snapshotStreamParams.snapshotStreamID == streamID && stream.isAllocated) {
if (stream.snapshotStreamParams.snapshotStreamID == streamID && stream.isAllocated) if (stream.snapshotStreamParams.referenceCount > 0) {
{
if (stream.snapshotStreamParams.referenceCount > 0)
{
ChipLogError(Camera, "Snapshot stream with ID: %d still in use", streamID); ChipLogError(Camera, "Snapshot stream with ID: %d still in use", streamID);
return Status::InvalidInState; return Status::InvalidInState;
} }
@@ -590,8 +525,7 @@ void CameraAVStreamManager::OnAttributeChanged(AttributeId attributeId)
{ {
ChipLogProgress(Camera, "Attribute changed for AttributeId = " ChipLogFormatMEI, ChipLogValueMEI(attributeId)); ChipLogProgress(Camera, "Attribute changed for AttributeId = " ChipLogFormatMEI, ChipLogValueMEI(attributeId));
switch (attributeId) switch (attributeId) {
{
case HDRModeEnabled::Id: { case HDRModeEnabled::Id: {
mCameraDeviceHAL->GetCameraHALInterface().SetHDRMode(GetCameraAVStreamManagementCluster()->GetHDRModeEnabled()); mCameraDeviceHAL->GetCameraHALInterface().SetHDRMode(GetCameraAVStreamManagementCluster()->GetHDRModeEnabled());
@@ -619,8 +553,7 @@ void CameraAVStreamManager::OnAttributeChanged(AttributeId attributeId)
mCameraDeviceHAL->GetCameraHALInterface().SetViewport(GetCameraAVStreamManagementCluster()->GetViewport()); mCameraDeviceHAL->GetCameraHALInterface().SetViewport(GetCameraAVStreamManagementCluster()->GetViewport());
// Update the per stream viewports on the camera // Update the per stream viewports on the camera
for (VideoStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (VideoStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{
mCameraDeviceHAL->GetCameraHALInterface().SetViewport(stream, GetCameraAVStreamManagementCluster()->GetViewport()); mCameraDeviceHAL->GetCameraHALInterface().SetViewport(stream, GetCameraAVStreamManagementCluster()->GetViewport());
} }
break; break;
@@ -680,12 +613,9 @@ Protocols::InteractionModel::Status CameraAVStreamManager::CaptureSnapshot(const
const VideoResolutionStruct &resolution, const VideoResolutionStruct &resolution,
ImageSnapshot &outImageSnapshot) ImageSnapshot &outImageSnapshot)
{ {
if (mCameraDeviceHAL->GetCameraHALInterface().CaptureSnapshot(streamID, resolution, outImageSnapshot) == CameraError::SUCCESS) if (mCameraDeviceHAL->GetCameraHALInterface().CaptureSnapshot(streamID, resolution, outImageSnapshot) == CameraError::SUCCESS) {
{
return Status::Success; return Status::Success;
} } else {
else
{
return Status::Failure; return Status::Failure;
} }
@@ -698,14 +628,12 @@ CameraAVStreamManager::AllocatedVideoStreamsLoaded()
const std::vector<VideoStreamStruct> &persistedStreams = GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams(); const std::vector<VideoStreamStruct> &persistedStreams = GetCameraAVStreamManagementCluster()->GetAllocatedVideoStreams();
auto &halStreams = mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams(); auto &halStreams = mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams();
for (auto & halStream : halStreams) for (auto &halStream : halStreams) {
{
auto it = std::find_if(persistedStreams.begin(), persistedStreams.end(), [&](const VideoStreamStruct & persistedStream) { auto it = std::find_if(persistedStreams.begin(), persistedStreams.end(), [&](const VideoStreamStruct & persistedStream) {
return persistedStream.videoStreamID == halStream.videoStreamParams.videoStreamID; return persistedStream.videoStreamID == halStream.videoStreamParams.videoStreamID;
}); });
if (it != persistedStreams.end()) if (it != persistedStreams.end()) {
{
// Found in persisted streams, mark as allocated in HAL // Found in persisted streams, mark as allocated in HAL
halStream.isAllocated = true; halStream.isAllocated = true;
ChipLogProgress(Camera, "HAL Video Stream ID %u marked as allocated from persisted state.", ChipLogProgress(Camera, "HAL Video Stream ID %u marked as allocated from persisted state.",
@@ -725,14 +653,12 @@ CameraAVStreamManager::AllocatedAudioStreamsLoaded()
const std::vector<AudioStreamStruct> &persistedStreams = GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams(); const std::vector<AudioStreamStruct> &persistedStreams = GetCameraAVStreamManagementCluster()->GetAllocatedAudioStreams();
auto &halStreams = mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams(); auto &halStreams = mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams();
for (auto & halStream : halStreams) for (auto &halStream : halStreams) {
{
auto it = std::find_if(persistedStreams.begin(), persistedStreams.end(), [&](const AudioStreamStruct & persistedStream) { auto it = std::find_if(persistedStreams.begin(), persistedStreams.end(), [&](const AudioStreamStruct & persistedStream) {
return persistedStream.audioStreamID == halStream.audioStreamParams.audioStreamID; return persistedStream.audioStreamID == halStream.audioStreamParams.audioStreamID;
}); });
if (it != persistedStreams.end()) if (it != persistedStreams.end()) {
{
// Found in persisted streams, mark as allocated in HAL // Found in persisted streams, mark as allocated in HAL
halStream.isAllocated = true; halStream.isAllocated = true;
ChipLogProgress(Camera, "HAL Audio Stream ID %u marked as allocated from persisted state.", ChipLogProgress(Camera, "HAL Audio Stream ID %u marked as allocated from persisted state.",
@@ -757,22 +683,19 @@ CameraAVStreamManager::PersistentAttributesLoadedCallback()
ChipLogDetail(Camera, "Successfully loaded persistent attributes"); ChipLogDetail(Camera, "Successfully loaded persistent attributes");
CHIP_ERROR err = AllocatedVideoStreamsLoaded(); CHIP_ERROR err = AllocatedVideoStreamsLoaded();
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Allocated video streams could not be loaded: %" CHIP_ERROR_FORMAT, err.Format()); ChipLogError(Camera, "Allocated video streams could not be loaded: %" CHIP_ERROR_FORMAT, err.Format());
return err; return err;
} }
err = AllocatedAudioStreamsLoaded(); err = AllocatedAudioStreamsLoaded();
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Allocated audio streams could not be loaded: %" CHIP_ERROR_FORMAT, err.Format()); ChipLogError(Camera, "Allocated audio streams could not be loaded: %" CHIP_ERROR_FORMAT, err.Format());
return err; return err;
} }
err = AllocatedSnapshotStreamsLoaded(); err = AllocatedSnapshotStreamsLoaded();
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Allocated snapshot streams could not be loaded: %" CHIP_ERROR_FORMAT, err.Format()); ChipLogError(Camera, "Allocated snapshot streams could not be loaded: %" CHIP_ERROR_FORMAT, err.Format());
return err; return err;
} }
@@ -784,32 +707,22 @@ CHIP_ERROR
CameraAVStreamManager::OnTransportAcquireAudioVideoStreams(uint16_t audioStreamID, uint16_t videoStreamID) CameraAVStreamManager::OnTransportAcquireAudioVideoStreams(uint16_t audioStreamID, uint16_t videoStreamID)
{ {
// Update the available audio stream in the HAL // Update the available audio stream in the HAL
for (AudioStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) for (AudioStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) {
{ if (stream.audioStreamParams.audioStreamID == audioStreamID && stream.isAllocated) {
if (stream.audioStreamParams.audioStreamID == audioStreamID && stream.isAllocated) if (stream.audioStreamParams.referenceCount < UINT8_MAX) {
{
if (stream.audioStreamParams.referenceCount < UINT8_MAX)
{
stream.audioStreamParams.referenceCount++; stream.audioStreamParams.referenceCount++;
} } else {
else
{
ChipLogError(Camera, "Attempted to increment audio stream %u ref count beyond max limit", audioStreamID); ChipLogError(Camera, "Attempted to increment audio stream %u ref count beyond max limit", audioStreamID);
} }
} }
} }
// Update the available video stream in the HAL // Update the available video stream in the HAL
for (VideoStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (VideoStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (stream.videoStreamParams.videoStreamID == videoStreamID && stream.isAllocated) {
if (stream.videoStreamParams.videoStreamID == videoStreamID && stream.isAllocated) if (stream.videoStreamParams.referenceCount < UINT8_MAX) {
{
if (stream.videoStreamParams.referenceCount < UINT8_MAX)
{
stream.videoStreamParams.referenceCount++; stream.videoStreamParams.referenceCount++;
} } else {
else
{
ChipLogError(Camera, "Attempted to increment video stream %u ref count beyond max limit", videoStreamID); ChipLogError(Camera, "Attempted to increment video stream %u ref count beyond max limit", videoStreamID);
} }
} }
@@ -817,14 +730,12 @@ CameraAVStreamManager::OnTransportAcquireAudioVideoStreams(uint16_t audioStreamI
// Update the counts in the SDK allocated stream attributes // Update the counts in the SDK allocated stream attributes
if (GetCameraAVStreamManagementCluster()->UpdateAudioStreamRefCount(audioStreamID, /* shouldIncrement = */ true) != if (GetCameraAVStreamManagementCluster()->UpdateAudioStreamRefCount(audioStreamID, /* shouldIncrement = */ true) !=
CHIP_NO_ERROR) CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Failed to increment audio stream %u ref count in SDK", audioStreamID); ChipLogError(Camera, "Failed to increment audio stream %u ref count in SDK", audioStreamID);
} }
if (GetCameraAVStreamManagementCluster()->UpdateVideoStreamRefCount(videoStreamID, /* shouldIncrement = */ true) != if (GetCameraAVStreamManagementCluster()->UpdateVideoStreamRefCount(videoStreamID, /* shouldIncrement = */ true) !=
CHIP_NO_ERROR) CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Failed to increment video stream %u ref count in SDK", videoStreamID); ChipLogError(Camera, "Failed to increment video stream %u ref count in SDK", videoStreamID);
} }
@@ -835,16 +746,11 @@ CHIP_ERROR
CameraAVStreamManager::OnTransportReleaseAudioVideoStreams(uint16_t audioStreamID, uint16_t videoStreamID) CameraAVStreamManager::OnTransportReleaseAudioVideoStreams(uint16_t audioStreamID, uint16_t videoStreamID)
{ {
// Update the available audio stream in the HAL // Update the available audio stream in the HAL
for (AudioStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) for (AudioStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableAudioStreams()) {
{ if (stream.audioStreamParams.audioStreamID == audioStreamID && stream.isAllocated) {
if (stream.audioStreamParams.audioStreamID == audioStreamID && stream.isAllocated) if (stream.audioStreamParams.referenceCount > 0) {
{
if (stream.audioStreamParams.referenceCount > 0)
{
stream.audioStreamParams.referenceCount--; stream.audioStreamParams.referenceCount--;
} } else {
else
{
ChipLogError(Camera, ChipLogError(Camera,
"Attempted to decrement audio stream %u ref count when it " "Attempted to decrement audio stream %u ref count when it "
"was already 0", "was already 0",
@@ -854,16 +760,11 @@ CameraAVStreamManager::OnTransportReleaseAudioVideoStreams(uint16_t audioStreamI
} }
// Update the available video stream in the HAL // Update the available video stream in the HAL
for (VideoStream & stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) for (VideoStream &stream : mCameraDeviceHAL->GetCameraHALInterface().GetAvailableVideoStreams()) {
{ if (stream.videoStreamParams.videoStreamID == videoStreamID && stream.isAllocated) {
if (stream.videoStreamParams.videoStreamID == videoStreamID && stream.isAllocated) if (stream.videoStreamParams.referenceCount > 0) {
{
if (stream.videoStreamParams.referenceCount > 0)
{
stream.videoStreamParams.referenceCount--; stream.videoStreamParams.referenceCount--;
} } else {
else
{
ChipLogError(Camera, ChipLogError(Camera,
"Attempted to decrement video stream %u ref count when it " "Attempted to decrement video stream %u ref count when it "
"was already 0", "was already 0",
@@ -874,14 +775,12 @@ CameraAVStreamManager::OnTransportReleaseAudioVideoStreams(uint16_t audioStreamI
// Update the counts in the SDK allocated stream attributes // Update the counts in the SDK allocated stream attributes
if (GetCameraAVStreamManagementCluster()->UpdateAudioStreamRefCount(audioStreamID, /* shouldIncrement = */ false) != if (GetCameraAVStreamManagementCluster()->UpdateAudioStreamRefCount(audioStreamID, /* shouldIncrement = */ false) !=
CHIP_NO_ERROR) CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Failed to decrement audio stream %u ref count in SDK", audioStreamID); ChipLogError(Camera, "Failed to decrement audio stream %u ref count in SDK", audioStreamID);
} }
if (GetCameraAVStreamManagementCluster()->UpdateVideoStreamRefCount(videoStreamID, /* shouldIncrement = */ false) != if (GetCameraAVStreamManagementCluster()->UpdateVideoStreamRefCount(videoStreamID, /* shouldIncrement = */ false) !=
CHIP_NO_ERROR) CHIP_NO_ERROR) {
{
ChipLogError(Camera, "Failed to decrement video stream %u ref count in SDK", videoStreamID); ChipLogError(Camera, "Failed to decrement video stream %u ref count in SDK", videoStreamID);
} }
@@ -31,8 +31,7 @@ namespace CameraAvStreamManagement {
/** /**
* The application delegate to define the options & implement commands. * The application delegate to define the options & implement commands.
*/ */
class CameraAVStreamManager : public CameraAVStreamManagementDelegate, public CameraAVStreamController class CameraAVStreamManager : public CameraAVStreamManagementDelegate, public CameraAVStreamController {
{
public: public:
Protocols::InteractionModel::Status VideoStreamAllocate(const VideoStreamStruct &allocateArgs, Protocols::InteractionModel::Status VideoStreamAllocate(const VideoStreamStruct &allocateArgs,
uint16_t &outStreamID) override; uint16_t &outStreamID) override;
@@ -77,42 +77,30 @@ WebRTCProviderManager::HandleSolicitOffer(const OfferRequestArgs & args, WebRTCS
uint16_t audioStreamID = 0; uint16_t audioStreamID = 0;
// Resolve or allocate a VIDEO stream // Resolve or allocate a VIDEO stream
if (args.videoStreamId.HasValue()) if (args.videoStreamId.HasValue()) {
{ if (args.videoStreamId.Value().IsNull()) {
if (args.videoStreamId.Value().IsNull())
{
// TODO: Automatically select the closest matching video stream for the // TODO: Automatically select the closest matching video stream for the
// StreamUsage requested by looking at the and the server MAY allocate a // StreamUsage requested by looking at the and the server MAY allocate a
// new video stream if there are available resources. // new video stream if there are available resources.
} } else {
else
{
outSession.videoStreamID = args.videoStreamId.Value(); outSession.videoStreamID = args.videoStreamId.Value();
videoStreamID = args.videoStreamId.Value().Value(); videoStreamID = args.videoStreamId.Value().Value();
} }
} } else {
else
{
outSession.videoStreamID.SetNull(); outSession.videoStreamID.SetNull();
} }
// Resolve or allocate an AUDIO stream // Resolve or allocate an AUDIO stream
if (args.audioStreamId.HasValue()) if (args.audioStreamId.HasValue()) {
{ if (args.audioStreamId.Value().IsNull()) {
if (args.audioStreamId.Value().IsNull())
{
// TODO: Automatically select the closest matching audio stream for the // TODO: Automatically select the closest matching audio stream for the
// StreamUsage requested and the server MAY allocate a new audio stream if // StreamUsage requested and the server MAY allocate a new audio stream if
// there are available resources. // there are available resources.
} } else {
else
{
outSession.audioStreamID = args.audioStreamId.Value(); outSession.audioStreamID = args.audioStreamId.Value();
audioStreamID = args.audioStreamId.Value().Value(); audioStreamID = args.audioStreamId.Value().Value();
} }
} } else {
else
{
outSession.audioStreamID.SetNull(); outSession.audioStreamID.SetNull();
} }
@@ -130,8 +118,7 @@ WebRTCProviderManager::HandleSolicitOffer(const OfferRequestArgs & args, WebRTCS
requestArgs.audioStreamId = audioStreamID; requestArgs.audioStreamId = audioStreamID;
requestArgs.peerId = ScopedNodeId(args.peerNodeId, args.fabricIndex); requestArgs.peerId = ScopedNodeId(args.peerNodeId, args.fabricIndex);
if (transport == nullptr) if (transport == nullptr) {
{
mWebrtcTransportMap[args.sessionId] = std::unique_ptr<WebrtcTransport>(new WebrtcTransport()); mWebrtcTransportMap[args.sessionId] = std::unique_ptr<WebrtcTransport>(new WebrtcTransport());
mSessionIdMap[ScopedNodeId(args.peerNodeId, args.fabricIndex)] = args.sessionId; mSessionIdMap[ScopedNodeId(args.peerNodeId, args.fabricIndex)] = args.sessionId;
transport = mWebrtcTransportMap[args.sessionId].get(); transport = mWebrtcTransportMap[args.sessionId].get();
@@ -139,7 +126,9 @@ WebRTCProviderManager::HandleSolicitOffer(const OfferRequestArgs & args, WebRTCS
[this](const std::string & sdp, SDPType type, const uint16_t sessionId) { [this](const std::string & sdp, SDPType type, const uint16_t sessionId) {
this->OnLocalDescription(sdp, type, sessionId); this->OnLocalDescription(sdp, type, sessionId);
}, },
[this](bool connected, const uint16_t sessionId) { this->OnConnectionStateChanged(connected, sessionId); }); [this](bool connected, const uint16_t sessionId) {
this->OnConnectionStateChanged(connected, sessionId);
});
} }
transport->SetRequestArgs(requestArgs); transport->SetRequestArgs(requestArgs);
@@ -147,8 +136,7 @@ WebRTCProviderManager::HandleSolicitOffer(const OfferRequestArgs & args, WebRTCS
// Check resource availability before proceeding // Check resource availability before proceeding
// If we cannot allocate resources, send End command with OutOfResources // If we cannot allocate resources, send End command with OutOfResources
// reason // reason
if (mWebrtcTransportMap.size() > kMaxConcurrentWebRTCSessions) if (mWebrtcTransportMap.size() > kMaxConcurrentWebRTCSessions) {
{
ChipLogProgress(Camera, "Resource exhaustion detected: maximum WebRTC sessions (%u)", kMaxConcurrentWebRTCSessions); ChipLogProgress(Camera, "Resource exhaustion detected: maximum WebRTC sessions (%u)", kMaxConcurrentWebRTCSessions);
transport->SetCommandType(WebrtcTransport::CommandType::kEnd); transport->SetCommandType(WebrtcTransport::CommandType::kEnd);
@@ -172,8 +160,9 @@ WebRTCProviderManager::HandleSolicitOffer(const OfferRequestArgs & args, WebRTCS
transport->MoveToState(WebrtcTransport::State::SendingOffer); transport->MoveToState(WebrtcTransport::State::SendingOffer);
ChipLogProgress(Camera, "Generate and set the SDP"); ChipLogProgress(Camera, "Generate and set the SDP");
if (transport->GetPeerConnection()) if (transport->GetPeerConnection()) {
transport->GetPeerConnection()->CreateOffer(args.sessionId); transport->GetPeerConnection()->CreateOffer(args.sessionId);
}
return CHIP_NO_ERROR; return CHIP_NO_ERROR;
} }
@@ -182,8 +171,7 @@ void WebRTCProviderManager::RegisterWebrtcTransport(uint16_t sessionId)
{ {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogProgress(Camera, ChipLogProgress(Camera,
"WebRTC Transport is null for sessionId %u. Failed to " "WebRTC Transport is null for sessionId %u. Failed to "
"Register WebRTC Transport", "Register WebRTC Transport",
@@ -199,8 +187,7 @@ void WebRTCProviderManager::UnregisterWebrtcTransport(uint16_t sessionId)
ChipLogProgress(Camera, "UnregisterWebrtcTransport called for sessionId: %u", sessionId); ChipLogProgress(Camera, "UnregisterWebrtcTransport called for sessionId: %u", sessionId);
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogProgress(Camera, ChipLogProgress(Camera,
"WebRTC Transport is null for sessionId %u. Already " "WebRTC Transport is null for sessionId %u. Already "
"unregistered or not found", "unregistered or not found",
@@ -224,40 +211,28 @@ WebRTCProviderManager::HandleProvideOffer(const ProvideOfferRequestArgs & args,
uint16_t audioStreamID = 0; uint16_t audioStreamID = 0;
// Resolve or allocate a VIDEO stream // Resolve or allocate a VIDEO stream
if (args.videoStreamId.HasValue()) if (args.videoStreamId.HasValue()) {
{ if (args.videoStreamId.Value().IsNull()) {
if (args.videoStreamId.Value().IsNull())
{
// TODO: Automatically select the closest matching video stream for the // TODO: Automatically select the closest matching video stream for the
// StreamUsage requested. // StreamUsage requested.
} } else {
else
{
outSession.videoStreamID = args.videoStreamId.Value(); outSession.videoStreamID = args.videoStreamId.Value();
videoStreamID = args.videoStreamId.Value().Value(); videoStreamID = args.videoStreamId.Value().Value();
} }
} } else {
else
{
outSession.videoStreamID.SetNull(); outSession.videoStreamID.SetNull();
} }
// Resolve or allocate an AUDIO stream // Resolve or allocate an AUDIO stream
if (args.audioStreamId.HasValue()) if (args.audioStreamId.HasValue()) {
{ if (args.audioStreamId.Value().IsNull()) {
if (args.audioStreamId.Value().IsNull())
{
// TODO: Automatically select the closest matching audio stream for the // TODO: Automatically select the closest matching audio stream for the
// StreamUsage requested // StreamUsage requested
} } else {
else
{
outSession.audioStreamID = args.audioStreamId.Value(); outSession.audioStreamID = args.audioStreamId.Value();
audioStreamID = args.audioStreamId.Value().Value(); audioStreamID = args.audioStreamId.Value().Value();
} }
} } else {
else
{
outSession.audioStreamID.SetNull(); outSession.audioStreamID.SetNull();
} }
@@ -273,8 +248,7 @@ WebRTCProviderManager::HandleProvideOffer(const ProvideOfferRequestArgs & args,
requestArgs.peerId = ScopedNodeId(args.peerNodeId, args.fabricIndex); requestArgs.peerId = ScopedNodeId(args.peerNodeId, args.fabricIndex);
WebrtcTransport * transport = GetTransport(args.sessionId); WebrtcTransport * transport = GetTransport(args.sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
mWebrtcTransportMap[args.sessionId] = std::unique_ptr<WebrtcTransport>(new WebrtcTransport()); mWebrtcTransportMap[args.sessionId] = std::unique_ptr<WebrtcTransport>(new WebrtcTransport());
mSessionIdMap[ScopedNodeId(args.peerNodeId, args.fabricIndex)] = args.sessionId; mSessionIdMap[ScopedNodeId(args.peerNodeId, args.fabricIndex)] = args.sessionId;
transport = mWebrtcTransportMap[args.sessionId].get(); transport = mWebrtcTransportMap[args.sessionId].get();
@@ -282,14 +256,15 @@ WebRTCProviderManager::HandleProvideOffer(const ProvideOfferRequestArgs & args,
[this](const std::string & sdp, SDPType type, const uint16_t sessionId) { [this](const std::string & sdp, SDPType type, const uint16_t sessionId) {
this->OnLocalDescription(sdp, type, sessionId); this->OnLocalDescription(sdp, type, sessionId);
}, },
[this](bool connected, const uint16_t sessionId) { this->OnConnectionStateChanged(connected, sessionId); }); [this](bool connected, const uint16_t sessionId) {
this->OnConnectionStateChanged(connected, sessionId);
});
} }
// Check resource availability before proceeding // Check resource availability before proceeding
// If we cannot allocate resources, respond with a response status of // If we cannot allocate resources, respond with a response status of
// RESOURCE_EXHAUSTED // RESOURCE_EXHAUSTED
if (mWebrtcTransportMap.size() > kMaxConcurrentWebRTCSessions) if (mWebrtcTransportMap.size() > kMaxConcurrentWebRTCSessions) {
{
ChipLogProgress(Camera, ChipLogProgress(Camera,
"Resource exhaustion detected in ProvideOffer: maximum " "Resource exhaustion detected in ProvideOffer: maximum "
"WebRTC sessions (%u)", "WebRTC sessions (%u)",
@@ -307,8 +282,7 @@ WebRTCProviderManager::HandleProvideOffer(const ProvideOfferRequestArgs & args,
transport->MoveToState(WebrtcTransport::State::SendingAnswer); transport->MoveToState(WebrtcTransport::State::SendingAnswer);
if (transport->GetPeerConnection()) if (transport->GetPeerConnection()) {
{
transport->GetPeerConnection()->SetRemoteDescription(args.sdp, SDPType::Offer); transport->GetPeerConnection()->SetRemoteDescription(args.sdp, SDPType::Offer);
transport->GetPeerConnection()->CreateAnswer(); transport->GetPeerConnection()->CreateAnswer();
} }
@@ -323,20 +297,17 @@ WebRTCProviderManager::HandleProvideAnswer(uint16_t sessionId, const std::string
// Check if the provided sessionId matches your current sessions // Check if the provided sessionId matches your current sessions
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "Session ID %u does not match the current sessions", sessionId); ChipLogError(Camera, "Session ID %u does not match the current sessions", sessionId);
return CHIP_ERROR_INVALID_ARGUMENT; return CHIP_ERROR_INVALID_ARGUMENT;
} }
if (sdpAnswer.empty()) if (sdpAnswer.empty()) {
{
ChipLogError(Camera, "Provided SDP Answer is empty for session ID %u", sessionId); ChipLogError(Camera, "Provided SDP Answer is empty for session ID %u", sessionId);
return CHIP_ERROR_INVALID_ARGUMENT; return CHIP_ERROR_INVALID_ARGUMENT;
} }
if (!transport->GetPeerConnection()) if (!transport->GetPeerConnection()) {
{
ChipLogError(Camera, ChipLogError(Camera,
"Cannot set remote description: mPeerConnection is null for " "Cannot set remote description: mPeerConnection is null for "
"session ID %u", "session ID %u",
@@ -358,14 +329,12 @@ CHIP_ERROR WebRTCProviderManager::HandleProvideICECandidates(uint16_t sessionId,
// Check if the provided sessionId matches your current sessions // Check if the provided sessionId matches your current sessions
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "Session ID %u does not match the current sessions", sessionId); ChipLogError(Camera, "Session ID %u does not match the current sessions", sessionId);
return CHIP_ERROR_INVALID_ARGUMENT; return CHIP_ERROR_INVALID_ARGUMENT;
} }
if (!transport->GetPeerConnection()) if (!transport->GetPeerConnection()) {
{
ChipLogError(Camera, ChipLogError(Camera,
"Cannot process ICE candidates: PeerConnection is null for " "Cannot process ICE candidates: PeerConnection is null for "
"session ID %u", "session ID %u",
@@ -373,14 +342,12 @@ CHIP_ERROR WebRTCProviderManager::HandleProvideICECandidates(uint16_t sessionId,
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
if (candidates.empty()) if (candidates.empty()) {
{
ChipLogError(Camera, "Candidate list is empty. At least one candidate is expected."); ChipLogError(Camera, "Candidate list is empty. At least one candidate is expected.");
return CHIP_ERROR_INVALID_ARGUMENT; return CHIP_ERROR_INVALID_ARGUMENT;
} }
for (const auto & candidate : candidates) for (const auto &candidate : candidates) {
{
ChipLogProgress(Camera, "Applying candidate: %s", ChipLogProgress(Camera, "Applying candidate: %s",
std::string(candidate.candidate.begin(), candidate.candidate.end()).c_str()); std::string(candidate.candidate.begin(), candidate.candidate.end()).c_str());
std::string mid = std::string mid =
@@ -401,13 +368,11 @@ CHIP_ERROR WebRTCProviderManager::HandleEndSession(uint16_t sessionId, WebRTCEnd
DataModel::Nullable<uint16_t> audioStreamID) DataModel::Nullable<uint16_t> audioStreamID)
{ {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "Session ID %u does not match the current sessions", sessionId); ChipLogError(Camera, "Session ID %u does not match the current sessions", sessionId);
return CHIP_ERROR_INVALID_ARGUMENT; return CHIP_ERROR_INVALID_ARGUMENT;
} }
if (transport != nullptr) if (transport != nullptr) {
{
ChipLogProgress(Camera, "Delete Webrtc Transport for the session: %u", sessionId); ChipLogProgress(Camera, "Delete Webrtc Transport for the session: %u", sessionId);
// Release the Video and Audio Streams from the CameraAVStreamManagement // Release the Video and Audio Streams from the CameraAVStreamManagement
@@ -421,8 +386,7 @@ CHIP_ERROR WebRTCProviderManager::HandleEndSession(uint16_t sessionId, WebRTCEnd
mSessionIdMap.erase(ScopedNodeId(args.peerNodeId, args.fabricIndex)); mSessionIdMap.erase(ScopedNodeId(args.peerNodeId, args.fabricIndex));
} }
if (transport->ClosePeerConnection()) if (transport->ClosePeerConnection()) {
{
ChipLogProgress(Camera, "Closing peer connection: %u", sessionId); ChipLogProgress(Camera, "Closing peer connection: %u", sessionId);
} }
@@ -433,8 +397,7 @@ CHIP_ERROR
WebRTCProviderManager::ValidateStreamUsage(StreamUsageEnum streamUsage, Optional<DataModel::Nullable<uint16_t>> &videoStreamId, WebRTCProviderManager::ValidateStreamUsage(StreamUsageEnum streamUsage, Optional<DataModel::Nullable<uint16_t>> &videoStreamId,
Optional<DataModel::Nullable<uint16_t>> &audioStreamId) Optional<DataModel::Nullable<uint16_t>> &audioStreamId)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -447,8 +410,7 @@ WebRTCProviderManager::ValidateStreamUsage(StreamUsageEnum streamUsage, Optional
CHIP_ERROR CHIP_ERROR
WebRTCProviderManager::ValidateVideoStreamID(uint16_t videoStreamId) WebRTCProviderManager::ValidateVideoStreamID(uint16_t videoStreamId)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -461,8 +423,7 @@ WebRTCProviderManager::ValidateVideoStreamID(uint16_t videoStreamId)
CHIP_ERROR CHIP_ERROR
WebRTCProviderManager::ValidateAudioStreamID(uint16_t audioStreamId) WebRTCProviderManager::ValidateAudioStreamID(uint16_t audioStreamId)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -475,8 +436,7 @@ WebRTCProviderManager::ValidateAudioStreamID(uint16_t audioStreamId)
CHIP_ERROR CHIP_ERROR
WebRTCProviderManager::IsStreamUsageSupported(StreamUsageEnum streamUsage) WebRTCProviderManager::IsStreamUsageSupported(StreamUsageEnum streamUsage)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -485,10 +445,8 @@ WebRTCProviderManager::IsStreamUsageSupported(StreamUsageEnum streamUsage)
auto &streamUsagePriorities = hal.GetStreamUsagePriorities(); auto &streamUsagePriorities = hal.GetStreamUsagePriorities();
// Check if the streamUsage is in the StreamUsagePriorities list // Check if the streamUsage is in the StreamUsagePriorities list
for (const auto & usage : streamUsagePriorities) for (const auto &usage : streamUsagePriorities) {
{ if (usage == streamUsage) {
if (usage == streamUsage)
{
return CHIP_NO_ERROR; return CHIP_NO_ERROR;
} }
} }
@@ -499,8 +457,7 @@ WebRTCProviderManager::IsStreamUsageSupported(StreamUsageEnum streamUsage)
CHIP_ERROR WebRTCProviderManager::IsHardPrivacyModeActive(bool &isActive) CHIP_ERROR WebRTCProviderManager::IsHardPrivacyModeActive(bool &isActive)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -513,8 +470,7 @@ CHIP_ERROR WebRTCProviderManager::IsHardPrivacyModeActive(bool & isActive)
CHIP_ERROR CHIP_ERROR
WebRTCProviderManager::IsSoftRecordingPrivacyModeActive(bool &isActive) WebRTCProviderManager::IsSoftRecordingPrivacyModeActive(bool &isActive)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -527,8 +483,7 @@ WebRTCProviderManager::IsSoftRecordingPrivacyModeActive(bool & isActive)
CHIP_ERROR CHIP_ERROR
WebRTCProviderManager::IsSoftLivestreamPrivacyModeActive(bool &isActive) WebRTCProviderManager::IsSoftLivestreamPrivacyModeActive(bool &isActive)
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
@@ -540,8 +495,7 @@ WebRTCProviderManager::IsSoftLivestreamPrivacyModeActive(bool & isActive)
bool WebRTCProviderManager::HasAllocatedVideoStreams() bool WebRTCProviderManager::HasAllocatedVideoStreams()
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return false; return false;
} }
@@ -553,8 +507,7 @@ bool WebRTCProviderManager::HasAllocatedVideoStreams()
bool WebRTCProviderManager::HasAllocatedAudioStreams() bool WebRTCProviderManager::HasAllocatedAudioStreams()
{ {
if (mCameraDevice == nullptr) if (mCameraDevice == nullptr) {
{
ChipLogError(Camera, "CameraDeviceInterface not initialized"); ChipLogError(Camera, "CameraDeviceInterface not initialized");
return false; return false;
} }
@@ -578,8 +531,7 @@ CHIP_ERROR WebRTCProviderManager::ValidateSFrameConfig(uint16_t cipherSuite, siz
size_t expectedKeyLength = 0; size_t expectedKeyLength = 0;
// Validate cipher suite and determine expected key length // Validate cipher suite and determine expected key length
switch (cipherSuite) switch (cipherSuite) {
{
case kCipherSuite_AES_128_GCM: case kCipherSuite_AES_128_GCM:
expectedKeyLength = kAES_128_KeyLength; expectedKeyLength = kAES_128_KeyLength;
break; break;
@@ -592,8 +544,7 @@ CHIP_ERROR WebRTCProviderManager::ValidateSFrameConfig(uint16_t cipherSuite, siz
} }
// Validate base key length matches the expected length for the cipher suite // Validate base key length matches the expected length for the cipher suite
if (baseKeyLength != expectedKeyLength) if (baseKeyLength != expectedKeyLength) {
{
ChipLogError(Camera, ChipLogError(Camera,
"SFrame base key length mismatch - expected %u bytes for " "SFrame base key length mismatch - expected %u bytes for "
"cipher suite 0x%04X, got %u bytes", "cipher suite 0x%04X, got %u bytes",
@@ -620,8 +571,7 @@ void WebRTCProviderManager::ScheduleOfferSend(uint16_t sessionId)
DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() { DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
return; return;
} }
@@ -646,8 +596,7 @@ void WebRTCProviderManager::ScheduleAnswerSend(uint16_t sessionId)
DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() { DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
return; return;
} }
@@ -673,8 +622,7 @@ void WebRTCProviderManager::ScheduleEndSend(uint16_t sessionId)
DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() { DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
return; return;
} }
@@ -700,8 +648,7 @@ void WebRTCProviderManager::ScheduleICECandidatesSend(uint16_t sessionId)
DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() { DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
return; return;
} }
@@ -731,8 +678,7 @@ void WebRTCProviderManager::OnDeviceConnected(void * context, Messaging::Exchang
// (NodeId + FabricIndex) // (NodeId + FabricIndex)
ScopedNodeId peerScopedNodeId = sessionHandle->GetPeer(); ScopedNodeId peerScopedNodeId = sessionHandle->GetPeer();
auto sessionIt = self->mSessionIdMap.find(peerScopedNodeId); auto sessionIt = self->mSessionIdMap.find(peerScopedNodeId);
if (sessionIt == self->mSessionIdMap.end()) if (sessionIt == self->mSessionIdMap.end()) {
{
ChipLogError(Camera, ChipLogError(Camera,
"OnDeviceConnected:: no session found for peer ScopedNodeId: " "OnDeviceConnected:: no session found for peer ScopedNodeId: "
"[%d:" ChipLogFormatX64 "]", "[%d:" ChipLogFormatX64 "]",
@@ -742,8 +688,7 @@ void WebRTCProviderManager::OnDeviceConnected(void * context, Messaging::Exchang
uint16_t sessionId = sessionIt->second; uint16_t sessionId = sessionIt->second;
WebrtcTransport * transport = self->GetTransport(sessionId); WebrtcTransport * transport = self->GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "OnDeviceConnected:: transport not found for sessionId: %u", sessionId); ChipLogError(Camera, "OnDeviceConnected:: transport not found for sessionId: %u", sessionId);
return; return;
} }
@@ -755,8 +700,7 @@ void WebRTCProviderManager::OnDeviceConnected(void * context, Messaging::Exchang
CHIP_ERROR err = CHIP_NO_ERROR; CHIP_ERROR err = CHIP_NO_ERROR;
switch (transport->GetCommandType()) switch (transport->GetCommandType()) {
{
case WebrtcTransport::CommandType::kOffer: case WebrtcTransport::CommandType::kOffer:
err = self->SendOfferCommand(exchangeMgr, sessionHandle, sessionId); err = self->SendOfferCommand(exchangeMgr, sessionHandle, sessionId);
transport->MoveToState(WebrtcTransport::State::Idle); transport->MoveToState(WebrtcTransport::State::Idle);
@@ -775,8 +719,7 @@ void WebRTCProviderManager::OnDeviceConnected(void * context, Messaging::Exchang
// exhaustion // exhaustion
WebRTCEndReasonEnum endReason = WebRTCEndReasonEnum::kOutOfResources; WebRTCEndReasonEnum endReason = WebRTCEndReasonEnum::kOutOfResources;
if (self->mSoftLiveStreamPrivacyEnabled) if (self->mSoftLiveStreamPrivacyEnabled) {
{
endReason = WebRTCEndReasonEnum::kPrivacyMode; endReason = WebRTCEndReasonEnum::kPrivacyMode;
} }
@@ -800,8 +743,7 @@ void WebRTCProviderManager::OnDeviceConnected(void * context, Messaging::Exchang
break; break;
} }
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(Camera, "OnDeviceConnected::SendCommand failed: %" CHIP_ERROR_FORMAT, err.Format()); ChipLogError(Camera, "OnDeviceConnected::SendCommand failed: %" CHIP_ERROR_FORMAT, err.Format());
} }
} }
@@ -816,8 +758,7 @@ void WebRTCProviderManager::OnDeviceConnectionFailure(void * context, const Scop
WebrtcTransport * WebRTCProviderManager::GetTransport(uint16_t sessionId) WebrtcTransport * WebRTCProviderManager::GetTransport(uint16_t sessionId)
{ {
WebrtcTransport * transport = nullptr; WebrtcTransport * transport = nullptr;
if (mWebrtcTransportMap.find(sessionId) != mWebrtcTransportMap.end()) if (mWebrtcTransportMap.find(sessionId) != mWebrtcTransportMap.end()) {
{
transport = mWebrtcTransportMap[sessionId].get(); transport = mWebrtcTransportMap[sessionId].get();
} }
@@ -828,18 +769,15 @@ void WebRTCProviderManager::LiveStreamPrivacyModeChanged(bool privacyModeEnabled
{ {
mSoftLiveStreamPrivacyEnabled = privacyModeEnabled; mSoftLiveStreamPrivacyEnabled = privacyModeEnabled;
if (privacyModeEnabled) if (privacyModeEnabled) {
{
WebrtcTransport * transport = nullptr; WebrtcTransport * transport = nullptr;
uint16_t sessionId = 0; uint16_t sessionId = 0;
for (auto & mapEntry : mWebrtcTransportMap) for (auto &mapEntry : mWebrtcTransportMap) {
{
sessionId = mapEntry.first; sessionId = mapEntry.first;
transport = (WebrtcTransport *) mapEntry.second.get(); transport = (WebrtcTransport *) mapEntry.second.get();
if (transport == nullptr) if (transport == nullptr) {
{
continue; continue;
} }
@@ -847,9 +785,7 @@ void WebRTCProviderManager::LiveStreamPrivacyModeChanged(bool privacyModeEnabled
ScheduleEndSend(sessionId); ScheduleEndSend(sessionId);
} }
} } else {
else
{
ChipLogProgress(Camera, "Privacy mode is disabled"); ChipLogProgress(Camera, "Privacy mode is disabled");
} }
} }
@@ -862,11 +798,12 @@ WebRTCProviderManager::SendOfferCommand(Messaging::ExchangeManager & exchangeMgr
ChipLogProgress(Camera, "Offer command succeeds"); ChipLogProgress(Camera, "Offer command succeeds");
}; };
auto onFailure = [](CHIP_ERROR error) { ChipLogError(Camera, "Offer command failed: %" CHIP_ERROR_FORMAT, error.Format()); }; auto onFailure = [](CHIP_ERROR error) {
ChipLogError(Camera, "Offer command failed: %" CHIP_ERROR_FORMAT, error.Format());
};
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "SendOfferCommand failed, WebTransport not found for sessionId: %u", sessionId); ChipLogError(Camera, "SendOfferCommand failed, WebTransport not found for sessionId: %u", sessionId);
return CHIP_ERROR_INTERNAL; return CHIP_ERROR_INTERNAL;
} }
@@ -888,15 +825,13 @@ WebRTCProviderManager::SendOfferCommand(Messaging::ExchangeManager & exchangeMgr
void WebRTCProviderManager::OnLocalDescription(const std::string &sdp, SDPType type, const uint16_t sessionId) void WebRTCProviderManager::OnLocalDescription(const std::string &sdp, SDPType type, const uint16_t sessionId)
{ {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "SendOfferCommand failed, WebTransport not found for sessionId: %u", sessionId); ChipLogError(Camera, "SendOfferCommand failed, WebTransport not found for sessionId: %u", sessionId);
return; return;
} }
WebrtcTransport::State state = transport->GetState(); WebrtcTransport::State state = transport->GetState();
if (state == WebrtcTransport::State::SendingAnswer && type != SDPType::Answer) if (state == WebrtcTransport::State::SendingAnswer && type != SDPType::Answer) {
{
return; return;
} }
const char * typeStr = (type == SDPType::Offer) ? "offer" : "answer"; const char * typeStr = (type == SDPType::Offer) ? "offer" : "answer";
@@ -905,8 +840,7 @@ void WebRTCProviderManager::OnLocalDescription(const std::string & sdp, SDPType
ChipLogProgress(Camera, "%s", localSdp.c_str()); ChipLogProgress(Camera, "%s", localSdp.c_str());
ChipLogProgress(Camera, "Size of SDP: %zu", localSdp.size()); ChipLogProgress(Camera, "Size of SDP: %zu", localSdp.size());
switch (state) switch (state) {
{
case WebrtcTransport::State::SendingOffer: case WebrtcTransport::State::SendingOffer:
ScheduleOfferSend(sessionId); ScheduleOfferSend(sessionId);
break; break;
@@ -922,20 +856,16 @@ void WebRTCProviderManager::OnConnectionStateChanged(bool connected, const uint1
{ {
ChipLogProgress(Camera, "Connection state changed for session %u: %s", sessionId, connected ? "connected" : "disconnected"); ChipLogProgress(Camera, "Connection state changed for session %u: %s", sessionId, connected ? "connected" : "disconnected");
if (connected) if (connected) {
{
RegisterWebrtcTransport(sessionId); RegisterWebrtcTransport(sessionId);
} } else {
else
{
// Schedule cleanup on Matter thread to ensure proper locking when calling // Schedule cleanup on Matter thread to ensure proper locking when calling
// RemoveSession. Safe to capture 'this' by value: WebRTCProviderManager is // RemoveSession. Safe to capture 'this' by value: WebRTCProviderManager is
// a member of the global CameraDevice object which has static storage // a member of the global CameraDevice object which has static storage
// duration and lives for the entire program lifetime. // duration and lives for the entire program lifetime.
DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() { DeviceLayer::SystemLayer().ScheduleLambda([this, sessionId]() {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogProgress(Camera, ChipLogProgress(Camera,
"Transport not found for session %u during disconnect; " "Transport not found for session %u during disconnect; "
"session may have already been cleaned up", "session may have already been cleaned up",
@@ -961,8 +891,7 @@ void WebRTCProviderManager::OnConnectionStateChanged(bool connected, const uint1
// Remove from current sessions list in the WebRTC Transport Provider // Remove from current sessions list in the WebRTC Transport Provider
// This MUST be called on the Matter thread with the stack lock held // This MUST be called on the Matter thread with the stack lock held
if (mWebRTCTransportProvider != nullptr) if (mWebRTCTransportProvider != nullptr) {
{
mWebRTCTransportProvider->RemoveSession(sessionId); mWebRTCTransportProvider->RemoveSession(sessionId);
} }
@@ -980,11 +909,12 @@ CHIP_ERROR WebRTCProviderManager::SendAnswerCommand(Messaging::ExchangeManager &
ChipLogProgress(Camera, "Answer command succeeds"); ChipLogProgress(Camera, "Answer command succeeds");
}; };
auto onFailure = [](CHIP_ERROR error) { ChipLogError(Camera, "Answer command failed: %" CHIP_ERROR_FORMAT, error.Format()); }; auto onFailure = [](CHIP_ERROR error) {
ChipLogError(Camera, "Answer command failed: %" CHIP_ERROR_FORMAT, error.Format());
};
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "SendOfferCommand failed, WebTransport not found for sessionId: %u", sessionId); ChipLogError(Camera, "SendOfferCommand failed, WebTransport not found for sessionId: %u", sessionId);
return CHIP_ERROR_INTERNAL; return CHIP_ERROR_INTERNAL;
} }
@@ -1016,8 +946,7 @@ CHIP_ERROR WebRTCProviderManager::SendICECandidatesCommand(Messaging::ExchangeMa
}; };
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId); ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId);
return CHIP_ERROR_INTERNAL; return CHIP_ERROR_INTERNAL;
} }
@@ -1025,15 +954,13 @@ CHIP_ERROR WebRTCProviderManager::SendICECandidatesCommand(Messaging::ExchangeMa
// Build the command // Build the command
WebRTCTransportRequestor::Commands::ICECandidates::Type command; WebRTCTransportRequestor::Commands::ICECandidates::Type command;
if (localCandidates.empty()) if (localCandidates.empty()) {
{
ChipLogError(Camera, "No local ICE candidates to send"); ChipLogError(Camera, "No local ICE candidates to send");
return CHIP_ERROR_INCORRECT_STATE; return CHIP_ERROR_INCORRECT_STATE;
} }
std::vector<ICECandidateStruct> iceCandidateStructList; std::vector<ICECandidateStruct> iceCandidateStructList;
for (const auto & candidate : localCandidates) for (const auto &candidate : localCandidates) {
{
ICECandidateStruct iceCandidate = { CharSpan::fromCharString(candidate.c_str()) }; ICECandidateStruct iceCandidate = { CharSpan::fromCharString(candidate.c_str()) };
iceCandidateStructList.push_back(iceCandidate); iceCandidateStructList.push_back(iceCandidate);
} }
@@ -1057,11 +984,12 @@ CHIP_ERROR WebRTCProviderManager::SendEndCommand(Messaging::ExchangeManager & ex
ChipLogProgress(Camera, "End command succeeds"); ChipLogProgress(Camera, "End command succeeds");
}; };
auto onFailure = [](CHIP_ERROR error) { ChipLogError(Camera, "End command failed: %" CHIP_ERROR_FORMAT, error.Format()); }; auto onFailure = [](CHIP_ERROR error) {
ChipLogError(Camera, "End command failed: %" CHIP_ERROR_FORMAT, error.Format());
};
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId); ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId);
return CHIP_ERROR_INTERNAL; return CHIP_ERROR_INTERNAL;
} }
@@ -1084,8 +1012,7 @@ CHIP_ERROR WebRTCProviderManager::SendEndCommand(Messaging::ExchangeManager & ex
CHIP_ERROR WebRTCProviderManager::AcquireAudioVideoStreams(uint16_t sessionId) CHIP_ERROR WebRTCProviderManager::AcquireAudioVideoStreams(uint16_t sessionId)
{ {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId); ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId);
return CHIP_ERROR_INTERNAL; return CHIP_ERROR_INTERNAL;
} }
@@ -1098,8 +1025,7 @@ CHIP_ERROR WebRTCProviderManager::AcquireAudioVideoStreams(uint16_t sessionId)
CHIP_ERROR WebRTCProviderManager::ReleaseAudioVideoStreams(uint16_t sessionId) CHIP_ERROR WebRTCProviderManager::ReleaseAudioVideoStreams(uint16_t sessionId)
{ {
WebrtcTransport * transport = GetTransport(sessionId); WebrtcTransport * transport = GetTransport(sessionId);
if (transport == nullptr) if (transport == nullptr) {
{
ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId); ChipLogError(Camera, "WebTransport not found for the sessionId: %u", sessionId);
return CHIP_ERROR_INTERNAL; return CHIP_ERROR_INTERNAL;
} }
@@ -35,14 +35,16 @@ using ICECandidateStruct = chip::app::Clusters::Globals::Structs::ICECandi
using StreamUsageEnum = chip::app::Clusters::Globals::StreamUsageEnum; using StreamUsageEnum = chip::app::Clusters::Globals::StreamUsageEnum;
using WebRTCEndReasonEnum = chip::app::Clusters::Globals::WebRTCEndReasonEnum; using WebRTCEndReasonEnum = chip::app::Clusters::Globals::WebRTCEndReasonEnum;
class WebRTCProviderManager : public Delegate class WebRTCProviderManager : public Delegate {
{
public: public:
WebRTCProviderManager() : WebRTCProviderManager() :
mOnConnectedCallback(OnDeviceConnected, this), mOnConnectionFailureCallback(OnDeviceConnectionFailure, this) mOnConnectedCallback(OnDeviceConnected, this), mOnConnectionFailureCallback(OnDeviceConnectionFailure, this)
{} {}
~WebRTCProviderManager() { CloseConnection(); }; ~WebRTCProviderManager()
{
CloseConnection();
};
void Init(); void Init();
+22 -44
View File
@@ -43,63 +43,52 @@ CameraApp::CameraApp(chip::EndpointId aClustersEndpoint, CameraDeviceInterface *
avsmFeatures.Set(CameraAvStreamManagement::Feature::kVideo); avsmFeatures.Set(CameraAvStreamManagement::Feature::kVideo);
// Enable the Watermark and OSD features if camera supports // Enable the Watermark and OSD features if camera supports
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsWatermark()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsWatermark()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kWatermark); avsmFeatures.Set(CameraAvStreamManagement::Feature::kWatermark);
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsOSD()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsOSD()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kOnScreenDisplay); avsmFeatures.Set(CameraAvStreamManagement::Feature::kOnScreenDisplay);
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsSoftPrivacy()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsSoftPrivacy()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kPrivacy); avsmFeatures.Set(CameraAvStreamManagement::Feature::kPrivacy);
} }
// Check microphone support to set Audio feature // Check microphone support to set Audio feature
if (mCameraDevice->GetCameraHALInterface().HasMicrophone()) if (mCameraDevice->GetCameraHALInterface().HasMicrophone()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kAudio); avsmFeatures.Set(CameraAvStreamManagement::Feature::kAudio);
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kMicrophoneAGCEnabled); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kMicrophoneAGCEnabled);
} }
if (mCameraDevice->GetCameraHALInterface().HasLocalStorage()) if (mCameraDevice->GetCameraHALInterface().HasLocalStorage()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kLocalStorage); avsmFeatures.Set(CameraAvStreamManagement::Feature::kLocalStorage);
} }
// Check if camera has speaker // Check if camera has speaker
if (mCameraDevice->GetCameraHALInterface().HasSpeaker()) if (mCameraDevice->GetCameraHALInterface().HasSpeaker()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kSpeaker); avsmFeatures.Set(CameraAvStreamManagement::Feature::kSpeaker);
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsHDR()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsHDR()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kHighDynamicRange); avsmFeatures.Set(CameraAvStreamManagement::Feature::kHighDynamicRange);
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsNightVision()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsNightVision()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kNightVision); avsmFeatures.Set(CameraAvStreamManagement::Feature::kNightVision);
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kNightVisionIllum); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kNightVisionIllum);
} }
if (mCameraDevice->GetCameraHALInterface().HasHardPrivacySwitch()) if (mCameraDevice->GetCameraHALInterface().HasHardPrivacySwitch()) {
{
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kHardPrivacyModeOn); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kHardPrivacyModeOn);
} }
if (mCameraDevice->GetCameraHALInterface().HasStatusLight()) if (mCameraDevice->GetCameraHALInterface().HasStatusLight()) {
{
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kStatusLightEnabled); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kStatusLightEnabled);
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kStatusLightBrightness); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kStatusLightBrightness);
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsImageControl()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsImageControl()) {
{
avsmFeatures.Set(CameraAvStreamManagement::Feature::kImageControl); avsmFeatures.Set(CameraAvStreamManagement::Feature::kImageControl);
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kImageFlipVertical); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kImageFlipVertical);
avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kImageFlipHorizontal); avsmOptionalAttrs.Set(CameraAvStreamManagement::OptionalAttribute::kImageFlipHorizontal);
@@ -137,41 +126,35 @@ CameraApp::CameraApp(chip::EndpointId aClustersEndpoint, CameraDeviceInterface *
void CameraApp::InitializeCameraAVStreamMgmt() void CameraApp::InitializeCameraAVStreamMgmt()
{ {
// Set the attribute defaults // Set the attribute defaults
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsHDR()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsHDR()) {
{
mAVStreamMgmtServerPtr->SetHDRModeEnabled(mCameraDevice->GetCameraHALInterface().GetHDRMode()); mAVStreamMgmtServerPtr->SetHDRModeEnabled(mCameraDevice->GetCameraHALInterface().GetHDRMode());
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsSoftPrivacy()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsSoftPrivacy()) {
{
mAVStreamMgmtServerPtr->SetSoftRecordingPrivacyModeEnabled( mAVStreamMgmtServerPtr->SetSoftRecordingPrivacyModeEnabled(
mCameraDevice->GetCameraHALInterface().GetSoftRecordingPrivacyModeEnabled()); mCameraDevice->GetCameraHALInterface().GetSoftRecordingPrivacyModeEnabled());
mAVStreamMgmtServerPtr->SetSoftLivestreamPrivacyModeEnabled( mAVStreamMgmtServerPtr->SetSoftLivestreamPrivacyModeEnabled(
mCameraDevice->GetCameraHALInterface().GetSoftLivestreamPrivacyModeEnabled()); mCameraDevice->GetCameraHALInterface().GetSoftLivestreamPrivacyModeEnabled());
} }
if (mCameraDevice->GetCameraHALInterface().HasHardPrivacySwitch()) if (mCameraDevice->GetCameraHALInterface().HasHardPrivacySwitch()) {
{
mAVStreamMgmtServerPtr->SetHardPrivacyModeOn(mCameraDevice->GetCameraHALInterface().GetHardPrivacyMode()); mAVStreamMgmtServerPtr->SetHardPrivacyModeOn(mCameraDevice->GetCameraHALInterface().GetHardPrivacyMode());
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsNightVision()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsNightVision()) {
{
mAVStreamMgmtServerPtr->SetNightVision(mCameraDevice->GetCameraHALInterface().GetNightVision()); mAVStreamMgmtServerPtr->SetNightVision(mCameraDevice->GetCameraHALInterface().GetNightVision());
} }
mAVStreamMgmtServerPtr->SetViewport(mCameraDevice->GetCameraHALInterface().GetViewport()); mAVStreamMgmtServerPtr->SetViewport(mCameraDevice->GetCameraHALInterface().GetViewport());
if (mCameraDevice->GetCameraHALInterface().HasSpeaker()) if (mCameraDevice->GetCameraHALInterface().HasSpeaker()) {
{
mAVStreamMgmtServerPtr->SetSpeakerMuted(mCameraDevice->GetCameraHALInterface().GetSpeakerMuted()); mAVStreamMgmtServerPtr->SetSpeakerMuted(mCameraDevice->GetCameraHALInterface().GetSpeakerMuted());
mAVStreamMgmtServerPtr->SetSpeakerVolumeLevel(mCameraDevice->GetCameraHALInterface().GetSpeakerVolume()); mAVStreamMgmtServerPtr->SetSpeakerVolumeLevel(mCameraDevice->GetCameraHALInterface().GetSpeakerVolume());
mAVStreamMgmtServerPtr->SetSpeakerMaxLevel(mCameraDevice->GetCameraHALInterface().GetSpeakerMaxLevel()); mAVStreamMgmtServerPtr->SetSpeakerMaxLevel(mCameraDevice->GetCameraHALInterface().GetSpeakerMaxLevel());
mAVStreamMgmtServerPtr->SetSpeakerMinLevel(mCameraDevice->GetCameraHALInterface().GetSpeakerMinLevel()); mAVStreamMgmtServerPtr->SetSpeakerMinLevel(mCameraDevice->GetCameraHALInterface().GetSpeakerMinLevel());
} }
if (mCameraDevice->GetCameraHALInterface().HasMicrophone()) if (mCameraDevice->GetCameraHALInterface().HasMicrophone()) {
{
mAVStreamMgmtServerPtr->SetMicrophoneMuted(mCameraDevice->GetCameraHALInterface().GetMicrophoneMuted()); mAVStreamMgmtServerPtr->SetMicrophoneMuted(mCameraDevice->GetCameraHALInterface().GetMicrophoneMuted());
mAVStreamMgmtServerPtr->SetMicrophoneVolumeLevel(mCameraDevice->GetCameraHALInterface().GetMicrophoneVolume()); mAVStreamMgmtServerPtr->SetMicrophoneVolumeLevel(mCameraDevice->GetCameraHALInterface().GetMicrophoneVolume());
mAVStreamMgmtServerPtr->SetMicrophoneMaxLevel(mCameraDevice->GetCameraHALInterface().GetMicrophoneMaxLevel()); mAVStreamMgmtServerPtr->SetMicrophoneMaxLevel(mCameraDevice->GetCameraHALInterface().GetMicrophoneMaxLevel());
@@ -179,21 +162,18 @@ void CameraApp::InitializeCameraAVStreamMgmt()
} }
// Video and Snapshot features are already enabled. // Video and Snapshot features are already enabled.
if (mCameraDevice->GetCameraHALInterface().HasLocalStorage()) if (mCameraDevice->GetCameraHALInterface().HasLocalStorage()) {
{
mAVStreamMgmtServerPtr->SetLocalVideoRecordingEnabled( mAVStreamMgmtServerPtr->SetLocalVideoRecordingEnabled(
mCameraDevice->GetCameraHALInterface().GetLocalVideoRecordingEnabled()); mCameraDevice->GetCameraHALInterface().GetLocalVideoRecordingEnabled());
mAVStreamMgmtServerPtr->SetLocalSnapshotRecordingEnabled( mAVStreamMgmtServerPtr->SetLocalSnapshotRecordingEnabled(
mCameraDevice->GetCameraHALInterface().GetLocalSnapshotRecordingEnabled()); mCameraDevice->GetCameraHALInterface().GetLocalSnapshotRecordingEnabled());
} }
if (mCameraDevice->GetCameraHALInterface().HasStatusLight()) if (mCameraDevice->GetCameraHALInterface().HasStatusLight()) {
{
mAVStreamMgmtServerPtr->SetStatusLightEnabled(mCameraDevice->GetCameraHALInterface().GetStatusLightEnabled()); mAVStreamMgmtServerPtr->SetStatusLightEnabled(mCameraDevice->GetCameraHALInterface().GetStatusLightEnabled());
} }
if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsImageControl()) if (mCameraDevice->GetCameraHALInterface().GetCameraSupportsImageControl()) {
{
mAVStreamMgmtServerPtr->SetImageRotation(mCameraDevice->GetCameraHALInterface().GetImageRotation()); mAVStreamMgmtServerPtr->SetImageRotation(mCameraDevice->GetCameraHALInterface().GetImageRotation());
mAVStreamMgmtServerPtr->SetImageFlipVertical(mCameraDevice->GetCameraHALInterface().GetImageFlipVertical()); mAVStreamMgmtServerPtr->SetImageFlipVertical(mCameraDevice->GetCameraHALInterface().GetImageFlipVertical());
mAVStreamMgmtServerPtr->SetImageFlipHorizontal(mCameraDevice->GetCameraHALInterface().GetImageFlipHorizontal()); mAVStreamMgmtServerPtr->SetImageFlipHorizontal(mCameraDevice->GetCameraHALInterface().GetImageFlipHorizontal());
@@ -207,8 +187,7 @@ void CameraApp::InitCameraDeviceClusters()
// Initialize Cluster Servers // Initialize Cluster Servers
mWebRTCTransportProviderServer.Create(mEndpoint, mCameraDevice->GetWebRTCProviderDelegate()); mWebRTCTransportProviderServer.Create(mEndpoint, mCameraDevice->GetWebRTCProviderDelegate());
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(mWebRTCTransportProviderServer.Registration()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Register(mWebRTCTransportProviderServer.Registration());
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(Camera, ChipLogError(Camera,
"Failed to register WebRTCTransportProvider on endpoint %u: " "Failed to register WebRTCTransportProvider on endpoint %u: "
"%" CHIP_ERROR_FORMAT, "%" CHIP_ERROR_FORMAT,
@@ -222,8 +201,7 @@ void CameraApp::ShutdownCameraDeviceClusters()
ChipLogDetail(Camera, "CameraAppShutdown: Shutting down Camera device clusters"); ChipLogDetail(Camera, "CameraAppShutdown: Shutting down Camera device clusters");
CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&mWebRTCTransportProviderServer.Cluster()); CHIP_ERROR err = esp_matter::data_model::provider::get_instance().registry().Unregister(&mWebRTCTransportProviderServer.Cluster());
if (err != CHIP_NO_ERROR) if (err != CHIP_NO_ERROR) {
{
ChipLogError(Camera, "WebRTCTransportProvider unregister error: %" CHIP_ERROR_FORMAT, err.Format()); ChipLogError(Camera, "WebRTCTransportProvider unregister error: %" CHIP_ERROR_FORMAT, err.Format());
} }
mWebRTCTransportProviderServer.Destroy(); mWebRTCTransportProviderServer.Destroy();

Some files were not shown because too many files have changed in this diff Show More