From e0df48198d0c73bcc47ba73f13777c56a30b62c5 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Tue, 6 Feb 2024 15:53:10 -0800 Subject: [PATCH 01/75] Adds TC_SC_4_3.py --- src/python_testing/TC_SC_4_3.py | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/python_testing/TC_SC_4_3.py diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py new file mode 100644 index 00000000000000..a69a8d75b5ecb6 --- /dev/null +++ b/src/python_testing/TC_SC_4_3.py @@ -0,0 +1,39 @@ +# +# Copyright (c) 2024 Project CHIP Authors +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import asyncio +import logging +import queue +import time +from threading import Event + +import chip.clusters as Clusters +from chip.clusters import ClusterObjects as ClustersObjects +from chip.clusters.Attribute import SubscriptionTransaction, TypedAttributePath +from chip.utils import CommissioningBuildingBlocks +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main +from mobly import asserts + + +class TC_SC_4_3(MatterBaseTest): + @async_test_body + async def test_TC_SC_4_3(self): + print() + + +if __name__ == "__main__": + default_matter_test_main() From 903238b134ccda05b9f17873b512f597b8c19027 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Tue, 6 Feb 2024 21:49:02 -0800 Subject: [PATCH 02/75] Fixes TXT record not available when making direct query with name and type --- .../mdns_discovery/mdns_discovery.py | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 86661d65729da3..193490916cafbe 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -22,7 +22,7 @@ from enum import Enum from typing import Dict, List, Optional -from zeroconf import IPVersion, ServiceStateChange, Zeroconf +from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes @@ -75,6 +75,20 @@ class MdnsServiceType(Enum): BORDER_ROUTER = "_meshcop._udp.local." +class DummyServiceListener(ServiceListener): + """ + A service listener required for the TXT record data to get populated and come back + """ + def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: + pass + + def remove_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: + pass + + def update_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: + pass + + class MdnsDiscovery: DISCOVERY_TIMEOUT_SEC = 15 @@ -160,10 +174,13 @@ async def get_operational_service(self, service_name: str = None, mdns_service_info = await self._get_service(MdnsServiceType.OPERATIONAL, log_output, discovery_timeout_sec) else: print(f"Looking for MDNS service type '{service_type}', service name '{service_name}'") - - # Get service info + service_listener = DummyServiceListener() + self._zc.add_service_listener(MdnsServiceType.OPERATIONAL.value, service_listener) + # Adds delay so TXT record is able to get populated + await asyncio.sleep(1) service_info = AsyncServiceInfo(service_type, service_name) is_discovered = await service_info.async_request(self._zc, 3000) + self._zc.remove_service_listener(service_listener) if is_discovered: mdns_service_info = self._to_mdns_service_info_class(service_info) self._discovered_services = {} From 9d566d0a2859804e1986a5844dd677c8e4322857 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Tue, 6 Feb 2024 21:54:11 -0800 Subject: [PATCH 03/75] Fixes restyle, adds comments to operational service logic --- src/python_testing/mdns_discovery/mdns_discovery.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 193490916cafbe..3dbb5fd8e808a0 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -79,6 +79,7 @@ class DummyServiceListener(ServiceListener): """ A service listener required for the TXT record data to get populated and come back """ + def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: pass @@ -174,13 +175,20 @@ async def get_operational_service(self, service_name: str = None, mdns_service_info = await self._get_service(MdnsServiceType.OPERATIONAL, log_output, discovery_timeout_sec) else: print(f"Looking for MDNS service type '{service_type}', service name '{service_name}'") + + # Adds service listener service_listener = DummyServiceListener() self._zc.add_service_listener(MdnsServiceType.OPERATIONAL.value, service_listener) + # Adds delay so TXT record is able to get populated await asyncio.sleep(1) + + # Get service info service_info = AsyncServiceInfo(service_type, service_name) is_discovered = await service_info.async_request(self._zc, 3000) self._zc.remove_service_listener(service_listener) + + # Adds service to discovered services if is_discovered: mdns_service_info = self._to_mdns_service_info_class(service_info) self._discovered_services = {} From dfd560eb9759c022f88e8b6a5c18d265f3e0c01d Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Tue, 6 Feb 2024 21:56:28 -0800 Subject: [PATCH 04/75] Fix restlye for mdns class --- src/python_testing/mdns_discovery/mdns_discovery.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 3dbb5fd8e808a0..ca017ab74f94c3 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -79,7 +79,7 @@ class DummyServiceListener(ServiceListener): """ A service listener required for the TXT record data to get populated and come back """ - + def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: pass From a365b50a9ff1c83b3db1e72117b7c1131c186baf Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 00:21:27 -0800 Subject: [PATCH 05/75] Adds get_service_types to mdns class --- .../mdns_discovery/mdns_discovery.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index ca017ab74f94c3..4c500909b3e1b2 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -232,6 +232,29 @@ async def get_all_services(self, log_output: bool = False, return self._discovered_services + async def get_service_types(self, log_output: bool = False) -> List[str]: + """ + Asynchronously discovers all available mDNS services within the network and returns a list + of the service types discovered. This method utilizes the AsyncZeroconfServiceTypes.async_find() + function to perform the network scan for mDNS services. + + Args: + log_output (bool): If set to True, the discovered service types are logged to the console. + This can be useful for debugging or informational purposes. Defaults to False. + + Returns: + List[str]: A list containing the service types (str) of the discovered mDNS services. Each + element in the list is a string representing a unique type of service found during + the discovery process. + """ + + discovered_services = list(await AsyncZeroconfServiceTypes.async_find()) + + if log_output: + print(f"MDNS discovered service types: {discovered_services}") + + return discovered_services + # Private methods async def _discover(self, discovery_timeout_sec: float, From fb7ba4a2ebbf0b7bef3603fe6f044700d6a8e3c3 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 00:23:06 -0800 Subject: [PATCH 06/75] Fix restyle --- src/python_testing/mdns_discovery/mdns_discovery.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 4c500909b3e1b2..50ec552d0a34bc 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -247,9 +247,9 @@ async def get_service_types(self, log_output: bool = False) -> List[str]: element in the list is a string representing a unique type of service found during the discovery process. """ - + discovered_services = list(await AsyncZeroconfServiceTypes.async_find()) - + if log_output: print(f"MDNS discovered service types: {discovered_services}") From 140840cee90217a053d950ec008aead62319e6d7 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 00:27:21 -0800 Subject: [PATCH 07/75] Steps progress --- src/python_testing/TC_SC_4_3.py | 233 ++++++++++++++++++++++++++++++-- 1 file changed, 225 insertions(+), 8 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index a69a8d75b5ecb6..81ba95ea0280dc 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -15,24 +15,241 @@ # limitations under the License. # -import asyncio import logging -import queue -import time -from threading import Event +import re import chip.clusters as Clusters -from chip.clusters import ClusterObjects as ClustersObjects -from chip.clusters.Attribute import SubscriptionTransaction, TypedAttributePath -from chip.utils import CommissioningBuildingBlocks from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mobly import asserts +from mdns_discovery.mdns_discovery import MdnsDiscovery, MdnsServiceType +''' +Category +Functional conformance + +Purpose +The purpose of this test case is to verify that a Matter node is discoverable +and can advertise its services in a Matter network. + +Test Plan +https://github.com/CHIP-Specifications/chip-test-plans/blob/master/src/securechannel.adoc#343-tc-sc-43-discovery-dut_commissionee +''' + class TC_SC_4_3(MatterBaseTest): + + ONE_HOUR_IN_MS = 3600000 + MAX_SAT_VALUE = 65535 + MAX_T_VALUE = 6 + + async def get_descriptor_server_list(self): + return await self.read_single_attribute_check_success( + endpoint=0, + dev_ctrl=self.default_controller, + cluster=Clusters.Descriptor, + attribute=Clusters.Descriptor.Attributes.ServerList + ) + async def get_idle_mode_threshhold_ms(self): + return await self.read_single_attribute_check_success( + endpoint=0, + dev_ctrl=self.default_controller, + cluster=Clusters.IcdManagement, + attribute=Clusters.IcdManagement.Attributes.ActiveModeThreshold + ) + async def get_icd_feature_map(self): + return await self.read_single_attribute_check_success( + endpoint=0, + dev_ctrl=self.default_controller, + cluster=Clusters.IcdManagement, + attribute=Clusters.IcdManagement.Attributes.FeatureMap + ) + def get_dut_instance_name(self) -> str: + node_id = self.dut_node_id + compressed_fabric_id = self.default_controller.GetCompressedFabricId() + instance_name = f'{compressed_fabric_id:016X}-{node_id:016X}' + return instance_name + def get_operational_subtype(self) -> str: + compressed_fabric_id = self.default_controller.GetCompressedFabricId() + service_name = f'_I{compressed_fabric_id:016X}._sub.{MdnsServiceType.OPERATIONAL.value}' + return service_name + @staticmethod + def verify_decimal_value(input_value, comparison_value: int): + try: + input_float = float(input_value) + input_int = int(input_float) + + if str(input_value).startswith("0") and input_int != 0: + return (False, f"Input ({input_value}) has leading zeros.") + + if input_float != input_int: + return (False, f"Input ({input_value}) is not an integer.") + + if input_int <= comparison_value: + return (True, f"Input ({input_value}) is valid.") + else: + return (False, f"Input ({input_value}) exceeds the allowed value {comparison_value}.") + except ValueError: + return (False, f"Input ({input_value}) is not a valid decimal number.") + def verify_t_value(self, t_value): + # Verify t_value is a decimal number without leading zeros and less than or equal to 6 + try: + T_int = int(t_value) + if T_int < 0 or T_int > self.MAX_T_VALUE: + return False, f"T value ({t_value}) is not in the range 0 to 6. ({t_value})" + if str(t_value).startswith("0") and T_int != 0: + return False, f"T value ({t_value}) has leading zeros." + if T_int != float(t_value): + return False, f"T value ({t_value}) is not an integer." + + # Convert to bitmap and verify bit 0 is clear + if T_int & 1 == 0: + return True, f"T value ({t_value}) is valid and bit 0 is clear." + else: + return False, f"Bit 0 is not clear. T value ({t_value})" + except ValueError: + return False, "T value ({t_value}) is not a valid decimal number." + @staticmethod + def contains_ipv6_address(addresses): + # IPv6 pattern for basic validation + ipv6_pattern = re.compile(r'(?:(?:[0-9a-fA-F]{1,4}:){7}(?:[0-9a-fA-F]{1,4}|:))|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){5}(?:(?::[0-9a-fA-F]{1,4}){1,2}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){4}(?:(?::[0-9a-fA-F]{1,4}){1,3}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){3}(?:(?::[0-9a-fA-F]{1,4}){1,4}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){2}(?:(?::[0-9a-fA-F]{1,4}){1,5}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){1}(?:(?::[0-9a-fA-F]{1,4}){1,6}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?::(?::[0-9a-fA-F]{1,4}){1,7}|:)', re.VERBOSE) + + for address in addresses: + if ipv6_pattern.match(address): + return True, "At least one IPv6 address is present." + + return False, "No IPv6 addresses found." + @async_test_body async def test_TC_SC_4_3(self): - print() + print(f"\n"*10) + + supports_icd = None + supports_lit = None + active_mode_threshold_ms = None + instance_name = None + icd_value = None + sit_mode = None + + # *** STEP 1 *** + self.print_step("1", "DUT is commissioned on the same fabric as TH.") + + # *** STEP 2 *** + self.print_step("2", "TH reads ServerList attribute from the Descriptor cluster on EP0. If the ICD Management cluster ID (70,0x46) is present in the list, set supports_icd to true, otherwise set supports_icd to false.") + ep0_servers = await self.get_descriptor_server_list() + + # Check if ep0_servers contains the ICD Management cluster ID (0x0046) + supports_icd = Clusters.IcdManagement.id in ep0_servers + logging.info(f"\n\n\tsupports_icd: {supports_icd}\n\n") + + # *** STEP 3 *** + self.print_step("3", "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.") + if supports_icd: + active_mode_threshold_ms = await self.get_idle_mode_threshhold_ms() + logging.info(f"\n\n\tactive_mode_threshold_ms: {active_mode_threshold_ms}\n\n") + + # *** STEP 4 *** + self.print_step("4", "If supports_icd is true, TH reads FeatureMap from the ICD Management cluster on EP0. If the LITS feature is set, set supports_lit to true. Otherwise set supports_lit to false.") + if supports_icd: + feature_map = await self.get_icd_feature_map() + LITS = Clusters.IcdManagement.Bitmaps.Feature.kLongIdleTimeSupport + supports_lit = bool(feature_map & LITS == LITS) + logging.info(f"\n\n\tkLongIdleTimeSupport set: {supports_lit}\n\n") + + # *** STEP 5 *** + self.print_step("5", "TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the assigned 64-bit Node identifier, each expressed as a fixed-length sixteen-character hexadecimal string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen.") + instance_name = self.get_dut_instance_name() + + + + # PENDING STEPS 6-8 + + + mdns = MdnsDiscovery() + operational = await mdns.get_operational_service( + service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", + service_type=MdnsServiceType.OPERATIONAL.value, + log_output=True + ) + + # *** STEP 9 *** + self.print_step("9", "TH verifies ICD, SII, SAI, SAT, and T TXT record keys/vales of the returned record.") + + # ICD TXT KEY + if supports_lit: + logging.info(f"supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") + + # Verify the ICD key IS present + asserts.assert_in('ICD', operational.txt_record, "ICD key is NOT present in the TXT record.") + + # Verify it has the value of 0 or 1 (ASCII) + icd_value = int(operational.txt_record['ICD']) + asserts.assert_true(icd_value == 0 or icd_value == 1, "ICD value is different than 0 or 1 (ASCII).") + else: + logging.info(f"supports_lit is false, verify that the ICD key is NOT present in the TXT record.") + asserts.assert_not_in('ICD', operational.txt_record, "ICD key is present in the TXT record.") + + # SII TXT KEY + if supports_icd and not supports_lit: + sit_mode = True + + if supports_lit and supports_lit: + if icd_value == 0: + sit_mode = True + else: + sit_mode = False + + if not supports_icd: + sit_mode = False + + if sit_mode: + logging.info(f"sit_mode is True, verify the SII key IS present.") + asserts.assert_in('SII', operational.txt_record, "SII key is NOT present in the TXT record.") + + logging.info(f"Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + sii_value = operational.txt_record['SII'] + result, message = self.verify_decimal_value(sii_value, self.ONE_HOUR_IN_MS) + asserts.assert_true(result, message) + + # SAI TXT KEY + if supports_icd: + logging.info(f"supports_icd is True, verify the SAI key IS present.") + asserts.assert_in('SAI', operational.txt_record, "SAI key is NOT present in the TXT record.") + + logging.info(f"Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + sai_value = operational.txt_record['SAI'] + result, message = self.verify_decimal_value(sai_value, self.ONE_HOUR_IN_MS) + asserts.assert_true(result, message) + + # SAT TXT KEY + if 'SAT' in operational.txt_record: + logging.info(f"SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") + sat_value = operational.txt_record['SAT'] + result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) + asserts.assert_true(result, message) + + if supports_icd: + logging.info(f"supports_icd is True, verify the SAT value is equal to active_mode_threshold.") + asserts.assert_equal(int(sat_value), active_mode_threshold_ms) + + # # T TXT KEY + # if 'T' in operational.txt_record: + # logging.info(f"T key is present in TXT record, verify if that it is a decimal value with no leading zeros and is less than or equal to 6. Convert the value to a bitmap and verify bit 0 is clear.") + # t_value = operational.txt_record['T'] + # result, message = self.verify_t_value(t_value) + # asserts.assert_true(result, message) + + # AAAA + logging.info(f"Verify the AAAA record contains at least one IPv6 address") + result, message = self.contains_ipv6_address(operational.addresses) + asserts.assert_true(result, message) + + # *** STEP 10 *** + self.print_step("10", "Verify DUT returns a PTR record with DNS-SD instance name set instance_name.") + service_types = await mdns.get_service_types(log_output=True) + op_sub_type = self.get_operational_subtype() + asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") + + print(f"\n"*10) if __name__ == "__main__": From 86fc530e332bd17a27d0ee7b53ca5eb1a1e36a65 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 00:33:16 -0800 Subject: [PATCH 08/75] Fix restyle --- src/python_testing/TC_SC_4_3.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 81ba95ea0280dc..26d46dbf8137ec 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -20,9 +20,9 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main -from mobly import asserts from mdns_discovery.mdns_discovery import MdnsDiscovery, MdnsServiceType +from mobly import asserts ''' Category @@ -36,6 +36,7 @@ https://github.com/CHIP-Specifications/chip-test-plans/blob/master/src/securechannel.adoc#343-tc-sc-43-discovery-dut_commissionee ''' + class TC_SC_4_3(MatterBaseTest): ONE_HOUR_IN_MS = 3600000 @@ -49,6 +50,7 @@ async def get_descriptor_server_list(self): cluster=Clusters.Descriptor, attribute=Clusters.Descriptor.Attributes.ServerList ) + async def get_idle_mode_threshhold_ms(self): return await self.read_single_attribute_check_success( endpoint=0, @@ -56,6 +58,7 @@ async def get_idle_mode_threshhold_ms(self): cluster=Clusters.IcdManagement, attribute=Clusters.IcdManagement.Attributes.ActiveModeThreshold ) + async def get_icd_feature_map(self): return await self.read_single_attribute_check_success( endpoint=0, @@ -63,15 +66,18 @@ async def get_icd_feature_map(self): cluster=Clusters.IcdManagement, attribute=Clusters.IcdManagement.Attributes.FeatureMap ) + def get_dut_instance_name(self) -> str: node_id = self.dut_node_id compressed_fabric_id = self.default_controller.GetCompressedFabricId() instance_name = f'{compressed_fabric_id:016X}-{node_id:016X}' return instance_name + def get_operational_subtype(self) -> str: compressed_fabric_id = self.default_controller.GetCompressedFabricId() service_name = f'_I{compressed_fabric_id:016X}._sub.{MdnsServiceType.OPERATIONAL.value}' return service_name + @staticmethod def verify_decimal_value(input_value, comparison_value: int): try: @@ -90,6 +96,7 @@ def verify_decimal_value(input_value, comparison_value: int): return (False, f"Input ({input_value}) exceeds the allowed value {comparison_value}.") except ValueError: return (False, f"Input ({input_value}) is not a valid decimal number.") + def verify_t_value(self, t_value): # Verify t_value is a decimal number without leading zeros and less than or equal to 6 try: @@ -100,7 +107,7 @@ def verify_t_value(self, t_value): return False, f"T value ({t_value}) has leading zeros." if T_int != float(t_value): return False, f"T value ({t_value}) is not an integer." - + # Convert to bitmap and verify bit 0 is clear if T_int & 1 == 0: return True, f"T value ({t_value}) is valid and bit 0 is clear." @@ -108,6 +115,7 @@ def verify_t_value(self, t_value): return False, f"Bit 0 is not clear. T value ({t_value})" except ValueError: return False, "T value ({t_value}) is not a valid decimal number." + @staticmethod def contains_ipv6_address(addresses): # IPv6 pattern for basic validation @@ -118,7 +126,7 @@ def contains_ipv6_address(addresses): return True, "At least one IPv6 address is present." return False, "No IPv6 addresses found." - + @async_test_body async def test_TC_SC_4_3(self): print(f"\n"*10) @@ -132,7 +140,7 @@ async def test_TC_SC_4_3(self): # *** STEP 1 *** self.print_step("1", "DUT is commissioned on the same fabric as TH.") - + # *** STEP 2 *** self.print_step("2", "TH reads ServerList attribute from the Descriptor cluster on EP0. If the ICD Management cluster ID (70,0x46) is present in the list, set supports_icd to true, otherwise set supports_icd to false.") ep0_servers = await self.get_descriptor_server_list() @@ -142,7 +150,8 @@ async def test_TC_SC_4_3(self): logging.info(f"\n\n\tsupports_icd: {supports_icd}\n\n") # *** STEP 3 *** - self.print_step("3", "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.") + self.print_step( + "3", "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.") if supports_icd: active_mode_threshold_ms = await self.get_idle_mode_threshhold_ms() logging.info(f"\n\n\tactive_mode_threshold_ms: {active_mode_threshold_ms}\n\n") @@ -159,11 +168,8 @@ async def test_TC_SC_4_3(self): self.print_step("5", "TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the assigned 64-bit Node identifier, each expressed as a fixed-length sixteen-character hexadecimal string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen.") instance_name = self.get_dut_instance_name() - - # PENDING STEPS 6-8 - mdns = MdnsDiscovery() operational = await mdns.get_operational_service( service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", @@ -222,7 +228,8 @@ async def test_TC_SC_4_3(self): # SAT TXT KEY if 'SAT' in operational.txt_record: - logging.info(f"SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") + logging.info( + f"SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") sat_value = operational.txt_record['SAT'] result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) asserts.assert_true(result, message) From 93d7857e5652237b22ca228189d68e6f7f369d81 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 00:35:53 -0800 Subject: [PATCH 09/75] Fix restyle --- src/python_testing/TC_SC_4_3.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 26d46dbf8137ec..b24437c89f61b6 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -21,7 +21,6 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import MdnsDiscovery, MdnsServiceType - from mobly import asserts ''' From 1f87b21017b3de23eda769ed123ce9a49a5e6210 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 00:51:05 -0800 Subject: [PATCH 10/75] Adds test to tests.yaml --- .github/workflows/tests.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 61db68f0233509..99aa04fd0e9933 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -463,6 +463,8 @@ jobs: scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RR_1_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DeviceBasicComposition.py" --script-args "--storage-path admin_storage.json --manual-code 10054912339 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_3_6.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_4_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DA_1_7.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_TestEventTrigger.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_ACE_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' From 61d1ff95026735e16af00aeb279039c079ef8275 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 07:31:15 -0800 Subject: [PATCH 11/75] Fix lint --- src/python_testing/TC_SC_4_3.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index b24437c89f61b6..8ab79e74ecb968 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -113,7 +113,7 @@ def verify_t_value(self, t_value): else: return False, f"Bit 0 is not clear. T value ({t_value})" except ValueError: - return False, "T value ({t_value}) is not a valid decimal number." + return False, f"T value ({t_value}) is not a valid decimal number." @staticmethod def contains_ipv6_address(addresses): @@ -128,7 +128,7 @@ def contains_ipv6_address(addresses): @async_test_body async def test_TC_SC_4_3(self): - print(f"\n"*10) + print("\n"*10) supports_icd = None supports_lit = None @@ -181,7 +181,7 @@ async def test_TC_SC_4_3(self): # ICD TXT KEY if supports_lit: - logging.info(f"supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") + logging.info("supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") # Verify the ICD key IS present asserts.assert_in('ICD', operational.txt_record, "ICD key is NOT present in the TXT record.") @@ -190,7 +190,7 @@ async def test_TC_SC_4_3(self): icd_value = int(operational.txt_record['ICD']) asserts.assert_true(icd_value == 0 or icd_value == 1, "ICD value is different than 0 or 1 (ASCII).") else: - logging.info(f"supports_lit is false, verify that the ICD key is NOT present in the TXT record.") + logging.info("supports_lit is false, verify that the ICD key is NOT present in the TXT record.") asserts.assert_not_in('ICD', operational.txt_record, "ICD key is present in the TXT record.") # SII TXT KEY @@ -207,20 +207,20 @@ async def test_TC_SC_4_3(self): sit_mode = False if sit_mode: - logging.info(f"sit_mode is True, verify the SII key IS present.") + logging.info("sit_mode is True, verify the SII key IS present.") asserts.assert_in('SII', operational.txt_record, "SII key is NOT present in the TXT record.") - logging.info(f"Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + logging.info("Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") sii_value = operational.txt_record['SII'] result, message = self.verify_decimal_value(sii_value, self.ONE_HOUR_IN_MS) asserts.assert_true(result, message) # SAI TXT KEY if supports_icd: - logging.info(f"supports_icd is True, verify the SAI key IS present.") + logging.info("supports_icd is True, verify the SAI key IS present.") asserts.assert_in('SAI', operational.txt_record, "SAI key is NOT present in the TXT record.") - logging.info(f"Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + logging.info("Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") sai_value = operational.txt_record['SAI'] result, message = self.verify_decimal_value(sai_value, self.ONE_HOUR_IN_MS) asserts.assert_true(result, message) @@ -228,13 +228,13 @@ async def test_TC_SC_4_3(self): # SAT TXT KEY if 'SAT' in operational.txt_record: logging.info( - f"SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") + "SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") sat_value = operational.txt_record['SAT'] result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) asserts.assert_true(result, message) if supports_icd: - logging.info(f"supports_icd is True, verify the SAT value is equal to active_mode_threshold.") + logging.info("supports_icd is True, verify the SAT value is equal to active_mode_threshold.") asserts.assert_equal(int(sat_value), active_mode_threshold_ms) # # T TXT KEY @@ -245,7 +245,7 @@ async def test_TC_SC_4_3(self): # asserts.assert_true(result, message) # AAAA - logging.info(f"Verify the AAAA record contains at least one IPv6 address") + logging.info("Verify the AAAA record contains at least one IPv6 address") result, message = self.contains_ipv6_address(operational.addresses) asserts.assert_true(result, message) @@ -255,7 +255,7 @@ async def test_TC_SC_4_3(self): op_sub_type = self.get_operational_subtype() asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") - print(f"\n"*10) + print("\n"*10) if __name__ == "__main__": From 19fa1f52cc025ddfe960384869584cb14f27c736 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 07:35:10 -0800 Subject: [PATCH 12/75] Fix lit-icd-app path in tests.yaml --- .github/workflows/tests.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 99aa04fd0e9933..7d5f87d2cc019a 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -463,7 +463,7 @@ jobs: scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RR_1_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DeviceBasicComposition.py" --script-args "--storage-path admin_storage.json --manual-code 10054912339 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_3_6.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_4_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lit-icd-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_4_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DA_1_7.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_TestEventTrigger.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' From ba7238148c135d202e948bc4a5f239b0650089ae Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 07:39:51 -0800 Subject: [PATCH 13/75] Fix SII key logic --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 8ab79e74ecb968..6a10210f032107 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -197,7 +197,7 @@ async def test_TC_SC_4_3(self): if supports_icd and not supports_lit: sit_mode = True - if supports_lit and supports_lit: + if supports_icd and supports_lit: if icd_value == 0: sit_mode = True else: From 5d6912fb52281e711cf1ab226886cac5e6c5325e Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 09:48:40 -0800 Subject: [PATCH 14/75] Addresses latest review comments --- src/python_testing/TC_SC_4_3.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 6a10210f032107..08188c1d6371d6 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -15,6 +15,7 @@ # limitations under the License. # +import ipaddress import logging import re @@ -78,7 +79,7 @@ def get_operational_subtype(self) -> str: return service_name @staticmethod - def verify_decimal_value(input_value, comparison_value: int): + def verify_decimal_value(input_value, max_value: int): try: input_float = float(input_value) input_int = int(input_float) @@ -89,7 +90,7 @@ def verify_decimal_value(input_value, comparison_value: int): if input_float != input_int: return (False, f"Input ({input_value}) is not an integer.") - if input_int <= comparison_value: + if input_int <= max_value: return (True, f"Input ({input_value}) is valid.") else: return (False, f"Input ({input_value}) exceeds the allowed value {comparison_value}.") @@ -117,13 +118,15 @@ def verify_t_value(self, t_value): @staticmethod def contains_ipv6_address(addresses): - # IPv6 pattern for basic validation - ipv6_pattern = re.compile(r'(?:(?:[0-9a-fA-F]{1,4}:){7}(?:[0-9a-fA-F]{1,4}|:))|(?:[0-9a-fA-F]{1,4}:){6}(?::[0-9a-fA-F]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){5}(?:(?::[0-9a-fA-F]{1,4}){1,2}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){4}(?:(?::[0-9a-fA-F]{1,4}){1,3}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){3}(?:(?::[0-9a-fA-F]{1,4}){1,4}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){2}(?:(?::[0-9a-fA-F]{1,4}){1,5}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?:[0-9a-fA-F]{1,4}:){1}(?:(?::[0-9a-fA-F]{1,4}){1,6}|:((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|:)|(?::(?::[0-9a-fA-F]{1,4}){1,7}|:)', re.VERBOSE) - for address in addresses: - if ipv6_pattern.match(address): + try: + # Attempt to create an IPv6 address object. If successful, this is an IPv6 address. + ipaddress.IPv6Address(address) return True, "At least one IPv6 address is present." - + except ipaddress.AddressValueError: + # If an AddressValueError is raised, the current address is not a valid IPv6 address. + # The loop will continue to the next address. + continue return False, "No IPv6 addresses found." @async_test_body From 3e3d6518b99cde7e26f6c07759c8aedee1e4b8ed Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 11:09:35 -0800 Subject: [PATCH 15/75] Fix lint --- src/python_testing/TC_SC_4_3.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 08188c1d6371d6..abc1b570657c37 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -17,7 +17,6 @@ import ipaddress import logging -import re import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main @@ -93,7 +92,7 @@ def verify_decimal_value(input_value, max_value: int): if input_int <= max_value: return (True, f"Input ({input_value}) is valid.") else: - return (False, f"Input ({input_value}) exceeds the allowed value {comparison_value}.") + return (False, f"Input ({input_value}) exceeds the allowed value {max_value}.") except ValueError: return (False, f"Input ({input_value}) is not a valid decimal number.") From 62624ff1ef59cfa522212355e12c3e5d60aca6ee Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 16:20:39 -0800 Subject: [PATCH 16/75] Replaces 1 sec fixed sleep in operational service logic with service listener event wait time --- .../mdns_discovery/mdns_discovery.py | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 50ec552d0a34bc..14deecde901f85 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -75,19 +75,22 @@ class MdnsServiceType(Enum): BORDER_ROUTER = "_meshcop._udp.local." -class DummyServiceListener(ServiceListener): +class MdnsServiceListener(ServiceListener): """ A service listener required for the TXT record data to get populated and come back """ + def __init__(self): + self.updated_event = asyncio.Event() + def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: - pass + self.updated_event.set() def remove_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: pass def update_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: - pass + self.updated_event.set() class MdnsDiscovery: @@ -177,16 +180,20 @@ async def get_operational_service(self, service_name: str = None, print(f"Looking for MDNS service type '{service_type}', service name '{service_name}'") # Adds service listener - service_listener = DummyServiceListener() + service_listener = MdnsServiceListener() self._zc.add_service_listener(MdnsServiceType.OPERATIONAL.value, service_listener) - # Adds delay so TXT record is able to get populated - await asyncio.sleep(1) + # Wait for the add/update service event or timeout + try: + await asyncio.wait_for(service_listener.updated_event.wait(), discovery_timeout_sec) + except asyncio.TimeoutError: + print(f"Service lookup for {service_name} timeout ({discovery_timeout_sec}) reached without an update.") + finally: + self._zc.remove_service_listener(service_listener) # Get service info service_info = AsyncServiceInfo(service_type, service_name) is_discovered = await service_info.async_request(self._zc, 3000) - self._zc.remove_service_listener(service_listener) # Adds service to discovered services if is_discovered: From a5a1c2e405b92ccc2f0d0799a9a89d59867fe722 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Wed, 7 Feb 2024 19:03:14 -0800 Subject: [PATCH 17/75] Merge from master --- .github/workflows/lint.yml | 138 +++++++ .../rvc-operational-state-delegate-impl.h | 12 - .../include/static-supported-modes-manager.h | 2 +- .../static-supported-temperature-levels.h | 2 +- .../rvc-operational-state-delegate-impl.cpp | 28 -- .../src/static-supported-modes-manager.cpp | 2 +- .../static-supported-temperature-levels.cpp | 2 +- .../linux/include/CHIPProjectAppConfig.h | 2 +- .../all-clusters-app/linux/main-common.cpp | 4 +- .../app/src/main/cpp/CHIPTest-JNI.cpp | 20 +- examples/chef/common/chef-air-quality.cpp | 2 +- examples/chef/common/chef-air-quality.h | 2 +- examples/chef/common/chef-channel-manager.cpp | 6 +- .../common/chef-concentration-measurement.cpp | 40 +- .../common/chef-concentration-measurement.h | 20 +- .../chef-rvc-operational-state-delegate.cpp | 2 +- examples/chef/common/stubs.cpp | 76 ++-- .../include/static-supported-modes-manager.h | 2 +- .../static-supported-temperature-levels.h | 2 +- .../linux/static-supported-modes-manager.cpp | 2 +- .../static-supported-temperature-levels.cpp | 2 +- examples/platform/asr/CHIPDeviceManager.cpp | 4 +- examples/platform/silabs/BaseApplication.cpp | 12 +- examples/platform/silabs/BaseApplication.h | 4 +- .../platform/silabs/SoftwareFaultReports.cpp | 4 +- .../static-supported-temperature-levels.h | 2 +- .../static-supported-temperature-levels.cpp | 2 +- .../include/rvc-operational-state-delegate.h | 16 - .../content-control/ContentController.cpp | 2 +- .../AppContentLauncherManager.cpp | 2 +- .../AppMediaPlaybackManager.cpp | 2 +- .../tv-app/android/java/ChannelManager.cpp | 45 +- examples/tv-app/android/java/ChannelManager.h | 3 +- .../java/ContentAppAttributeDelegate.cpp | 6 +- .../java/ContentAppAttributeDelegate.h | 16 +- .../java/ContentAppCommandDelegate.cpp | 19 +- .../android/java/ContentAppCommandDelegate.h | 16 +- .../android/java/ContentLauncherManager.cpp | 20 +- .../android/java/ContentLauncherManager.h | 3 +- .../tv-app/android/java/DeviceCallbacks.cpp | 11 +- .../tv-app/android/java/DeviceCallbacks.h | 3 +- .../tv-app/android/java/JNIDACProvider.cpp | 12 +- examples/tv-app/android/java/JNIDACProvider.h | 3 +- .../android/java/KeypadInputManager.cpp | 10 +- .../tv-app/android/java/KeypadInputManager.h | 5 +- examples/tv-app/android/java/LevelManager.cpp | 13 +- examples/tv-app/android/java/LevelManager.h | 3 +- .../tv-app/android/java/LowPowerManager.cpp | 8 +- .../tv-app/android/java/LowPowerManager.h | 5 +- .../tv-app/android/java/MediaInputManager.cpp | 30 +- .../tv-app/android/java/MediaInputManager.h | 3 +- .../android/java/MediaPlaybackManager.cpp | 43 +- .../android/java/MediaPlaybackManager.h | 3 +- .../android/java/MyUserPrompter-JNI.cpp | 22 +- .../tv-app/android/java/MyUserPrompter-JNI.h | 3 +- examples/tv-app/android/java/OnOffManager.cpp | 13 +- examples/tv-app/android/java/OnOffManager.h | 3 +- examples/tv-app/android/java/TVApp-JNI.cpp | 10 +- examples/tv-app/android/java/TvApp-JNI.h | 3 +- .../tv-app/android/java/WakeOnLanManager.cpp | 8 +- .../tv-app/android/java/WakeOnLanManager.h | 5 +- .../clusters/channel/ChannelManager.cpp | 2 +- .../content-control/ContentController.cpp | 2 +- .../ContentLauncherManager.cpp | 2 +- .../keypad-input/KeypadInputManager.cpp | 2 +- .../media-playback/MediaPlaybackManager.cpp | 2 +- .../app/src/main/jni/cpp/JNIDACProvider.cpp | 13 +- .../App/app/src/main/jni/cpp/JNIDACProvider.h | 3 +- .../jni/cpp/MatterCallbackHandler-JNI.cpp | 13 +- .../main/jni/cpp/MatterCallbackHandler-JNI.h | 6 +- .../cpp/core/CastingPlayerDiscovery-JNI.cpp | 37 +- .../RotatingDeviceIdUniqueIdProvider-JNI.cpp | 8 +- .../RotatingDeviceIdUniqueIdProvider-JNI.h | 5 +- .../android/java/ColorControlManager.cpp | 29 +- .../android/java/ColorControlManager.h | 3 +- .../android/java/DeviceApp-JNI.cpp | 14 +- .../android/java/DeviceApp-JNI.h | 3 +- .../android/java/DoorLockManager.cpp | 13 +- .../android/java/DoorLockManager.h | 3 +- .../android/java/JNIDACProvider.cpp | 9 +- .../android/java/JNIDACProvider.h | 3 +- .../android/java/OnOffManager.cpp | 14 +- .../android/java/OnOffManager.h | 3 +- .../android/java/PowerSourceManager.cpp | 10 +- .../android/java/PowerSourceManager.h | 3 +- scripts/tools/not_known_to_gn.py | 182 ++++++++ .../app-templates/gen_config.h | 388 +++++++++--------- .../lighting-app/app-templates/gen_config.h | 172 ++++---- .../account-login-server.cpp | 6 +- .../application-basic-server.cpp | 6 +- .../application-launcher-server.cpp | 6 +- .../audio-output-server.cpp | 6 +- .../boolean-state-configuration-server.cpp | 6 +- .../channel-server/channel-server.cpp | 6 +- .../color-control-server.cpp | 112 ++--- .../color-control-server.h | 52 +-- .../content-app-observer.cpp | 6 +- .../content-control-server.cpp | 6 +- .../content-launch-server.cpp | 6 +- .../diagnostic-logs-server.cpp | 10 +- .../dishwasher-alarm-server.cpp | 6 +- .../door-lock-server/door-lock-server.cpp | 8 +- .../door-lock-server/door-lock-server.h | 2 +- .../electrical-energy-measurement-server.cpp | 8 +- .../fan-control-server/fan-control-server.cpp | 6 +- .../clusters/groups-server/groups-server.cpp | 8 +- .../keypad-input-server.cpp | 6 +- .../laundry-dryer-controls-server.cpp | 6 +- .../laundry-washer-controls-server.cpp | 6 +- .../clusters/level-control/level-control.cpp | 60 +-- .../clusters/level-control/level-control.h | 6 +- .../low-power-server/low-power-server.cpp | 6 +- .../media-input-server/media-input-server.cpp | 6 +- .../media-playback-server.cpp | 6 +- src/app/clusters/mode-base-server/README.md | 2 +- .../mode-base-server/mode-base-server.cpp | 4 +- .../mode-select-server/mode-select-server.cpp | 8 +- .../clusters/on-off-server/on-off-server.cpp | 70 ++-- .../operational-state-server.h | 22 + .../clusters/ota-provider/ota-provider.cpp | 14 +- .../power-source-server.cpp | 4 +- .../pump-configuration-and-control-server.cpp | 8 +- .../sample-mei-server/sample-mei-server.cpp | 2 +- .../sample-mei-server/sample-mei-server.h | 2 +- .../clusters/scenes-server/scenes-server.cpp | 2 +- .../clusters/scenes-server/scenes-server.h | 2 +- .../target-navigator-server.cpp | 6 +- ...valve-configuration-and-control-server.cpp | 14 +- .../wake-on-lan-server/wake-on-lan-server.cpp | 8 +- .../window-covering-server.cpp | 10 +- src/app/icd/server/ICDManager.cpp | 14 + src/app/icd/server/ICDManager.h | 5 + src/app/server/Server.cpp | 10 + src/app/server/java/CHIPAppServer-JNI.cpp | 11 +- src/app/server/java/ChipAppServerDelegate.cpp | 30 +- src/app/server/java/ChipAppServerDelegate.h | 3 +- .../suites/TestIcdManagementCluster.yaml | 65 +-- src/app/util/af-types.h | 6 +- src/app/util/af.h | 2 +- src/app/util/util.cpp | 8 +- .../templates/app/gen_config.zapt | 22 +- src/controller/java/AndroidCallbacks.cpp | 17 +- .../java/AndroidCommissioningWindowOpener.cpp | 27 +- .../java/AndroidCommissioningWindowOpener.h | 4 +- .../java/AndroidCurrentFabricRemover.cpp | 22 +- .../java/AndroidCurrentFabricRemover.h | 4 +- .../java/AndroidDeviceControllerWrapper.cpp | 69 ++-- .../java/AndroidDeviceControllerWrapper.h | 6 +- .../java/AttestationTrustStoreBridge.cpp | 20 +- .../java/AttestationTrustStoreBridge.h | 7 +- .../java/CHIPDeviceController-JNI.cpp | 29 +- .../java/DeviceAttestationDelegateBridge.cpp | 21 +- .../java/DeviceAttestationDelegateBridge.h | 11 +- .../CHIP/templates/availability.yaml | 2 + src/lib/support/JniReferences.cpp | 211 ++++++---- src/lib/support/JniReferences.h | 95 +++-- src/lib/support/JniTypeWrappers.h | 71 ---- .../android/AndroidChipPlatform-JNI.cpp | 14 +- src/platform/android/AndroidConfig.cpp | 46 ++- src/platform/android/BLEManagerImpl.cpp | 49 ++- src/platform/android/BLEManagerImpl.h | 6 +- .../android/CHIPP256KeypairBridge.cpp | 25 +- src/platform/android/CHIPP256KeypairBridge.h | 10 +- .../android/ConfigurationManagerImpl.cpp | 7 +- .../android/ConfigurationManagerImpl.h | 3 +- .../android/DiagnosticDataProviderImpl.cpp | 14 +- .../android/DiagnosticDataProviderImpl.h | 6 +- src/platform/android/DnssdImpl.cpp | 54 +-- .../android/KeyValueStoreManagerImpl.cpp | 18 +- .../android/KeyValueStoreManagerImpl.h | 9 +- src/platform/stm32/CHIPDevicePlatformConfig.h | 4 +- 171 files changed, 1828 insertions(+), 1484 deletions(-) create mode 100755 scripts/tools/not_known_to_gn.py diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 29a3dc8624e491..a3f2937276d4a9 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -42,6 +42,144 @@ jobs: with: platform: linux + - name: Check for orphaned gn files + if: always() + # We should enforce that ALL new files are referenced in our build scripts. + # Several things do not have a clear fix path: + # - various platform implementations (including darwin-specific files as they + # are not using GN) + # - app/clusters (they are fetched dynamically - this should probably be fixed) + # + # All the rest of the exceptions should be driven down to 0: chip should fully + # be defined in build rules. + # + # This check enforces that for any newly added file, it must be part of some + # BUILD.gn file + run: | + ./scripts/run_in_build_env.sh "./scripts/tools/not_known_to_gn.py \ + src \ + --skip-dir app/clusters \ + --skip-dir darwin \ + --skip-dir include \ + --skip-dir platform/Ameba \ + --skip-dir platform/android \ + --skip-dir platform/ASR \ + --skip-dir platform/Beken \ + --skip-dir platform/bouffalolab \ + --skip-dir platform/cc13xx_26xx \ + --skip-dir platform/cc32xx \ + --skip-dir platform/Darwin \ + --skip-dir platform/ESP32 \ + --skip-dir platform/fake \ + --skip-dir platform/FreeRTOS \ + --skip-dir platform/Infineon \ + --skip-dir platform/Linux \ + --skip-dir platform/mbed \ + --skip-dir platform/mt793x \ + --skip-dir platform/nxp \ + --skip-dir platform/OpenThread \ + --skip-dir platform/qpg \ + --skip-dir platform/silabs \ + --skip-dir platform/telink \ + --skip-dir platform/webos \ + --skip-dir platform/Zephyr \ + --skip-dir test_driver \ + --known-failure app/app-platform/ContentApp.cpp \ + --known-failure app/app-platform/ContentApp.h \ + --known-failure app/app-platform/ContentAppPlatform.cpp \ + --known-failure app/app-platform/ContentAppPlatform.h \ + --known-failure controller/ExamplePersistentStorage.cpp \ + --known-failure controller/ExamplePersistentStorage.h \ + --known-failure controller/java/GroupDeviceProxy.h \ + --known-failure controller/java/CHIPEventTLVValueDecoder.h \ + --known-failure controller/python/chip/credentials/cert.h \ + --known-failure controller/python/chip/server/Options.h \ + --known-failure controller/python/chip/crypto/p256keypair.h \ + --known-failure controller/python/chip/commissioning/PlaceholderOperationalCredentialsIssuer.h \ + --known-failure controller/python/chip/native/PyChipError.h \ + --known-failure app/AttributeAccessInterface.h \ + --known-failure app/AttributeAccessToken.h \ + --known-failure app/att-storage.h \ + --known-failure app/BufferedReadCallback.h \ + --known-failure app/CommandHandler.h \ + --known-failure app/CommandHandlerInterface.h \ + --known-failure app/CommandPathParams.h \ + --known-failure app/CommandPathRegistry.h \ + --known-failure app/CommandResponseSender.h \ + --known-failure app/CommandSender.h \ + --known-failure app/CommandSenderLegacyCallback.h \ + --known-failure app/CompatEnumNames.h \ + --known-failure app/ConcreteAttributePath.h \ + --known-failure app/ConcreteCommandPath.h \ + --known-failure app/data-model/ListLargeSystemExtensions.h \ + --known-failure app/EventHeader.h \ + --known-failure app/EventLoggingDelegate.h \ + --known-failure app/EventLogging.h \ + --known-failure app/EventLoggingTypes.h \ + --known-failure app/EventManagement.h \ + --known-failure app/InteractionModelHelper.h \ + --known-failure app/ObjectList.h \ + --known-failure app/ReadClient.h \ + --known-failure app/ReadHandler.h \ + --known-failure app/ReadPrepareParams.h \ + --known-failure app/reporting/tests/MockReportScheduler.cpp \ + --known-failure app/reporting/tests/MockReportScheduler.h \ + --known-failure app/server/AppDelegate.h \ + --known-failure app/TestEventTriggerDelegate.h \ + --known-failure app/tests/integration/common.h \ + --known-failure app/tests/integration/MockEvents.h \ + --known-failure app/tests/suites/credentials/TestHarnessDACProvider.h \ + --known-failure app/tests/TestOperationalDeviceProxy.cpp \ + --known-failure app/util/af-enums.h \ + --known-failure app/util/af.h \ + --known-failure app/util/af-types.h \ + --known-failure app/util/attribute-metadata.h \ + --known-failure app/util/attribute-storage.cpp \ + --known-failure app/util/attribute-storage.h \ + --known-failure app/util/attribute-storage-null-handling.h \ + --known-failure app/util/attribute-table.cpp \ + --known-failure app/util/attribute-table.h \ + --known-failure app/util/binding-table.cpp \ + --known-failure app/util/binding-table.h \ + --known-failure app/util/common.h \ + --known-failure app/util/config.h \ + --known-failure app/util/DataModelHandler.cpp \ + --known-failure app/util/DataModelHandler.h \ + --known-failure app/util/ember-compatibility-functions.cpp \ + --known-failure app/util/endpoint-config-api.h \ + --known-failure app/util/endpoint-config-defines.h \ + --known-failure app/util/error-mapping.h \ + --known-failure app/util/generic-callbacks.h \ + --known-failure app/util/generic-callback-stubs.cpp \ + --known-failure app/util/im-client-callbacks.h \ + --known-failure app/util/MatterCallbacks.h \ + --known-failure app/util/message.cpp \ + --known-failure app/util/mock/Constants.h \ + --known-failure app/util/mock/Functions.h \ + --known-failure app/util/mock/MockNodeConfig.h \ + --known-failure app/util/odd-sized-integers.h \ + --known-failure app/util/types_stub.h \ + --known-failure app/util/util.cpp \ + --known-failure app/util/util.h \ + --known-failure app/WriteClient.h \ + --known-failure app/WriteHandler.h \ + --known-failure inet/tests/TestInetLayerCommon.hpp \ + --known-failure lib/core/CHIPVendorIdentifiers.hpp \ + --known-failure lib/dnssd/Constants.h \ + --known-failure lib/dnssd/minimal_mdns/core/FlatAllocatedQName.h \ + --known-failure lib/dnssd/minimal_mdns/core/HeapQName.h \ + --known-failure lib/dnssd/minimal_mdns/ListenIterator.h \ + --known-failure lib/dnssd/minimal_mdns/tests/CheckOnlyServer.h \ + --known-failure lib/dnssd/platform/DnssdBrowseDelegate.h \ + --known-failure lib/support/CHIPArgParser.hpp \ + --known-failure messaging/tests/echo/common.h \ + --known-failure platform/DeviceSafeQueue.cpp \ + --known-failure platform/DeviceSafeQueue.h \ + --known-failure platform/GLibTypeDeleter.h \ + --known-failure platform/SingletonConfigurationManager.cpp \ + --known-failure transport/retransmit/tests/TestCacheDriver.cpp \ + " + - name: Check for matter lint errors if: always() run: | diff --git a/examples/all-clusters-app/all-clusters-common/include/rvc-operational-state-delegate-impl.h b/examples/all-clusters-app/all-clusters-common/include/rvc-operational-state-delegate-impl.h index 89a3e69c5b8bed..4417f9f5a3ab4a 100644 --- a/examples/all-clusters-app/all-clusters-common/include/rvc-operational-state-delegate-impl.h +++ b/examples/all-clusters-app/all-clusters-common/include/rvc-operational-state-delegate-impl.h @@ -90,18 +90,6 @@ class RvcOperationalStateDelegate : public Delegate */ void HandleResumeStateCallback(OperationalState::GenericOperationalError & err) override; - /** - * Handle Command Callback in application: Start - * @param[out] get operational error after callback. - */ - void HandleStartStateCallback(OperationalState::GenericOperationalError & err) override; - - /** - * Handle Command Callback in application: Stop - * @param[out] get operational error after callback. - */ - void HandleStopStateCallback(OperationalState::GenericOperationalError & err) override; - /** * Handle the GoHome command. * @param err diff --git a/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h b/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h index 192bb6718bfb0f..ef90de38697f4c 100644 --- a/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h +++ b/examples/all-clusters-app/all-clusters-common/include/static-supported-modes-manager.h @@ -50,7 +50,7 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp }; static storage_value_type coffeeOptions[]; - static const EndpointSpanPair supportedOptionsByEndpoints[EMBER_AF_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT]; + static const EndpointSpanPair supportedOptionsByEndpoints[MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT]; public: static const StaticSupportedModesManager instance; diff --git a/examples/all-clusters-app/all-clusters-common/include/static-supported-temperature-levels.h b/examples/all-clusters-app/all-clusters-common/include/static-supported-temperature-levels.h index 50739de0201628..3fdce87e109317 100644 --- a/examples/all-clusters-app/all-clusters-common/include/static-supported-temperature-levels.h +++ b/examples/all-clusters-app/all-clusters-common/include/static-supported-temperature-levels.h @@ -49,7 +49,7 @@ class AppSupportedTemperatureLevelsDelegate : public SupportedTemperatureLevelsI static CharSpan temperatureLevelOptions[3]; public: - static const EndpointPair supportedOptionsByEndpoints[EMBER_AF_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT]; + static const EndpointPair supportedOptionsByEndpoints[MATTER_DM_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT]; uint8_t Size() override; diff --git a/examples/all-clusters-app/all-clusters-common/src/rvc-operational-state-delegate-impl.cpp b/examples/all-clusters-app/all-clusters-common/src/rvc-operational-state-delegate-impl.cpp index 946110bb18906c..e41ae2b863fa54 100644 --- a/examples/all-clusters-app/all-clusters-common/src/rvc-operational-state-delegate-impl.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/rvc-operational-state-delegate-impl.cpp @@ -70,34 +70,6 @@ void RvcOperationalStateDelegate::HandleResumeStateCallback(OperationalState::Ge } } -void RvcOperationalStateDelegate::HandleStartStateCallback(OperationalState::GenericOperationalError & err) -{ - // placeholder implementation - auto error = GetInstance()->SetOperationalState(to_underlying(OperationalState::OperationalStateEnum::kRunning)); - if (error == CHIP_NO_ERROR) - { - err.Set(to_underlying(OperationalState::ErrorStateEnum::kNoError)); - } - else - { - err.Set(to_underlying(OperationalState::ErrorStateEnum::kUnableToCompleteOperation)); - } -} - -void RvcOperationalStateDelegate::HandleStopStateCallback(OperationalState::GenericOperationalError & err) -{ - // placeholder implementation - auto error = GetInstance()->SetOperationalState(to_underlying(OperationalState::OperationalStateEnum::kStopped)); - if (error == CHIP_NO_ERROR) - { - err.Set(to_underlying(OperationalState::ErrorStateEnum::kNoError)); - } - else - { - err.Set(to_underlying(OperationalState::ErrorStateEnum::kUnableToCompleteOperation)); - } -} - void RvcOperationalStateDelegate::HandleGoHomeCommandCallback(OperationalState::GenericOperationalError & err) { // placeholder implementation diff --git a/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp b/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp index 17fa5d007b8493..4060d4be85ec9c 100644 --- a/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp @@ -35,7 +35,7 @@ storage_value_type StaticSupportedModesManager::coffeeOptions[] = { buildModeOptionStruct("Espresso", 7, List(semanticTagsEspresso)) }; const StaticSupportedModesManager::EndpointSpanPair - StaticSupportedModesManager::supportedOptionsByEndpoints[EMBER_AF_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT] = { + StaticSupportedModesManager::supportedOptionsByEndpoints[MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT] = { EndpointSpanPair(1, Span(StaticSupportedModesManager::coffeeOptions)) // Options for Endpoint 1 }; diff --git a/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp b/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp index 0a830480fb188c..6019006c2a2868 100644 --- a/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/static-supported-temperature-levels.cpp @@ -30,7 +30,7 @@ CharSpan AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions[] = { Ch CharSpan("Freezing", 8) }; const AppSupportedTemperatureLevelsDelegate::EndpointPair AppSupportedTemperatureLevelsDelegate::supportedOptionsByEndpoints - [EMBER_AF_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT] = { + [MATTER_DM_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT] = { EndpointPair(1, AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions, 3) // Options for Endpoint 1 }; diff --git a/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h b/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h index 588d77da1ce652..440ba53f4ee3ba 100644 --- a/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h +++ b/examples/all-clusters-app/linux/include/CHIPProjectAppConfig.h @@ -41,7 +41,7 @@ #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DEVICE_TYPE 1 // Marks that a ModeBase Derived cluster is being used. -#define EMBER_AF_PLUGIN_MODE_BASE +#define MATTER_DM_PLUGIN_MODE_BASE // Enable batching of up to 5 commands. #define CHIP_CONFIG_MAX_PATHS_PER_INVOKE 5 diff --git a/examples/all-clusters-app/linux/main-common.cpp b/examples/all-clusters-app/linux/main-common.cpp index 1d849dc5f2751b..775f4a1c0f324c 100644 --- a/examples/all-clusters-app/linux/main-common.cpp +++ b/examples/all-clusters-app/linux/main-common.cpp @@ -104,7 +104,7 @@ const Clusters::Descriptor::Structs::SemanticTagStruct::Type gEp2TagList[] = { }; } // namespace -#ifdef EMBER_AF_PLUGIN_DISHWASHER_ALARM_SERVER +#ifdef MATTER_DM_PLUGIN_DISHWASHER_ALARM_SERVER extern void MatterDishwasherAlarmServerInit(); #endif @@ -225,7 +225,7 @@ void ApplicationInit() SetDeviceInstanceInfoProvider(&gExampleDeviceInstanceInfoProvider); } -#ifdef EMBER_AF_PLUGIN_DISHWASHER_ALARM_SERVER +#ifdef MATTER_DM_PLUGIN_DISHWASHER_ALARM_SERVER MatterDishwasherAlarmServerInit(); #endif Clusters::TemperatureControl::SetInstance(&sAppSupportedTemperatureLevelsDelegate); diff --git a/examples/android/CHIPTest/app/src/main/cpp/CHIPTest-JNI.cpp b/examples/android/CHIPTest/app/src/main/cpp/CHIPTest-JNI.cpp index fbf88e673f8059..c1d9ffe2e1c985 100644 --- a/examples/android/CHIPTest/app/src/main/cpp/CHIPTest-JNI.cpp +++ b/examples/android/CHIPTest/app/src/main/cpp/CHIPTest-JNI.cpp @@ -63,10 +63,15 @@ jint JNI_OnLoad(JavaVM * jvm, void * reserved) ChipLogProgress(Test, "Loading Java class references."); // Get various class references need by the API. - err = JniReferences::GetInstance().GetClassRef(env, "com/tcl/chip/chiptest/TestEngine", sTestEngineCls); + jobject testEngineCls; + err = JniReferences::GetInstance().GetLocalClassRef(env, "com/tcl/chip/chiptest/TestEngine", sTestEngineCls); SuccessOrExit(err); - - err = JniReferences::GetInstance().GetClassRef(env, "com/tcl/chip/chiptest/TestEngineException", sTestEngineExceptionCls); + err = sTestEngineCls.Init(testEngineCls); + SuccessOrExit(err); + jobject testEngineExceptionCls; + err = JniReferences::GetInstance().GetLocalClassRef(env, "com/tcl/chip/chiptest/TestEngineException", sTestEngineExceptionCls); + SuccessOrExit(err); + err = sTestEngineExceptionCls.Init(testEngineExceptionCls); SuccessOrExit(err); ChipLogProgress(Test, "Java class references loaded."); @@ -141,7 +146,7 @@ CHIP_ERROR N2J_Error(JNIEnv * env, CHIP_ERROR inErr, jthrowable & outEx) jmethodID constructor; env->ExceptionClear(); - constructor = env->GetMethodID(sTestEngineExceptionCls, "", "(ILjava/lang/String;)V"); + constructor = env->GetMethodID(sTestEngineExceptionCls.ObjectRef(), "", "(ILjava/lang/String;)V"); VerifyOrExit(constructor != NULL, err = CHIP_JNI_ERROR_METHOD_NOT_FOUND); switch (inErr.AsInteger()) @@ -164,7 +169,8 @@ CHIP_ERROR N2J_Error(JNIEnv * env, CHIP_ERROR inErr, jthrowable & outEx) } errStrObj = (errStr != NULL) ? env->NewStringUTF(errStr) : NULL; - outEx = (jthrowable) env->NewObject(sTestEngineExceptionCls, constructor, static_cast(inErr.AsInteger()), errStrObj); + outEx = (jthrowable) env->NewObject(sTestEngineExceptionCls.ObjectRef(), constructor, static_cast(inErr.AsInteger()), + errStrObj); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -184,7 +190,7 @@ static void onLog(const char * fmt, ...) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); - method = env->GetStaticMethodID(sTestEngineCls, "onTestLog", "(Ljava/lang/String;)V"); + method = env->GetStaticMethodID(sTestEngineCls.ObjectRef(), "onTestLog", "(Ljava/lang/String;)V"); VerifyOrExit(method != NULL, err = CHIP_JNI_ERROR_NO_ENV); va_start(args, fmt); @@ -195,7 +201,7 @@ static void onLog(const char * fmt, ...) ChipLogProgress(Test, "Calling Java onTestLog"); env->ExceptionClear(); - env->CallStaticVoidMethod(sTestEngineCls, method, strObj); + env->CallStaticVoidMethod(sTestEngineCls.ObjectRef(), method, strObj); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: diff --git a/examples/chef/common/chef-air-quality.cpp b/examples/chef/common/chef-air-quality.cpp index 3385c9e455e339..0770d0c185aa0c 100644 --- a/examples/chef/common/chef-air-quality.cpp +++ b/examples/chef/common/chef-air-quality.cpp @@ -25,7 +25,7 @@ using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; -#ifdef EMBER_AF_PLUGIN_AIR_QUALITY_SERVER +#ifdef MATTER_DM_PLUGIN_AIR_QUALITY_SERVER #include using namespace chip::app::Clusters::AirQuality; diff --git a/examples/chef/common/chef-air-quality.h b/examples/chef/common/chef-air-quality.h index 0749d4d1afe662..39019b03fbb781 100644 --- a/examples/chef/common/chef-air-quality.h +++ b/examples/chef/common/chef-air-quality.h @@ -21,7 +21,7 @@ #include #include -#ifdef EMBER_AF_PLUGIN_AIR_QUALITY_SERVER +#ifdef MATTER_DM_PLUGIN_AIR_QUALITY_SERVER EmberAfStatus chefAirQualityWriteCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer); EmberAfStatus chefAirQualityReadCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, diff --git a/examples/chef/common/chef-channel-manager.cpp b/examples/chef/common/chef-channel-manager.cpp index b50cb0076f6f38..4a8d6de466d746 100644 --- a/examples/chef/common/chef-channel-manager.cpp +++ b/examples/chef/common/chef-channel-manager.cpp @@ -23,7 +23,7 @@ using ChangeChannelResponseType = chip::app::Clusters::Channel::Commands::Change using ChannelInfoType = chip::app::Clusters::Channel::Structs::ChannelInfoStruct::Type; using LineupInfoType = chip::app::Clusters::Channel::Structs::LineupInfoStruct::Type; // Include Channel Cluster Server callbacks only when the server is enabled -#ifdef EMBER_AF_PLUGIN_CHANNEL_SERVER +#ifdef MATTER_DM_PLUGIN_CHANNEL_SERVER #include using namespace chip; @@ -213,7 +213,7 @@ bool ChefChannelManager::HandleSkipChannel(const int16_t & count) uint32_t ChefChannelManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint > EMBER_AF_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint > MATTER_DM_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT) { return 0; } @@ -223,4 +223,4 @@ uint32_t ChefChannelManager::GetFeatureMap(chip::EndpointId endpoint) return featureMap; } -#endif /* EMBER_AF_PLUGIN_CHANNEL_SERVER */ +#endif /* MATTER_DM_PLUGIN_CHANNEL_SERVER */ diff --git a/examples/chef/common/chef-concentration-measurement.cpp b/examples/chef/common/chef-concentration-measurement.cpp index 90c6f85d3b99d1..395d6604582edf 100644 --- a/examples/chef/common/chef-concentration-measurement.cpp +++ b/examples/chef/common/chef-concentration-measurement.cpp @@ -27,16 +27,16 @@ using namespace chip::app; using namespace chip::app::DataModel; using namespace chip::app::Clusters; -#if defined(EMBER_AF_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) +#if defined(MATTER_DM_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) #include using namespace chip::app::Clusters::ConcentrationMeasurement; @@ -184,7 +184,7 @@ EmberAfStatus chefConcentrationMeasurementReadCallback(chip::EndpointId endpoint } #endif -#ifdef EMBER_AF_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER void emberAfCarbonMonoxideConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gCarbonMonoxideConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -202,7 +202,7 @@ void emberAfCarbonMonoxideConcentrationMeasurementClusterInitCallback(EndpointId } #endif -#ifdef EMBER_AF_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER void emberAfCarbonDioxideConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gCarbonDioxideConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -220,7 +220,7 @@ void emberAfCarbonDioxideConcentrationMeasurementClusterInitCallback(EndpointId } #endif -#ifdef EMBER_AF_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER void emberAfNitrogenDioxideConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gNitrogenDioxideConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -238,7 +238,7 @@ void emberAfNitrogenDioxideConcentrationMeasurementClusterInitCallback(EndpointI } #endif -#ifdef EMBER_AF_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER void emberAfOzoneConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gOzoneConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -256,7 +256,7 @@ void emberAfOzoneConcentrationMeasurementClusterInitCallback(EndpointId endpoint } #endif -#ifdef EMBER_AF_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER void emberAfPm25ConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gPm25ConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -274,7 +274,7 @@ void emberAfPm25ConcentrationMeasurementClusterInitCallback(EndpointId endpoint) } #endif -#ifdef EMBER_AF_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER void emberAfFormaldehydeConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gFormaldehydeConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -292,7 +292,7 @@ void emberAfFormaldehydeConcentrationMeasurementClusterInitCallback(EndpointId e } #endif -#ifdef EMBER_AF_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER void emberAfPm1ConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gPm1ConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -310,7 +310,7 @@ void emberAfPm1ConcentrationMeasurementClusterInitCallback(EndpointId endpoint) } #endif -#ifdef EMBER_AF_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER void emberAfPm10ConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gPm10ConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -328,7 +328,7 @@ void emberAfPm10ConcentrationMeasurementClusterInitCallback(EndpointId endpoint) } #endif -#ifdef EMBER_AF_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER void emberAfRadonConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gRadonConcentrationMeasurementInstance[EndpointId(endpoint)] = new Instance( @@ -346,7 +346,7 @@ void emberAfRadonConcentrationMeasurementClusterInitCallback(EndpointId endpoint } #endif -#ifdef EMBER_AF_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER +#ifdef MATTER_DM_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER void emberAfTotalVolatileOrganicCompoundsConcentrationMeasurementClusterInitCallback(EndpointId endpoint) { gTotalVolatileOrganicCompoundsConcentrationMeasurementInstance[EndpointId(endpoint)] = diff --git a/examples/chef/common/chef-concentration-measurement.h b/examples/chef/common/chef-concentration-measurement.h index ea874314814f22..ddd004ebd7047e 100644 --- a/examples/chef/common/chef-concentration-measurement.h +++ b/examples/chef/common/chef-concentration-measurement.h @@ -21,16 +21,16 @@ #include #include -#if defined(EMBER_AF_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) +#if defined(MATTER_DM_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) EmberAfStatus chefConcentrationMeasurementWriteCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer); EmberAfStatus chefConcentrationMeasurementReadCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, diff --git a/examples/chef/common/chef-rvc-operational-state-delegate.cpp b/examples/chef/common/chef-rvc-operational-state-delegate.cpp index 6a773f41c6450e..9ea4e610e64fb1 100644 --- a/examples/chef/common/chef-rvc-operational-state-delegate.cpp +++ b/examples/chef/common/chef-rvc-operational-state-delegate.cpp @@ -167,4 +167,4 @@ void emberAfRvcOperationalStateClusterInitCallback(chip::EndpointId endpointId) gRvcOperationalStateInstance->Init(); } -#endif // EMBER_AF_PLUGIN_RVC_OPERATIONAL_STATE_SERVER +#endif // MATTER_DM_PLUGIN_RVC_OPERATIONAL_STATE_SERVER diff --git a/examples/chef/common/stubs.cpp b/examples/chef/common/stubs.cpp index bfd5e370cba136..483919c1c9a952 100644 --- a/examples/chef/common/stubs.cpp +++ b/examples/chef/common/stubs.cpp @@ -3,19 +3,19 @@ #include #include #include -#ifdef EMBER_AF_PLUGIN_AIR_QUALITY_SERVER +#ifdef MATTER_DM_PLUGIN_AIR_QUALITY_SERVER #include "chef-air-quality.h" -#endif // EMBER_AF_PLUGIN_AIR_QUALITY_SERVER -#if defined(EMBER_AF_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) +#endif // MATTER_DM_PLUGIN_AIR_QUALITY_SERVER +#if defined(MATTER_DM_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) #include "chef-concentration-measurement.h" #endif @@ -29,20 +29,20 @@ EmberAfStatus emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterI { switch (clusterId) { -#ifdef EMBER_AF_PLUGIN_AIR_QUALITY_SERVER +#ifdef MATTER_DM_PLUGIN_AIR_QUALITY_SERVER case chip::app::Clusters::AirQuality::Id: return chefAirQualityReadCallback(endpoint, clusterId, attributeMetadata, buffer, maxReadLength); #endif -#if defined(EMBER_AF_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) +#if defined(MATTER_DM_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Id: case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Id: case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Id: @@ -76,20 +76,20 @@ EmberAfStatus emberAfExternalAttributeWriteCallback(EndpointId endpoint, Cluster { switch (clusterId) { -#ifdef EMBER_AF_PLUGIN_AIR_QUALITY_SERVER +#ifdef MATTER_DM_PLUGIN_AIR_QUALITY_SERVER case chip::app::Clusters::AirQuality::Id: return chefAirQualityWriteCallback(endpoint, clusterId, attributeMetadata, buffer); #endif -#if defined(EMBER_AF_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ - defined(EMBER_AF_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) +#if defined(MATTER_DM_PLUGIN_CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_OZONE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM2__5_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_FORMALDEHYDE_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM1_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_PM10_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_TOTAL_VOLATILE_ORGANIC_COMPOUNDS_CONCENTRATION_MEASUREMENT_SERVER) || \ + defined(MATTER_DM_PLUGIN_RADON_CONCENTRATION_MEASUREMENT_SERVER) case chip::app::Clusters::CarbonMonoxideConcentrationMeasurement::Id: case chip::app::Clusters::CarbonDioxideConcentrationMeasurement::Id: case chip::app::Clusters::NitrogenDioxideConcentrationMeasurement::Id: @@ -109,7 +109,7 @@ EmberAfStatus emberAfExternalAttributeWriteCallback(EndpointId endpoint, Cluster } // Include door lock callbacks only when the server is enabled -#ifdef EMBER_AF_PLUGIN_DOOR_LOCK_SERVER +#ifdef MATTER_DM_PLUGIN_DOOR_LOCK_SERVER #include class LockManager @@ -338,9 +338,9 @@ bool emberAfPluginDoorLockSetCredential(chip::EndpointId endpointId, uint16_t cr credentialType, credentialData); } -#endif /* EMBER_AF_PLUGIN_DOOR_LOCK_SERVER */ +#endif /* MATTER_DM_PLUGIN_DOOR_LOCK_SERVER */ -#ifdef EMBER_AF_PLUGIN_CHANNEL_SERVER +#ifdef MATTER_DM_PLUGIN_CHANNEL_SERVER #include void emberAfChannelClusterInitCallback(EndpointId endpoint) @@ -348,6 +348,6 @@ void emberAfChannelClusterInitCallback(EndpointId endpoint) app::Clusters::Channel::SetDefaultDelegate(endpoint, static_cast(&(ChefChannelManager::Instance()))); } -#endif // EMBER_AF_PLUGIN_CHANNEL_SERVER +#endif // MATTER_DM_PLUGIN_CHANNEL_SERVER void emberAfPluginSmokeCoAlarmSelfTestRequestCommand(EndpointId endpointId) {} diff --git a/examples/placeholder/linux/include/static-supported-modes-manager.h b/examples/placeholder/linux/include/static-supported-modes-manager.h index 192bb6718bfb0f..ef90de38697f4c 100644 --- a/examples/placeholder/linux/include/static-supported-modes-manager.h +++ b/examples/placeholder/linux/include/static-supported-modes-manager.h @@ -50,7 +50,7 @@ class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::Supp }; static storage_value_type coffeeOptions[]; - static const EndpointSpanPair supportedOptionsByEndpoints[EMBER_AF_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT]; + static const EndpointSpanPair supportedOptionsByEndpoints[MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT]; public: static const StaticSupportedModesManager instance; diff --git a/examples/placeholder/linux/include/static-supported-temperature-levels.h b/examples/placeholder/linux/include/static-supported-temperature-levels.h index 50739de0201628..3fdce87e109317 100644 --- a/examples/placeholder/linux/include/static-supported-temperature-levels.h +++ b/examples/placeholder/linux/include/static-supported-temperature-levels.h @@ -49,7 +49,7 @@ class AppSupportedTemperatureLevelsDelegate : public SupportedTemperatureLevelsI static CharSpan temperatureLevelOptions[3]; public: - static const EndpointPair supportedOptionsByEndpoints[EMBER_AF_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT]; + static const EndpointPair supportedOptionsByEndpoints[MATTER_DM_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT]; uint8_t Size() override; diff --git a/examples/placeholder/linux/static-supported-modes-manager.cpp b/examples/placeholder/linux/static-supported-modes-manager.cpp index 17fa5d007b8493..4060d4be85ec9c 100644 --- a/examples/placeholder/linux/static-supported-modes-manager.cpp +++ b/examples/placeholder/linux/static-supported-modes-manager.cpp @@ -35,7 +35,7 @@ storage_value_type StaticSupportedModesManager::coffeeOptions[] = { buildModeOptionStruct("Espresso", 7, List(semanticTagsEspresso)) }; const StaticSupportedModesManager::EndpointSpanPair - StaticSupportedModesManager::supportedOptionsByEndpoints[EMBER_AF_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT] = { + StaticSupportedModesManager::supportedOptionsByEndpoints[MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT] = { EndpointSpanPair(1, Span(StaticSupportedModesManager::coffeeOptions)) // Options for Endpoint 1 }; diff --git a/examples/placeholder/linux/static-supported-temperature-levels.cpp b/examples/placeholder/linux/static-supported-temperature-levels.cpp index ed80f5490df821..de8933fdf649ea 100644 --- a/examples/placeholder/linux/static-supported-temperature-levels.cpp +++ b/examples/placeholder/linux/static-supported-temperature-levels.cpp @@ -29,7 +29,7 @@ using chip::Protocols::InteractionModel::Status; CharSpan AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions[] = { "Hot"_span, "Warm"_span, "Cold"_span }; const AppSupportedTemperatureLevelsDelegate::EndpointPair AppSupportedTemperatureLevelsDelegate::supportedOptionsByEndpoints - [EMBER_AF_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT] = { + [MATTER_DM_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT] = { EndpointPair(1, AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions, 3) // Options for Endpoint 1 }; diff --git a/examples/platform/asr/CHIPDeviceManager.cpp b/examples/platform/asr/CHIPDeviceManager.cpp index 9d190400c53aa7..9aa349dc6d517e 100644 --- a/examples/platform/asr/CHIPDeviceManager.cpp +++ b/examples/platform/asr/CHIPDeviceManager.cpp @@ -32,7 +32,7 @@ #include #include -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER #include #endif @@ -81,7 +81,7 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & } } -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER void OnIdentifyStart(Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); diff --git a/examples/platform/silabs/BaseApplication.cpp b/examples/platform/silabs/BaseApplication.cpp index d2c6266a58382b..4216dbb4864452 100644 --- a/examples/platform/silabs/BaseApplication.cpp +++ b/examples/platform/silabs/BaseApplication.cpp @@ -129,7 +129,7 @@ StaticTask_t appTaskStruct; SilabsLCD slLCD; #endif -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER Clusters::Identify::EffectIdentifierEnum sIdentifyEffect = Clusters::Identify::EffectIdentifierEnum::kStopEffect; Identify gIdentify = { @@ -140,7 +140,7 @@ Identify gIdentify = { BaseApplication::OnTriggerIdentifyEffect, }; -#endif // EMBER_AF_PLUGIN_IDENTIFY_SERVER +#endif // MATTER_DM_PLUGIN_IDENTIFY_SERVER } // namespace bool BaseApplication::sIsProvisioned = false; @@ -298,7 +298,7 @@ bool BaseApplication::ActivateStatusLedPatterns() { bool isPatternSet = false; #if (defined(ENABLE_WSTK_LEDS) && (defined(SL_CATALOG_SIMPLE_LED_LED1_PRESENT) || defined(SIWX_917))) -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER if (gIdentify.mActive) { // Identify in progress @@ -342,7 +342,7 @@ bool BaseApplication::ActivateStatusLedPatterns() } isPatternSet = true; } -#endif // EMBER_AF_PLUGIN_IDENTIFY_SERVER +#endif // MATTER_DM_PLUGIN_IDENTIFY_SERVER #if !(defined(CHIP_CONFIG_ENABLE_ICD_SERVER) && CHIP_CONFIG_ENABLE_ICD_SERVER) // Identify Patterns have priority over Status patterns @@ -583,7 +583,7 @@ void BaseApplication::StopStatusLEDTimer() } } -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER void BaseApplication::OnIdentifyStart(Identify * identify) { ChipLogProgress(Zcl, "onIdentifyStart"); @@ -650,7 +650,7 @@ void BaseApplication::OnTriggerIdentifyEffect(Identify * identify) ChipLogProgress(Zcl, "No identifier effect"); } } -#endif // EMBER_AF_PLUGIN_IDENTIFY_SERVER +#endif // MATTER_DM_PLUGIN_IDENTIFY_SERVER void BaseApplication::LightTimerEventHandler(TimerHandle_t xTimer) { diff --git a/examples/platform/silabs/BaseApplication.h b/examples/platform/silabs/BaseApplication.h index b38f0e58e1c305..1714f47024f2c2 100644 --- a/examples/platform/silabs/BaseApplication.h +++ b/examples/platform/silabs/BaseApplication.h @@ -38,7 +38,7 @@ #include "LEDWidget.h" -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER #include #endif @@ -134,7 +134,7 @@ class BaseApplication static void StartFactoryResetSequence(void); static void CancelFactoryResetSequence(void); -#ifdef EMBER_AF_PLUGIN_IDENTIFY_SERVER +#ifdef MATTER_DM_PLUGIN_IDENTIFY_SERVER // Idenfiy server command callbacks. static void OnIdentifyStart(Identify * identify); static void OnIdentifyStop(Identify * identify); diff --git a/examples/platform/silabs/SoftwareFaultReports.cpp b/examples/platform/silabs/SoftwareFaultReports.cpp index 0f4e8a4822a435..0b730576807628 100644 --- a/examples/platform/silabs/SoftwareFaultReports.cpp +++ b/examples/platform/silabs/SoftwareFaultReports.cpp @@ -54,7 +54,7 @@ namespace Silabs { void OnSoftwareFaultEventHandler(const char * faultRecordString) { -#ifdef EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER +#ifdef MATTER_DM_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER EnabledEndpointsWithServerCluster enabledEndpoints(SoftwareDiagnostics::Id); VerifyOrReturn(enabledEndpoints.begin() != enabledEndpoints.end()); @@ -71,7 +71,7 @@ void OnSoftwareFaultEventHandler(const char * faultRecordString) softwareFault.faultRecording.SetValue(ByteSpan(Uint8::from_const_char(faultRecordString), strlen(faultRecordString))); SoftwareDiagnosticsServer::Instance().OnSoftwareFaultDetect(softwareFault); -#endif // EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER +#endif // MATTER_DM_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER } } // namespace Silabs diff --git a/examples/refrigerator-app/refrigerator-common/include/static-supported-temperature-levels.h b/examples/refrigerator-app/refrigerator-common/include/static-supported-temperature-levels.h index 50739de0201628..3fdce87e109317 100644 --- a/examples/refrigerator-app/refrigerator-common/include/static-supported-temperature-levels.h +++ b/examples/refrigerator-app/refrigerator-common/include/static-supported-temperature-levels.h @@ -49,7 +49,7 @@ class AppSupportedTemperatureLevelsDelegate : public SupportedTemperatureLevelsI static CharSpan temperatureLevelOptions[3]; public: - static const EndpointPair supportedOptionsByEndpoints[EMBER_AF_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT]; + static const EndpointPair supportedOptionsByEndpoints[MATTER_DM_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT]; uint8_t Size() override; diff --git a/examples/refrigerator-app/refrigerator-common/src/static-supported-temperature-levels.cpp b/examples/refrigerator-app/refrigerator-common/src/static-supported-temperature-levels.cpp index a03a98d89feb1f..8678e5f3d009d0 100644 --- a/examples/refrigerator-app/refrigerator-common/src/static-supported-temperature-levels.cpp +++ b/examples/refrigerator-app/refrigerator-common/src/static-supported-temperature-levels.cpp @@ -31,7 +31,7 @@ CharSpan AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions[] = { Ch CharSpan::fromCharString("Freezing") }; const AppSupportedTemperatureLevelsDelegate::EndpointPair AppSupportedTemperatureLevelsDelegate::supportedOptionsByEndpoints - [EMBER_AF_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT] = { + [MATTER_DM_TEMPERATURE_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT] = { EndpointPair(2, AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions, ArraySize(AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions)), // Options for Endpoint 2 EndpointPair(3, AppSupportedTemperatureLevelsDelegate::temperatureLevelOptions, diff --git a/examples/rvc-app/rvc-common/include/rvc-operational-state-delegate.h b/examples/rvc-app/rvc-common/include/rvc-operational-state-delegate.h index 400dfd67910234..e40ba64fbf7f3a 100644 --- a/examples/rvc-app/rvc-common/include/rvc-operational-state-delegate.h +++ b/examples/rvc-app/rvc-common/include/rvc-operational-state-delegate.h @@ -99,22 +99,6 @@ class RvcOperationalStateDelegate : public RvcOperationalState::Delegate */ void HandleResumeStateCallback(Clusters::OperationalState::GenericOperationalError & err) override; - /** - * Handle Command Callback in application: Start - * @param[out] get operational error after callback. - */ - void HandleStartStateCallback(Clusters::OperationalState::GenericOperationalError & err) override{ - // This command in not supported. - }; - - /** - * Handle Command Callback in application: Stop - * @param[out] get operational error after callback. - */ - void HandleStopStateCallback(Clusters::OperationalState::GenericOperationalError & err) override{ - // This command in not supported. - }; - void SetPauseCallback(HandleOpStateCommand aCallback, RvcDevice * aInstance) { mPauseCallback = aCallback; diff --git a/examples/tv-app/android/include/content-control/ContentController.cpp b/examples/tv-app/android/include/content-control/ContentController.cpp index c4eee0355f4552..99373583b0632d 100644 --- a/examples/tv-app/android/include/content-control/ContentController.cpp +++ b/examples/tv-app/android/include/content-control/ContentController.cpp @@ -94,7 +94,7 @@ void ContentController::HandleSetScheduledContentRatingThreshold(chip::CharSpan uint32_t ContentController::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/android/include/content-launcher/AppContentLauncherManager.cpp b/examples/tv-app/android/include/content-launcher/AppContentLauncherManager.cpp index 329df8cd802299..50b451994de2f7 100644 --- a/examples/tv-app/android/include/content-launcher/AppContentLauncherManager.cpp +++ b/examples/tv-app/android/include/content-launcher/AppContentLauncherManager.cpp @@ -156,7 +156,7 @@ uint32_t AppContentLauncherManager::HandleGetSupportedStreamingProtocols() uint32_t AppContentLauncherManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/android/include/media-playback/AppMediaPlaybackManager.cpp b/examples/tv-app/android/include/media-playback/AppMediaPlaybackManager.cpp index e7d8100e9e5ce0..c3195133711552 100644 --- a/examples/tv-app/android/include/media-playback/AppMediaPlaybackManager.cpp +++ b/examples/tv-app/android/include/media-playback/AppMediaPlaybackManager.cpp @@ -274,7 +274,7 @@ CHIP_ERROR AppMediaPlaybackManager::HandleGetSampledPosition(AttributeValueEncod uint32_t AppMediaPlaybackManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/android/java/ChannelManager.cpp b/examples/tv-app/android/java/ChannelManager.cpp index d471bebf3075f6..d7657fd5622fee 100644 --- a/examples/tv-app/android/java/ChannelManager.cpp +++ b/examples/tv-app/android/java/ChannelManager.cpp @@ -63,11 +63,12 @@ CHIP_ERROR ChannelManager::HandleGetChannelList(AttributeValueEncoder & aEncoder JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ChannelManager::HandleGetChannelList"); - VerifyOrExit(mChannelManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetChannelListMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); return aEncoder.EncodeList([this, env](const auto & encoder) -> CHIP_ERROR { - jobjectArray channelInfoList = (jobjectArray) env->CallObjectMethod(mChannelManagerObject, mGetChannelListMethod); + jobjectArray channelInfoList = + (jobjectArray) env->CallObjectMethod(mChannelManagerObject.ObjectRef(), mGetChannelListMethod); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ChannelManager::HandleGetChannelList"); @@ -140,11 +141,11 @@ CHIP_ERROR ChannelManager::HandleGetLineup(AttributeValueEncoder & aEncoder) JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ChannelManager::HandleGetLineup"); - VerifyOrExit(mChannelManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetLineupMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); { - jobject channelLineupObject = env->CallObjectMethod(mChannelManagerObject, mGetLineupMethod); + jobject channelLineupObject = env->CallObjectMethod(mChannelManagerObject.ObjectRef(), mGetLineupMethod); if (channelLineupObject != nullptr) { jclass channelLineupClazz = env->GetObjectClass(channelLineupObject); @@ -203,11 +204,11 @@ CHIP_ERROR ChannelManager::HandleGetCurrentChannel(AttributeValueEncoder & aEnco JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ChannelManager::HandleGetCurrentChannel"); - VerifyOrExit(mChannelManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetCurrentChannelMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); { - jobject channelInfoObject = env->CallObjectMethod(mChannelManagerObject, mGetCurrentChannelMethod); + jobject channelInfoObject = env->CallObjectMethod(mChannelManagerObject.ObjectRef(), mGetCurrentChannelMethod); if (channelInfoObject != nullptr) { jclass channelClass = env->GetObjectClass(channelInfoObject); @@ -278,13 +279,13 @@ void ChannelManager::HandleChangeChannel(CommandResponseHelperExceptionClear(); - jobject channelObject = env->CallObjectMethod(mChannelManagerObject, mChangeChannelMethod, jniname.jniValue()); + jobject channelObject = env->CallObjectMethod(mChannelManagerObject.ObjectRef(), mChangeChannelMethod, jniname.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in ChannelManager::HandleChangeChannel"); @@ -325,12 +326,12 @@ bool ChannelManager::HandleChangeChannelByNumber(const uint16_t & majorNumber, c ChipLogProgress(Zcl, "Received ChannelManager::HandleChangeChannelByNumber majorNumber %d, minorNumber %d", majorNumber, minorNumber); - VerifyOrExit(mChannelManagerObject != nullptr, ChipLogError(Zcl, "mChannelManagerObject null")); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mChannelManagerObject null")); VerifyOrExit(mChangeChannelByNumberMethod != nullptr, ChipLogError(Zcl, "mChangeChannelByNumberMethod null")); env->ExceptionClear(); - ret = env->CallBooleanMethod(mChannelManagerObject, mChangeChannelByNumberMethod, static_cast(majorNumber), + ret = env->CallBooleanMethod(mChannelManagerObject.ObjectRef(), mChangeChannelByNumberMethod, static_cast(majorNumber), static_cast(minorNumber)); if (env->ExceptionCheck()) { @@ -352,12 +353,12 @@ bool ChannelManager::HandleSkipChannel(const int16_t & count) JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ChannelManager::HandleSkipChannel count %d", count); - VerifyOrExit(mChannelManagerObject != nullptr, ChipLogError(Zcl, "mChannelManagerObject null")); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mChannelManagerObject null")); VerifyOrExit(mSkipChannelMethod != nullptr, ChipLogError(Zcl, "mSkipChannelMethod null")); env->ExceptionClear(); - ret = env->CallBooleanMethod(mChannelManagerObject, mSkipChannelMethod, static_cast(count)); + ret = env->CallBooleanMethod(mChannelManagerObject.ObjectRef(), mSkipChannelMethod, static_cast(count)); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in ChannelManager::HandleSkipChannel"); @@ -390,7 +391,7 @@ void ChannelManager::HandleGetProgramGuide( std::vector needToFreeStrings; ChipLogProgress(Zcl, "Received ChannelManager::HandleGetProgramGuide"); - VerifyOrExit(mChannelManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetProgramGuideMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); { @@ -401,7 +402,7 @@ void ChannelManager::HandleGetProgramGuide( jobjectArray externalIDListArray = (jobjectArray) env->NewObjectArray(0, env->FindClass("java/util/Map$Entry"), NULL); jobject resp = env->CallObjectMethod( - mChannelManagerObject, mGetProgramGuideMethod, static_cast(startTime.ValueOr(0)), + mChannelManagerObject.ObjectRef(), mGetProgramGuideMethod, static_cast(startTime.ValueOr(0)), static_cast(endTime.ValueOr(0)), channelsArray, jToken.jniValue(), static_cast(recordingFlag.ValueOr(0).Raw() != 0), externalIDListArray, jData.jniValue()); if (env->ExceptionCheck()) @@ -596,7 +597,7 @@ bool ChannelManager::HandleRecordProgram(const chip::CharSpan & programIdentifie JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ChannelManager::HandleRecordProgram"); - VerifyOrExit(mChannelManagerObject != nullptr, ChipLogError(Zcl, "mChannelManagerObject null")); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mChannelManagerObject null")); VerifyOrExit(mRecordProgramMethod != nullptr, ChipLogError(Zcl, "mRecordProgramMethod null")); env->ExceptionClear(); @@ -608,7 +609,7 @@ bool ChannelManager::HandleRecordProgram(const chip::CharSpan & programIdentifie UtfString jData(env, ""); jobjectArray externalIDListArray = (jobjectArray) env->NewObjectArray(0, env->FindClass("java/util/Map$Entry"), NULL); - ret = env->CallBooleanMethod(mChannelManagerObject, mRecordProgramMethod, jIdentifier.jniValue(), + ret = env->CallBooleanMethod(mChannelManagerObject.ObjectRef(), mRecordProgramMethod, jIdentifier.jniValue(), static_cast(shouldRecordSeries), externalIDListArray, jData.jniValue()); if (env->ExceptionCheck()) { @@ -633,7 +634,7 @@ bool ChannelManager::HandleCancelRecordProgram(const chip::CharSpan & programIde JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ChannelManager::HandleCancelRecordProgram"); - VerifyOrExit(mChannelManagerObject != nullptr, ChipLogError(Zcl, "mChannelManagerObject null")); + VerifyOrExit(mChannelManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mChannelManagerObject null")); VerifyOrExit(mCancelRecordProgramMethod != nullptr, ChipLogError(Zcl, "mCancelRecordProgramMethod null")); env->ExceptionClear(); @@ -645,7 +646,7 @@ bool ChannelManager::HandleCancelRecordProgram(const chip::CharSpan & programIde UtfString jData(env, ""); jobjectArray externalIDListArray = (jobjectArray) env->NewObjectArray(0, env->FindClass("java/util/Map$Entry"), NULL); - ret = env->CallBooleanMethod(mChannelManagerObject, mCancelRecordProgramMethod, jIdentifier.jniValue(), + ret = env->CallBooleanMethod(mChannelManagerObject.ObjectRef(), mCancelRecordProgramMethod, jIdentifier.jniValue(), static_cast(shouldRecordSeries), externalIDListArray, jData.jniValue()); if (env->ExceptionCheck()) { @@ -665,10 +666,10 @@ void ChannelManager::InitializeWithObjects(jobject managerObject) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for ChannelManager")); - mChannelManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mChannelManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef ChannelManager")); + VerifyOrReturn(mChannelManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mChannelManagerObject")); - jclass managerClass = env->GetObjectClass(mChannelManagerObject); + jclass managerClass = env->GetObjectClass(managerObject); VerifyOrReturn(managerClass != nullptr, ChipLogError(Zcl, "Failed to get ChannelManager Java class")); mGetChannelListMethod = env->GetMethodID(managerClass, "getChannelList", "()[Lcom/matter/tv/server/tvapp/ChannelInfo;"); @@ -742,7 +743,7 @@ void ChannelManager::InitializeWithObjects(jobject managerObject) uint32_t ChannelManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/android/java/ChannelManager.h b/examples/tv-app/android/java/ChannelManager.h index 85d645beda40a3..95bf5317a842cc 100644 --- a/examples/tv-app/android/java/ChannelManager.h +++ b/examples/tv-app/android/java/ChannelManager.h @@ -19,6 +19,7 @@ #include #include +#include using chip::CharSpan; using chip::app::AttributeValueEncoder; @@ -66,7 +67,7 @@ class ChannelManager : public ChannelDelegate uint32_t GetFeatureMap(chip::EndpointId endpoint) override; private: - jobject mChannelManagerObject = nullptr; + chip::JniGlobalReference mChannelManagerObject; jmethodID mGetChannelListMethod = nullptr; jmethodID mGetLineupMethod = nullptr; jmethodID mGetCurrentChannelMethod = nullptr; diff --git a/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp b/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp index 54e4ee633ce7d9..84e7d9933ad022 100644 --- a/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp @@ -47,9 +47,9 @@ std::string ContentAppAttributeDelegate::Read(const chip::app::ConcreteReadAttri ChipLogProgress(Zcl, "ContentAppAttributeDelegate::Read being called for endpoint %d cluster %d attribute %d", aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId); - jstring resp = - (jstring) env->CallObjectMethod(mContentAppEndpointManager, mReadAttributeMethod, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); + jstring resp = static_cast( + env->CallObjectMethod(mContentAppEndpointManager.ObjectRef(), mReadAttributeMethod, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId))); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentAppAttributeDelegate::Read"); diff --git a/examples/tv-app/android/java/ContentAppAttributeDelegate.h b/examples/tv-app/android/java/ContentAppAttributeDelegate.h index 9d22bbc5fff7aa..25d6367762c58f 100644 --- a/examples/tv-app/android/java/ContentAppAttributeDelegate.h +++ b/examples/tv-app/android/java/ContentAppAttributeDelegate.h @@ -44,13 +44,6 @@ class ContentAppAttributeDelegate InitializeJNIObjects(manager); } - ~ContentAppAttributeDelegate() - { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for ContentAppEndpointManager")); - env->DeleteGlobalRef(mContentAppEndpointManager); - } - std::string Read(const chip::app::ConcreteReadAttributePath & aPath); private: @@ -59,9 +52,8 @@ class ContentAppAttributeDelegate JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for ContentAppEndpointManager")); - mContentAppEndpointManager = env->NewGlobalRef(manager); - VerifyOrReturn(mContentAppEndpointManager != nullptr, - ChipLogError(Zcl, "Failed to NewGlobalRef ContentAppEndpointManager")); + VerifyOrReturn(mContentAppEndpointManager.Init(manager) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mContentAppEndpointManager")); jclass ContentAppEndpointManagerClass = env->GetObjectClass(manager); VerifyOrReturn(ContentAppEndpointManagerClass != nullptr, @@ -75,8 +67,8 @@ class ContentAppAttributeDelegate } } - jobject mContentAppEndpointManager = nullptr; - jmethodID mReadAttributeMethod = nullptr; + chip::JniGlobalReference mContentAppEndpointManager; + jmethodID mReadAttributeMethod = nullptr; }; } // namespace AppPlatform diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp index 23437ee4f2b6be..53136c23e5a596 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp @@ -69,12 +69,16 @@ void ContentAppCommandDelegate::InvokeCommand(CommandHandlerInterface::HandlerCo std::string payload = JsonToString(value); UtfString jsonString(env, payload.c_str()); - ChipLogProgress(Zcl, "ContentAppCommandDelegate::InvokeCommand send command being called with payload %s", payload.c_str()); + if (!mContentAppEndpointManager.HasValidObjectRef()) + { + ChipLogProgress(Zcl, "mContentAppEndpointManager is not valid"); + return; + } - jstring resp = (jstring) env->CallObjectMethod( - mContentAppEndpointManager, mSendCommandMethod, static_cast(handlerContext.mRequestPath.mEndpointId), + jstring resp = static_cast(env->CallObjectMethod( + mContentAppEndpointManager.ObjectRef(), mSendCommandMethod, static_cast(handlerContext.mRequestPath.mEndpointId), static_cast(handlerContext.mRequestPath.mClusterId), static_cast(handlerContext.mRequestPath.mCommandId), - jsonString.jniValue()); + jsonString.jniValue())); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentAppCommandDelegate::sendCommand"); @@ -106,8 +110,13 @@ Status ContentAppCommandDelegate::InvokeCommand(EndpointId epId, ClusterId clust ChipLogProgress(Zcl, "ContentAppCommandDelegate::InvokeCommand send command being called with payload %s", payload.c_str()); + if (!mContentAppEndpointManager.HasValidObjectRef()) + { + return Protocols::InteractionModel::Status::Failure; + } + jstring resp = - (jstring) env->CallObjectMethod(mContentAppEndpointManager, mSendCommandMethod, static_cast(epId), + (jstring) env->CallObjectMethod(mContentAppEndpointManager.ObjectRef(), mSendCommandMethod, static_cast(epId), static_cast(clusterId), static_cast(commandId), jsonString.jniValue()); if (env->ExceptionCheck()) { diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.h b/examples/tv-app/android/java/ContentAppCommandDelegate.h index 156fa287f2ef9a..a896e55b4ce035 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.h +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.h @@ -64,13 +64,6 @@ class ContentAppCommandDelegate : public CommandHandlerInterface InitializeJNIObjects(manager); }; - ~ContentAppCommandDelegate() - { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for ContentAppEndpointManager")); - env->DeleteGlobalRef(mContentAppEndpointManager); - } - void InvokeCommand(CommandHandlerInterface::HandlerContext & handlerContext) override; Status InvokeCommand(EndpointId epId, ClusterId clusterId, CommandId commandId, std::string payload, bool & commandHandled, @@ -87,9 +80,8 @@ class ContentAppCommandDelegate : public CommandHandlerInterface JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for ContentAppEndpointManager")); - mContentAppEndpointManager = env->NewGlobalRef(manager); - VerifyOrReturn(mContentAppEndpointManager != nullptr, - ChipLogError(Zcl, "Failed to NewGlobalRef ContentAppEndpointManager")); + VerifyOrReturn(mContentAppEndpointManager.Init(manager) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mContentAppEndpointManager")); jclass ContentAppEndpointManagerClass = env->GetObjectClass(manager); VerifyOrReturn(ContentAppEndpointManagerClass != nullptr, @@ -106,8 +98,8 @@ class ContentAppCommandDelegate : public CommandHandlerInterface void FormatResponseData(CommandHandlerInterface::HandlerContext & handlerContext, const char * response); - jobject mContentAppEndpointManager = nullptr; - jmethodID mSendCommandMethod = nullptr; + chip::JniGlobalReference mContentAppEndpointManager; + jmethodID mSendCommandMethod = nullptr; }; } // namespace AppPlatform diff --git a/examples/tv-app/android/java/ContentLauncherManager.cpp b/examples/tv-app/android/java/ContentLauncherManager.cpp index aec5319a567f27..8e8a08be78f4b5 100644 --- a/examples/tv-app/android/java/ContentLauncherManager.cpp +++ b/examples/tv-app/android/java/ContentLauncherManager.cpp @@ -58,7 +58,7 @@ void ContentLauncherManager::HandleLaunchContent(CommandResponseHelperCallObjectMethod(mContentLauncherManagerObject, mLaunchContentMethod, parameterArray, + jobject resp = env->CallObjectMethod(mContentLauncherManagerObject.ObjectRef(), mLaunchContentMethod, parameterArray, static_cast(autoplay), jData.jniValue()); if (env->ExceptionCheck()) { @@ -113,7 +113,7 @@ void ContentLauncherManager::HandleLaunchUrl(CommandResponseHelperCallObjectMethod(mContentLauncherManagerObject, mLaunchUrlMethod, jContentUrl.jniValue(), + jobject resp = env->CallObjectMethod(mContentLauncherManagerObject.ObjectRef(), mLaunchUrlMethod, jContentUrl.jniValue(), jDisplayString.jniValue(), branding); if (env->ExceptionCheck()) { @@ -167,12 +167,12 @@ CHIP_ERROR ContentLauncherManager::HandleGetAcceptHeaderList(AttributeValueEncod JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ContentLauncherManager::GetAcceptHeader"); - VerifyOrExit(mContentLauncherManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mContentLauncherManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetAcceptHeaderMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); return aEncoder.EncodeList([this, env](const auto & encoder) -> CHIP_ERROR { jobjectArray acceptedHeadersArray = - (jobjectArray) env->CallObjectMethod(mContentLauncherManagerObject, mGetAcceptHeaderMethod); + (jobjectArray) env->CallObjectMethod(mContentLauncherManagerObject.ObjectRef(), mGetAcceptHeaderMethod); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentLauncherManager::GetAcceptHeader"); @@ -210,12 +210,12 @@ uint32_t ContentLauncherManager::HandleGetSupportedStreamingProtocols() JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received ContentLauncherManager::GetSupportedStreamingProtocols"); - VerifyOrExit(mContentLauncherManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mContentLauncherManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetSupportedStreamingProtocolsMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); { jlong jSupportedStreamingProtocols = - env->CallLongMethod(mContentLauncherManagerObject, mGetSupportedStreamingProtocolsMethod); + env->CallLongMethod(mContentLauncherManagerObject.ObjectRef(), mGetSupportedStreamingProtocolsMethod); supportedStreamingProtocols = (uint32_t) jSupportedStreamingProtocols; if (env->ExceptionCheck()) { @@ -241,8 +241,8 @@ void ContentLauncherManager::InitializeWithObjects(jobject managerObject) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for ContentLauncherManager")); - mContentLauncherManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mContentLauncherManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef ContentLauncherManager")); + VerifyOrReturn(mContentLauncherManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mContentLauncherManagerObject")); jclass ContentLauncherClass = env->GetObjectClass(managerObject); VerifyOrReturn(ContentLauncherClass != nullptr, ChipLogError(Zcl, "Failed to get ContentLauncherManager Java class")); diff --git a/examples/tv-app/android/java/ContentLauncherManager.h b/examples/tv-app/android/java/ContentLauncherManager.h index ac65dcaac0dc71..864d52c4fa64ca 100644 --- a/examples/tv-app/android/java/ContentLauncherManager.h +++ b/examples/tv-app/android/java/ContentLauncherManager.h @@ -22,6 +22,7 @@ #include #include #include +#include using chip::CharSpan; using chip::app::AttributeValueEncoder; @@ -50,7 +51,7 @@ class ContentLauncherManager : public ContentLauncherDelegate uint32_t GetFeatureMap(chip::EndpointId endpoint) override; private: - jobject mContentLauncherManagerObject = nullptr; + chip::JniGlobalReference mContentLauncherManagerObject; jmethodID mGetAcceptHeaderMethod = nullptr; jmethodID mGetSupportedStreamingProtocolsMethod = nullptr; jmethodID mLaunchContentMethod = nullptr; diff --git a/examples/tv-app/android/java/DeviceCallbacks.cpp b/examples/tv-app/android/java/DeviceCallbacks.cpp index ad1b40fa10bcb4..a85402a10fef7e 100644 --- a/examples/tv-app/android/java/DeviceCallbacks.cpp +++ b/examples/tv-app/android/java/DeviceCallbacks.cpp @@ -58,9 +58,9 @@ void DeviceCallbacks::InitializeWithObjects(jobject provider) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(AppServer, "Failed to GetEnvForCurrentThread for DeviceEventProvider")); - mProvider = env->NewGlobalRef(provider); - VerifyOrReturn(mProvider != nullptr, ChipLogError(AppServer, "Failed to NewGlobalRef DeviceEventProvider")); - jclass deviceEventProviderCls = env->GetObjectClass(mProvider); + VerifyOrReturn(mProvider.Init(provider) == CHIP_NO_ERROR, ChipLogError(Zcl, "Failed to init mProvider")); + + jclass deviceEventProviderCls = env->GetObjectClass(provider); VerifyOrReturn(deviceEventProviderCls != nullptr, ChipLogError(AppServer, "Failed to get KeypadInputManager Java class")); mCommissioningCompleteMethod = env->GetMethodID(deviceEventProviderCls, "onCommissioningComplete", "()V"); @@ -85,7 +85,10 @@ void DeviceCallbacks::OnCommissioningComplete(const ChipDeviceEvent * event) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for DeviceEventProvider")); - env->CallVoidMethod(mProvider, mCommissioningCompleteMethod); + + VerifyOrReturn(mProvider.HasValidObjectRef(), ChipLogError(Zcl, "mProvider is not valid")); + + env->CallVoidMethod(mProvider.ObjectRef(), mCommissioningCompleteMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in DeviceEventProvider::onCommissioningComplete"); diff --git a/examples/tv-app/android/java/DeviceCallbacks.h b/examples/tv-app/android/java/DeviceCallbacks.h index 1f0df0cd5e886a..c212a3e92149ad 100644 --- a/examples/tv-app/android/java/DeviceCallbacks.h +++ b/examples/tv-app/android/java/DeviceCallbacks.h @@ -18,6 +18,7 @@ #include "lib/support/logging/CHIPLogging.h" #include +#include class DeviceCallbacks { @@ -28,7 +29,7 @@ class DeviceCallbacks void InitializeWithObjects(jobject manager); private: - jobject mProvider = nullptr; + chip::JniGlobalReference mProvider; jmethodID mCommissioningCompleteMethod = nullptr; void OnCommissioningComplete(const chip::DeviceLayer::ChipDeviceEvent * event); }; diff --git a/examples/tv-app/android/java/JNIDACProvider.cpp b/examples/tv-app/android/java/JNIDACProvider.cpp index 3d8ea4fca5f371..dc6f6f88249fd6 100644 --- a/examples/tv-app/android/java/JNIDACProvider.cpp +++ b/examples/tv-app/android/java/JNIDACProvider.cpp @@ -34,8 +34,8 @@ JNIDACProvider::JNIDACProvider(jobject provider) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for JNIDACProvider")); - mJNIDACProviderObject = env->NewGlobalRef(provider); - VerifyOrReturn(mJNIDACProviderObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef JNIDACProvider")); + VerifyOrReturn(mJNIDACProviderObject.Init(provider) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mJNIDACProviderObject")); jclass JNIDACProviderClass = env->GetObjectClass(provider); VerifyOrReturn(JNIDACProviderClass != nullptr, ChipLogError(Zcl, "Failed to get JNIDACProvider Java class")); @@ -80,11 +80,11 @@ JNIDACProvider::JNIDACProvider(jobject provider) CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, MutableByteSpan & out_buffer) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mJNIDACProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mJNIDACProviderObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(method != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject, method); + jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject.ObjectRef(), method); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in get Method"); @@ -106,14 +106,14 @@ CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, MutableByteSpan CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, const ByteSpan & in_buffer, MutableByteSpan & out_buffer) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mJNIDACProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mJNIDACProviderObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(method != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); jbyteArray in_buffer_jbyteArray = env->NewByteArray((jsize) (in_buffer.size())); env->SetByteArrayRegion(in_buffer_jbyteArray, 0, (int) in_buffer.size(), reinterpret_cast(in_buffer.data())); - jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject, method, in_buffer_jbyteArray); + jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject.ObjectRef(), method, in_buffer_jbyteArray); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in get Method"); diff --git a/examples/tv-app/android/java/JNIDACProvider.h b/examples/tv-app/android/java/JNIDACProvider.h index 9c419367253c5f..d8d774f41f3061 100644 --- a/examples/tv-app/android/java/JNIDACProvider.h +++ b/examples/tv-app/android/java/JNIDACProvider.h @@ -19,6 +19,7 @@ #include "lib/support/logging/CHIPLogging.h" #include #include +#include class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsProvider { @@ -34,7 +35,7 @@ class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsPro private: CHIP_ERROR GetJavaByteByMethod(jmethodID method, chip::MutableByteSpan & out_buffer); CHIP_ERROR GetJavaByteByMethod(jmethodID method, const chip::ByteSpan & in_buffer, chip::MutableByteSpan & out_buffer); - jobject mJNIDACProviderObject = nullptr; + chip::JniGlobalReference mJNIDACProviderObject; jmethodID mGetCertificationDeclarationMethod = nullptr; jmethodID mGetFirmwareInformationMethod = nullptr; jmethodID mGetDeviceAttestationCertMethod = nullptr; diff --git a/examples/tv-app/android/java/KeypadInputManager.cpp b/examples/tv-app/android/java/KeypadInputManager.cpp index 2b642a825b0bef..450804a3764449 100644 --- a/examples/tv-app/android/java/KeypadInputManager.cpp +++ b/examples/tv-app/android/java/KeypadInputManager.cpp @@ -53,11 +53,11 @@ void KeypadInputManager::HandleSendKey(CommandResponseHelperExceptionClear(); - ret = env->CallIntMethod(mKeypadInputManagerObject, mSendKeyMethod, static_cast(keyCode)); + ret = env->CallIntMethod(mKeypadInputManagerObject.ObjectRef(), mSendKeyMethod, static_cast(keyCode)); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -78,8 +78,8 @@ void KeypadInputManager::InitializeWithObjects(jobject managerObject) VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for KeypadInputManager")); JniLocalReferenceScope scope(env); - mKeypadInputManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mKeypadInputManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef KeypadInputManager")); + VerifyOrReturn(mKeypadInputManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mKeypadInputManagerObject")); jclass KeypadInputManagerClass = env->GetObjectClass(managerObject); VerifyOrReturn(KeypadInputManagerClass != nullptr, ChipLogError(Zcl, "Failed to get KeypadInputManager Java class")); @@ -94,7 +94,7 @@ void KeypadInputManager::InitializeWithObjects(jobject managerObject) uint32_t KeypadInputManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/android/java/KeypadInputManager.h b/examples/tv-app/android/java/KeypadInputManager.h index 77d58a8255830b..568648eab6e557 100644 --- a/examples/tv-app/android/java/KeypadInputManager.h +++ b/examples/tv-app/android/java/KeypadInputManager.h @@ -20,6 +20,7 @@ #include #include +#include using chip::app::CommandResponseHelper; using KeypadInputDelegate = chip::app::Clusters::KeypadInput::Delegate; @@ -37,8 +38,8 @@ class KeypadInputManager : public KeypadInputDelegate uint32_t GetFeatureMap(chip::EndpointId endpoint) override; private: - jobject mKeypadInputManagerObject = nullptr; - jmethodID mSendKeyMethod = nullptr; + chip::JniGlobalReference mKeypadInputManagerObject; + jmethodID mSendKeyMethod = nullptr; // TODO: set this based upon meta data from app uint32_t mDynamicEndpointFeatureMap = 7; diff --git a/examples/tv-app/android/java/LevelManager.cpp b/examples/tv-app/android/java/LevelManager.cpp index cefb26ecfe325d..f8e3dab6aa7773 100644 --- a/examples/tv-app/android/java/LevelManager.cpp +++ b/examples/tv-app/android/java/LevelManager.cpp @@ -27,7 +27,7 @@ using namespace chip; -static constexpr size_t kLevelManagerTableSize = EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT; +static constexpr size_t kLevelManagerTableSize = MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT; namespace { @@ -46,7 +46,7 @@ void LevelManager::NewManager(jint endpoint, jobject manager) { ChipLogProgress(Zcl, "TV Android App: LevelManager::NewManager"); uint16_t ep = emberAfGetClusterServerEndpointIndex(static_cast(endpoint), app::Clusters::LevelControl::Id, - EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturn(ep < kLevelManagerTableSize, ChipLogError(Zcl, "TV Android App::Level::NewManager: endpoint %d not found", endpoint)); @@ -68,7 +68,7 @@ void LevelManager::NewManager(jint endpoint, jobject manager) LevelManager * GetLevelManager(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::LevelControl::Id, - EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); return ((ep >= kLevelManagerTableSize) ? nullptr : gLevelManagerTable[ep]); } @@ -94,8 +94,7 @@ CHIP_ERROR LevelManager::InitializeWithObjects(jobject managerObject) VerifyOrReturnLogError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); JniLocalReferenceScope scope(env); - mLevelManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturnLogError(mLevelManagerObject != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + ReturnLogErrorOnFailure(mLevelManagerObject.Init(managerObject)); jclass LevelManagerClass = env->GetObjectClass(managerObject); VerifyOrReturnLogError(LevelManagerClass != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -119,11 +118,11 @@ void LevelManager::HandleLevelChanged(uint8_t value) VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); - VerifyOrReturn(mLevelManagerObject != nullptr, ChipLogProgress(Zcl, "mLevelManagerObject null")); + VerifyOrReturn(mLevelManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mLevelManagerObject is not valid")); VerifyOrReturn(mHandleLevelChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleLevelChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mLevelManagerObject, mHandleLevelChangedMethod, static_cast(value)); + env->CallVoidMethod(mLevelManagerObject.ObjectRef(), mHandleLevelChangedMethod, static_cast(value)); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in LevelManager::HandleLevelChanged"); diff --git a/examples/tv-app/android/java/LevelManager.h b/examples/tv-app/android/java/LevelManager.h index ca8fbabe569bcf..5c696629bf4b11 100644 --- a/examples/tv-app/android/java/LevelManager.h +++ b/examples/tv-app/android/java/LevelManager.h @@ -19,6 +19,7 @@ #include #include #include +#include /** * @brief Handles interfacing between java code and C++ code for the purposes of LevelControl clusters. @@ -41,6 +42,6 @@ class LevelManager private: // init with java objects CHIP_ERROR InitializeWithObjects(jobject managerObject); - jobject mLevelManagerObject = nullptr; + chip::JniGlobalReference mLevelManagerObject; jmethodID mHandleLevelChangedMethod = nullptr; }; diff --git a/examples/tv-app/android/java/LowPowerManager.cpp b/examples/tv-app/android/java/LowPowerManager.cpp index 9b21a1ce872c31..12e234964d4c5e 100644 --- a/examples/tv-app/android/java/LowPowerManager.cpp +++ b/examples/tv-app/android/java/LowPowerManager.cpp @@ -48,8 +48,8 @@ void LowPowerManager::InitializeWithObjects(jobject managerObject) VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for LowPowerManager")); JniLocalReferenceScope scope(env); - mLowPowerManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mLowPowerManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef LowPowerManager")); + VerifyOrReturn(mLowPowerManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mLowPowerManagerObject")); jclass LowPowerManagerClass = env->GetObjectClass(managerObject); VerifyOrReturn(LowPowerManagerClass != nullptr, ChipLogError(Zcl, "Failed to get LowPowerManager Java class")); @@ -69,12 +69,12 @@ bool LowPowerManager::HandleSleep() JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received LowPowerManager::Sleep"); - VerifyOrExit(mLowPowerManagerObject != nullptr, ChipLogError(Zcl, "mLowPowerManagerObject null")); + VerifyOrExit(mLowPowerManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mLowPowerManagerObject null")); VerifyOrExit(mSleepMethod != nullptr, ChipLogError(Zcl, "mSleepMethod null")); VerifyOrExit(env != NULL, ChipLogError(Zcl, "env null")); env->ExceptionClear(); - ret = env->CallBooleanMethod(mLowPowerManagerObject, mSleepMethod); + ret = env->CallBooleanMethod(mLowPowerManagerObject.ObjectRef(), mSleepMethod); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in LowPowerManager::Sleep"); diff --git a/examples/tv-app/android/java/LowPowerManager.h b/examples/tv-app/android/java/LowPowerManager.h index df191be746b7d8..e4a674d89f7e07 100644 --- a/examples/tv-app/android/java/LowPowerManager.h +++ b/examples/tv-app/android/java/LowPowerManager.h @@ -22,6 +22,7 @@ #include #include +#include class LowPowerManager : public chip::app::Clusters::LowPower::Delegate { @@ -32,6 +33,6 @@ class LowPowerManager : public chip::app::Clusters::LowPower::Delegate bool HandleSleep() override; private: - jobject mLowPowerManagerObject = nullptr; - jmethodID mSleepMethod = nullptr; + chip::JniGlobalReference mLowPowerManagerObject; + jmethodID mSleepMethod = nullptr; }; diff --git a/examples/tv-app/android/java/MediaInputManager.cpp b/examples/tv-app/android/java/MediaInputManager.cpp index 1c183c205c6628..bbc575b6eab378 100644 --- a/examples/tv-app/android/java/MediaInputManager.cpp +++ b/examples/tv-app/android/java/MediaInputManager.cpp @@ -57,11 +57,11 @@ CHIP_ERROR MediaInputManager::HandleGetInputList(chip::app::AttributeValueEncode JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaInputManager::HandleGetInputList"); - VerifyOrExit(mMediaInputManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaInputManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetInputListMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); return aEncoder.EncodeList([this, env](const auto & encoder) -> CHIP_ERROR { - jobjectArray inputArray = (jobjectArray) env->CallObjectMethod(mMediaInputManagerObject, mGetInputListMethod); + jobjectArray inputArray = (jobjectArray) env->CallObjectMethod(mMediaInputManagerObject.ObjectRef(), mGetInputListMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaInputManager::HandleGetInputList"); @@ -128,12 +128,12 @@ uint8_t MediaInputManager::HandleGetCurrentInput() JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaInputManager::HandleGetCurrentInput"); - VerifyOrExit(mMediaInputManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaInputManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetCurrentInputMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); { - index = env->CallIntMethod(mMediaInputManagerObject, mGetCurrentInputMethod); + index = env->CallIntMethod(mMediaInputManagerObject.ObjectRef(), mGetCurrentInputMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaInputManager::HandleGetCurrentInput"); @@ -160,11 +160,11 @@ bool MediaInputManager::HandleSelectInput(const uint8_t index) JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaInputManager::HandleSelectInput %d", index); - VerifyOrExit(mMediaInputManagerObject != nullptr, ChipLogError(Zcl, "mMediaInputManagerObject null")); + VerifyOrExit(mMediaInputManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mMediaInputManagerObject is not valid")); VerifyOrExit(mSelectInputMethod != nullptr, ChipLogError(Zcl, "mSelectInputMethod null")); env->ExceptionClear(); - ret = env->CallBooleanMethod(mMediaInputManagerObject, mSelectInputMethod, static_cast(index)); + ret = env->CallBooleanMethod(mMediaInputManagerObject.ObjectRef(), mSelectInputMethod, static_cast(index)); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in MediaInputManager::HandleSelectInput"); @@ -185,11 +185,11 @@ bool MediaInputManager::HandleShowInputStatus() JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaInputManager::HandleShowInputStatus"); - VerifyOrExit(mMediaInputManagerObject != nullptr, ChipLogError(Zcl, "mMediaInputManagerObject null")); + VerifyOrExit(mMediaInputManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mMediaInputManagerObject is not valid")); VerifyOrExit(mShowInputStatusMethod != nullptr, ChipLogError(Zcl, "mShowInputStatusMethod null")); env->ExceptionClear(); - ret = env->CallBooleanMethod(mMediaInputManagerObject, mShowInputStatusMethod); + ret = env->CallBooleanMethod(mMediaInputManagerObject.ObjectRef(), mShowInputStatusMethod); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in MediaInputManager::HandleShowInputStatus"); @@ -210,11 +210,11 @@ bool MediaInputManager::HandleHideInputStatus() JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaInputManager::HandleHideInputStatus"); - VerifyOrExit(mMediaInputManagerObject != nullptr, ChipLogError(Zcl, "mMediaInputManagerObject null")); + VerifyOrExit(mMediaInputManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mMediaInputManagerObject is not valid")); VerifyOrExit(mHideInputStatusMethod != nullptr, ChipLogError(Zcl, "mHideInputStatusMethod null")); env->ExceptionClear(); - ret = env->CallBooleanMethod(mMediaInputManagerObject, mHideInputStatusMethod); + ret = env->CallBooleanMethod(mMediaInputManagerObject.ObjectRef(), mHideInputStatusMethod); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in MediaInputManager::HandleHideInputStatus"); @@ -236,14 +236,14 @@ bool MediaInputManager::HandleRenameInput(const uint8_t index, const chip::CharS JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaInputManager::HandleRenameInput %d to %s", index, name.data()); - VerifyOrExit(mMediaInputManagerObject != nullptr, ChipLogError(Zcl, "mMediaInputManagerObject null")); + VerifyOrExit(mMediaInputManagerObject.HasValidObjectRef(), ChipLogError(Zcl, "mMediaInputManagerObject is not valid")); VerifyOrExit(mRenameInputMethod != nullptr, ChipLogError(Zcl, "mHideInputStatusMethod null")); { UtfString jniInputname(env, inputname.data()); env->ExceptionClear(); - ret = - env->CallBooleanMethod(mMediaInputManagerObject, mRenameInputMethod, static_cast(index), jniInputname.jniValue()); + ret = env->CallBooleanMethod(mMediaInputManagerObject.ObjectRef(), mRenameInputMethod, static_cast(index), + jniInputname.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in MediaInputManager::HandleRenameInput"); @@ -262,8 +262,8 @@ void MediaInputManager::InitializeWithObjects(jobject managerObject) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for MediaInputManager")); - mMediaInputManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mMediaInputManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef MediaInputManager")); + VerifyOrReturn(mMediaInputManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mMediaInputManagerObject")); jclass MediaInputManagerClass = env->GetObjectClass(managerObject); VerifyOrReturn(MediaInputManagerClass != nullptr, ChipLogError(Zcl, "Failed to get MediaInputManager Java class")); diff --git a/examples/tv-app/android/java/MediaInputManager.h b/examples/tv-app/android/java/MediaInputManager.h index e93e956c249e07..fdc014ab1b331e 100644 --- a/examples/tv-app/android/java/MediaInputManager.h +++ b/examples/tv-app/android/java/MediaInputManager.h @@ -21,6 +21,7 @@ #include #include #include +#include class MediaInputManager : public chip::app::Clusters::MediaInput::Delegate { @@ -36,7 +37,7 @@ class MediaInputManager : public chip::app::Clusters::MediaInput::Delegate bool HandleRenameInput(const uint8_t index, const chip::CharSpan & name) override; private: - jobject mMediaInputManagerObject = nullptr; + chip::JniGlobalReference mMediaInputManagerObject; jmethodID mGetInputListMethod = nullptr; jmethodID mGetCurrentInputMethod = nullptr; jmethodID mSelectInputMethod = nullptr; diff --git a/examples/tv-app/android/java/MediaPlaybackManager.cpp b/examples/tv-app/android/java/MediaPlaybackManager.cpp index 52666e8da9bfda..c72a3135c4b222 100644 --- a/examples/tv-app/android/java/MediaPlaybackManager.cpp +++ b/examples/tv-app/android/java/MediaPlaybackManager.cpp @@ -108,11 +108,11 @@ CHIP_ERROR MediaPlaybackManager::HandleGetActiveTrack(bool audio, AttributeValue JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "MediaPlaybackManager::HandleGetActiveAudioTrack"); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetActiveTrackMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); env->ExceptionClear(); - trackObj = env->CallObjectMethod(mMediaPlaybackManagerObject, mGetActiveTrackMethod, static_cast(audio)); + trackObj = env->CallObjectMethod(mMediaPlaybackManagerObject.ObjectRef(), mGetActiveTrackMethod, static_cast(audio)); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaPlaybackManager::HandleGetActiveAudioTrack"); @@ -176,12 +176,12 @@ CHIP_ERROR MediaPlaybackManager::HandleGetAvailableTracks(bool audio, AttributeV JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "MediaPlaybackManager::HandleGetAvailableAudioTracks"); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetAvailableTracksMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); return aEncoder.EncodeList([this, env, audio](const auto & encoder) -> CHIP_ERROR { - jobjectArray trackList = (jobjectArray) env->CallObjectMethod(mMediaPlaybackManagerObject, mGetAvailableTracksMethod, - static_cast(audio)); + jobjectArray trackList = (jobjectArray) env->CallObjectMethod(mMediaPlaybackManagerObject.ObjectRef(), + mGetAvailableTracksMethod, static_cast(audio)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in MediaPlaybackManager::HandleGetAvailableAudioTracks"); @@ -326,12 +326,13 @@ bool MediaPlaybackManager::HandleActivateTrack(bool audio, const chip::CharSpan JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "MediaPlaybackManager::HandleActivateAudioTrack"); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mActivateTrackMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); { UtfString jniid(env, id.c_str()); env->ExceptionClear(); - ret = env->CallIntMethod(mMediaPlaybackManagerObject, mActivateTrackMethod, static_cast(audio), jniid.jniValue()); + ret = env->CallIntMethod(mMediaPlaybackManagerObject.ObjectRef(), mActivateTrackMethod, static_cast(audio), + jniid.jniValue()); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaPlaybackManager::HandleActivateTrack %s", id.c_str()); @@ -357,11 +358,11 @@ bool MediaPlaybackManager::HandleDeactivateTextTrack() JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "MediaPlaybackManager::HandleDeactivateTextTrack"); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mDeactivateTextTrackMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); env->ExceptionClear(); - ret = env->CallIntMethod(mMediaPlaybackManagerObject, mDeactivateTextTrackMethod); + ret = env->CallIntMethod(mMediaPlaybackManagerObject.ObjectRef(), mDeactivateTextTrackMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaPlaybackManager::HandleDeactivateTextTrack"); @@ -377,8 +378,8 @@ void MediaPlaybackManager::InitializeWithObjects(jobject managerObject) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for MediaPlaybackManager")); - mMediaPlaybackManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mMediaPlaybackManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef MediaPlaybackManager")); + VerifyOrReturn(mMediaPlaybackManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mMediaPlaybackManagerObject")); jclass mMediaPlaybackManagerClass = env->GetObjectClass(managerObject); VerifyOrReturn(mMediaPlaybackManagerClass != nullptr, ChipLogError(Zcl, "Failed to get MediaPlaybackManager Java class")); @@ -446,10 +447,11 @@ uint64_t MediaPlaybackManager::HandleMediaRequestGetAttribute(MediaPlaybackReque JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaPlaybackManager::HandleMediaRequestGetAttribute:%d", attribute); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetAttributeMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - jAttributeValue = env->CallLongMethod(mMediaPlaybackManagerObject, mGetAttributeMethod, static_cast(attribute)); + jAttributeValue = + env->CallLongMethod(mMediaPlaybackManagerObject.ObjectRef(), mGetAttributeMethod, static_cast(attribute)); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaPlaybackManager::GetAttribute"); @@ -486,10 +488,11 @@ long MediaPlaybackManager::HandleMediaRequestGetLongAttribute(MediaPlaybackReque JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "Received MediaPlaybackManager::HandleMediaRequestGetLongAttribute:%d", attribute); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetAttributeMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - jAttributeValue = env->CallLongMethod(mMediaPlaybackManagerObject, mGetAttributeMethod, static_cast(attribute)); + jAttributeValue = + env->CallLongMethod(mMediaPlaybackManagerObject.ObjectRef(), mGetAttributeMethod, static_cast(attribute)); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaPlaybackManager::GetAttribute"); @@ -523,11 +526,11 @@ Commands::PlaybackResponse::Type MediaPlaybackManager::HandleMediaRequest(MediaP ChipLogProgress(Zcl, "MediaPlaybackManager::Request %d-%ld", mediaPlaybackRequest, static_cast(deltaPositionMilliseconds)); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mRequestMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); env->ExceptionClear(); - ret = env->CallIntMethod(mMediaPlaybackManagerObject, mRequestMethod, static_cast(mediaPlaybackRequest), + ret = env->CallIntMethod(mMediaPlaybackManagerObject.ObjectRef(), mRequestMethod, static_cast(mediaPlaybackRequest), static_cast(deltaPositionMilliseconds)); if (env->ExceptionCheck()) { @@ -561,11 +564,11 @@ CHIP_ERROR MediaPlaybackManager::HandleGetSampledPosition(AttributeValueEncoder JniLocalReferenceScope scope(env); ChipLogProgress(Zcl, "MediaPlaybackManager::HandleGetSampledPosition"); - VerifyOrExit(mMediaPlaybackManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mMediaPlaybackManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetPositionMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); env->ExceptionClear(); - positionObj = env->CallObjectMethod(mMediaPlaybackManagerObject, mGetPositionMethod); + positionObj = env->CallObjectMethod(mMediaPlaybackManagerObject.ObjectRef(), mGetPositionMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in MediaPlaybackManager::HandleGetSampledPosition"); @@ -593,7 +596,7 @@ CHIP_ERROR MediaPlaybackManager::HandleGetSampledPosition(AttributeValueEncoder uint32_t MediaPlaybackManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/android/java/MediaPlaybackManager.h b/examples/tv-app/android/java/MediaPlaybackManager.h index 914462fea57fb2..0414a3087be0cb 100644 --- a/examples/tv-app/android/java/MediaPlaybackManager.h +++ b/examples/tv-app/android/java/MediaPlaybackManager.h @@ -21,6 +21,7 @@ #include #include #include +#include #include enum MediaPlaybackRequestAttribute : uint8_t @@ -105,7 +106,7 @@ class MediaPlaybackManager : public MediaPlaybackDelegate uint32_t GetFeatureMap(chip::EndpointId endpoint) override; private: - jobject mMediaPlaybackManagerObject = nullptr; + chip::JniGlobalReference mMediaPlaybackManagerObject; jmethodID mRequestMethod = nullptr; jmethodID mGetAttributeMethod = nullptr; jmethodID mGetPositionMethod = nullptr; diff --git a/examples/tv-app/android/java/MyUserPrompter-JNI.cpp b/examples/tv-app/android/java/MyUserPrompter-JNI.cpp index 3d29126e5b838a..d2c83b28a1ce8f 100644 --- a/examples/tv-app/android/java/MyUserPrompter-JNI.cpp +++ b/examples/tv-app/android/java/MyUserPrompter-JNI.cpp @@ -29,8 +29,8 @@ JNIMyUserPrompter::JNIMyUserPrompter(jobject provider) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for JNIMyUserPrompter")); - mJNIMyUserPrompterObject = env->NewGlobalRef(provider); - VerifyOrReturn(mJNIMyUserPrompterObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef JNIMyUserPrompter")); + VerifyOrReturn(mJNIMyUserPrompterObject.Init(provider) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init mJNIMyUserPrompterObject")); jclass JNIMyUserPrompterClass = env->GetObjectClass(provider); VerifyOrReturn(JNIMyUserPrompterClass != nullptr, ChipLogError(Zcl, "Failed to get JNIMyUserPrompter Java class")); @@ -82,15 +82,15 @@ void JNIMyUserPrompter::PromptForCommissionOKPermission(uint16_t vendorId, uint1 JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); std::string stringCommissioneeName(commissioneeName); - VerifyOrExit(mJNIMyUserPrompterObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mJNIMyUserPrompterObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mPromptForCommissionOKPermissionMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV); { UtfString jniCommissioneeName(env, stringCommissioneeName.data()); env->ExceptionClear(); - env->CallVoidMethod(mJNIMyUserPrompterObject, mPromptForCommissionOKPermissionMethod, static_cast(vendorId), - static_cast(productId), jniCommissioneeName.jniValue()); + env->CallVoidMethod(mJNIMyUserPrompterObject.ObjectRef(), mPromptForCommissionOKPermissionMethod, + static_cast(vendorId), static_cast(productId), jniCommissioneeName.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in PromptForCommissionOKPermission"); @@ -123,14 +123,14 @@ void JNIMyUserPrompter::PromptForCommissionPasscode(uint16_t vendorId, uint16_t JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); std::string stringCommissioneeName(commissioneeName); - VerifyOrExit(mJNIMyUserPrompterObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mJNIMyUserPrompterObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mPromptForCommissionPincodeMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV); { UtfString jniCommissioneeName(env, stringCommissioneeName.data()); env->ExceptionClear(); - env->CallVoidMethod(mJNIMyUserPrompterObject, mPromptForCommissionPincodeMethod, static_cast(vendorId), + env->CallVoidMethod(mJNIMyUserPrompterObject.ObjectRef(), mPromptForCommissionPincodeMethod, static_cast(vendorId), static_cast(productId), jniCommissioneeName.jniValue()); if (env->ExceptionCheck()) { @@ -202,14 +202,14 @@ void JNIMyUserPrompter::PromptCommissioningSucceeded(uint16_t vendorId, uint16_t JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); std::string stringCommissioneeName(commissioneeName); - VerifyOrExit(mJNIMyUserPrompterObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mJNIMyUserPrompterObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mPromptCommissioningSucceededMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV); { UtfString jniCommissioneeName(env, stringCommissioneeName.data()); env->ExceptionClear(); - env->CallVoidMethod(mJNIMyUserPrompterObject, mPromptCommissioningSucceededMethod, static_cast(vendorId), + env->CallVoidMethod(mJNIMyUserPrompterObject.ObjectRef(), mPromptCommissioningSucceededMethod, static_cast(vendorId), static_cast(productId), jniCommissioneeName.jniValue()); if (env->ExceptionCheck()) @@ -238,7 +238,7 @@ void JNIMyUserPrompter::PromptCommissioningFailed(const char * commissioneeName, JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); std::string stringCommissioneeName(commissioneeName); - VerifyOrExit(mJNIMyUserPrompterObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mJNIMyUserPrompterObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mPromptCommissioningFailedMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV); @@ -247,7 +247,7 @@ void JNIMyUserPrompter::PromptCommissioningFailed(const char * commissioneeName, UtfString jniCommissioneeName(env, stringCommissioneeName.data()); UtfString jniCommissioneeError(env, stringError.data()); env->ExceptionClear(); - env->CallVoidMethod(mJNIMyUserPrompterObject, mPromptCommissioningFailedMethod, jniCommissioneeName.jniValue(), + env->CallVoidMethod(mJNIMyUserPrompterObject.ObjectRef(), mPromptCommissioningFailedMethod, jniCommissioneeName.jniValue(), jniCommissioneeError.jniValue()); if (env->ExceptionCheck()) diff --git a/examples/tv-app/android/java/MyUserPrompter-JNI.h b/examples/tv-app/android/java/MyUserPrompter-JNI.h index f4d93ad49b10e1..03fb88d2fd7887 100644 --- a/examples/tv-app/android/java/MyUserPrompter-JNI.h +++ b/examples/tv-app/android/java/MyUserPrompter-JNI.h @@ -19,6 +19,7 @@ #include "CommissionerMain.h" #include "lib/support/logging/CHIPLogging.h" #include +#include class JNIMyUserPrompter : public UserPrompter { @@ -37,7 +38,7 @@ class JNIMyUserPrompter : public UserPrompter void PromptCommissioningFailed(const char * commissioneeName, CHIP_ERROR error) override; private: - jobject mJNIMyUserPrompterObject = nullptr; + chip::JniGlobalReference mJNIMyUserPrompterObject; jmethodID mPromptForCommissionOKPermissionMethod = nullptr; jmethodID mPromptForCommissionPincodeMethod = nullptr; jmethodID mPromptCommissioningSucceededMethod = nullptr; diff --git a/examples/tv-app/android/java/OnOffManager.cpp b/examples/tv-app/android/java/OnOffManager.cpp index bf6796d4cb9542..c05c20700eabd0 100644 --- a/examples/tv-app/android/java/OnOffManager.cpp +++ b/examples/tv-app/android/java/OnOffManager.cpp @@ -27,7 +27,7 @@ using namespace chip; -static constexpr size_t kOnffManagerTableSize = EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT; +static constexpr size_t kOnffManagerTableSize = MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT; namespace { @@ -46,7 +46,7 @@ void OnOffManager::NewManager(jint endpoint, jobject manager) { ChipLogProgress(Zcl, "TV Android App: OnOffManager::NewManager"); uint16_t ep = emberAfGetClusterServerEndpointIndex(static_cast(endpoint), app::Clusters::OnOff::Id, - EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturn(ep < kOnffManagerTableSize, ChipLogError(Zcl, "TV Android App::OnOff::NewManager: endpoint %d not found", endpoint)); @@ -68,7 +68,7 @@ void OnOffManager::NewManager(jint endpoint, jobject manager) OnOffManager * GetOnOffManager(EndpointId endpoint) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::OnOff::Id, EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::OnOff::Id, MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kOnffManagerTableSize ? nullptr : gOnOffManagerTable[ep]); } @@ -94,8 +94,7 @@ CHIP_ERROR OnOffManager::InitializeWithObjects(jobject managerObject) VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NO_ENV, ChipLogError(Zcl, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); - mOnOffManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturnLogError(mOnOffManagerObject != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + ReturnLogErrorOnFailure(mOnOffManagerObject.Init(managerObject)); jclass OnOffManagerClass = env->GetObjectClass(managerObject); VerifyOrReturnLogError(OnOffManagerClass != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -119,11 +118,11 @@ void OnOffManager::HandleOnOffChanged(bool value) VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); - VerifyOrReturn(mOnOffManagerObject != nullptr, ChipLogProgress(Zcl, "mOnOffManagerObject null")); + VerifyOrReturn(mOnOffManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mOnOffManagerObject null")); VerifyOrReturn(mHandleOnOffChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleOnOffChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mOnOffManagerObject, mHandleOnOffChangedMethod, static_cast(value)); + env->CallVoidMethod(mOnOffManagerObject.ObjectRef(), mHandleOnOffChangedMethod, static_cast(value)); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnOffManager::HandleOnOffChanged"); diff --git a/examples/tv-app/android/java/OnOffManager.h b/examples/tv-app/android/java/OnOffManager.h index 02420b8fd14dd3..7a535ebe40b576 100644 --- a/examples/tv-app/android/java/OnOffManager.h +++ b/examples/tv-app/android/java/OnOffManager.h @@ -18,6 +18,7 @@ #include #include +#include /** * @brief Handles interfacing between java code and C++ code for the purposes of On/Off clusters. @@ -40,6 +41,6 @@ class OnOffManager private: // init with java objects CHIP_ERROR InitializeWithObjects(jobject managerObject); - jobject mOnOffManagerObject = nullptr; + chip::JniGlobalReference mOnOffManagerObject; jmethodID mHandleOnOffChangedMethod = nullptr; }; diff --git a/examples/tv-app/android/java/TVApp-JNI.cpp b/examples/tv-app/android/java/TVApp-JNI.cpp index f8afdfeb9c3b5f..82fae67ec1dd39 100644 --- a/examples/tv-app/android/java/TVApp-JNI.cpp +++ b/examples/tv-app/android/java/TVApp-JNI.cpp @@ -58,10 +58,9 @@ void TvAppJNI::InitializeWithObjects(jobject app) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for TvAppJNI")); - mTvAppObject = env->NewGlobalRef(app); - VerifyOrReturn(mTvAppObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef TvAppJNI")); + VerifyOrReturn(mTvAppObject.Init(app) == CHIP_NO_ERROR, ChipLogError(Zcl, "Failed to init mTvAppObject")); - jclass managerClass = env->GetObjectClass(mTvAppObject); + jclass managerClass = env->GetObjectClass(app); VerifyOrReturn(managerClass != nullptr, ChipLogError(Zcl, "Failed to get TvAppJNI Java class")); mPostClusterInitMethod = env->GetMethodID(managerClass, "postClusterInit", "(JI)V"); @@ -76,10 +75,11 @@ void TvAppJNI::PostClusterInit(int clusterId, int endpoint) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for TvAppJNI::PostClusterInit")); - VerifyOrReturn(mTvAppObject != nullptr, ChipLogError(Zcl, "TvAppJNI::mTvAppObject null")); + VerifyOrReturn(mTvAppObject.HasValidObjectRef(), ChipLogError(Zcl, "TvAppJNI::mTvAppObject is not valid")); VerifyOrReturn(mPostClusterInitMethod != nullptr, ChipLogError(Zcl, "TvAppJNI::mPostClusterInitMethod null")); - env->CallVoidMethod(mTvAppObject, mPostClusterInitMethod, static_cast(clusterId), static_cast(endpoint)); + env->CallVoidMethod(mTvAppObject.ObjectRef(), mPostClusterInitMethod, static_cast(clusterId), + static_cast(endpoint)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Failed to call TvAppJNI 'postClusterInit' method"); diff --git a/examples/tv-app/android/java/TvApp-JNI.h b/examples/tv-app/android/java/TvApp-JNI.h index 4f710299a7be21..96f2b0ec0cb7e5 100644 --- a/examples/tv-app/android/java/TvApp-JNI.h +++ b/examples/tv-app/android/java/TvApp-JNI.h @@ -20,6 +20,7 @@ #include "MyUserPrompter-JNI.h" #include +#include class TvAppJNI { @@ -32,7 +33,7 @@ class TvAppJNI friend TvAppJNI & TvAppJNIMgr(); static TvAppJNI sInstance; - jobject mTvAppObject = nullptr; + chip::JniGlobalReference mTvAppObject; jmethodID mPostClusterInitMethod = nullptr; }; diff --git a/examples/tv-app/android/java/WakeOnLanManager.cpp b/examples/tv-app/android/java/WakeOnLanManager.cpp index 7c1a08fd37877a..5a3093aca53332 100644 --- a/examples/tv-app/android/java/WakeOnLanManager.cpp +++ b/examples/tv-app/android/java/WakeOnLanManager.cpp @@ -59,11 +59,11 @@ CHIP_ERROR WakeOnLanManager::HandleGetMacAddress(chip::app::AttributeValueEncode chip::CharSpan macValue; ChipLogProgress(Zcl, "Received WakeOnLanManager::HandleGetMacAddress"); - VerifyOrExit(mWakeOnLanManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mWakeOnLanManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetMacMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); env->ExceptionClear(); - javaMac = env->CallObjectMethod(mWakeOnLanManagerObject, mGetMacMethod); + javaMac = env->CallObjectMethod(mWakeOnLanManagerObject.ObjectRef(), mGetMacMethod); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in WakeOnLanManager::getMac"); @@ -89,8 +89,8 @@ void WakeOnLanManager::InitializeWithObjects(jobject managerObject) VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); - mWakeOnLanManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturn(mWakeOnLanManagerObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef WakeOnLanManager")); + VerifyOrReturn(mWakeOnLanManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to init WakeOnLanManager")); jclass WakeOnLanManagerClass = env->GetObjectClass(managerObject); VerifyOrReturn(WakeOnLanManagerClass != nullptr, ChipLogError(Zcl, "Failed to get WakeOnLanManager Java class")); diff --git a/examples/tv-app/android/java/WakeOnLanManager.h b/examples/tv-app/android/java/WakeOnLanManager.h index f837572c377168..07aebe3dc488b5 100644 --- a/examples/tv-app/android/java/WakeOnLanManager.h +++ b/examples/tv-app/android/java/WakeOnLanManager.h @@ -20,6 +20,7 @@ #include #include +#include class WakeOnLanManager : public chip::app::Clusters::WakeOnLan::Delegate { @@ -30,6 +31,6 @@ class WakeOnLanManager : public chip::app::Clusters::WakeOnLan::Delegate CHIP_ERROR HandleGetMacAddress(chip::app::AttributeValueEncoder & aEncoder) override; private: - jobject mWakeOnLanManagerObject = nullptr; - jmethodID mGetMacMethod = nullptr; + chip::JniGlobalReference mWakeOnLanManagerObject; + jmethodID mGetMacMethod = nullptr; }; diff --git a/examples/tv-app/tv-common/clusters/channel/ChannelManager.cpp b/examples/tv-app/tv-common/clusters/channel/ChannelManager.cpp index 7599bc48ef5d29..6fc558da5d3759 100644 --- a/examples/tv-app/tv-common/clusters/channel/ChannelManager.cpp +++ b/examples/tv-app/tv-common/clusters/channel/ChannelManager.cpp @@ -329,7 +329,7 @@ bool ChannelManager::HandleCancelRecordProgram(const chip::CharSpan & programIde uint32_t ChannelManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/tv-common/clusters/content-control/ContentController.cpp b/examples/tv-app/tv-common/clusters/content-control/ContentController.cpp index 7ebb2ee4a45954..3d622e4a5b9383 100644 --- a/examples/tv-app/tv-common/clusters/content-control/ContentController.cpp +++ b/examples/tv-app/tv-common/clusters/content-control/ContentController.cpp @@ -94,7 +94,7 @@ void ContentControlManager::HandleSetScheduledContentRatingThreshold(chip::CharS uint32_t ContentControlManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/tv-common/clusters/content-launcher/ContentLauncherManager.cpp b/examples/tv-app/tv-common/clusters/content-launcher/ContentLauncherManager.cpp index ff2da45d7db461..013831ec5a6055 100644 --- a/examples/tv-app/tv-common/clusters/content-launcher/ContentLauncherManager.cpp +++ b/examples/tv-app/tv-common/clusters/content-launcher/ContentLauncherManager.cpp @@ -196,7 +196,7 @@ uint32_t ContentLauncherManager::HandleGetSupportedStreamingProtocols() uint32_t ContentLauncherManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/tv-common/clusters/keypad-input/KeypadInputManager.cpp b/examples/tv-app/tv-common/clusters/keypad-input/KeypadInputManager.cpp index 17c372accea7a9..5817f9a6bb1654 100644 --- a/examples/tv-app/tv-common/clusters/keypad-input/KeypadInputManager.cpp +++ b/examples/tv-app/tv-common/clusters/keypad-input/KeypadInputManager.cpp @@ -99,7 +99,7 @@ void KeypadInputManager::HandleSendKey(CommandResponseHelper= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-app/tv-common/clusters/media-playback/MediaPlaybackManager.cpp b/examples/tv-app/tv-common/clusters/media-playback/MediaPlaybackManager.cpp index fe220ce612e7d5..0bb3f1366d7e3a 100644 --- a/examples/tv-app/tv-common/clusters/media-playback/MediaPlaybackManager.cpp +++ b/examples/tv-app/tv-common/clusters/media-playback/MediaPlaybackManager.cpp @@ -317,7 +317,7 @@ bool MediaPlaybackManager::HandleDeactivateTextTrack() uint32_t MediaPlaybackManager::GetFeatureMap(chip::EndpointId endpoint) { - if (endpoint >= EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) + if (endpoint >= MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT) { return mDynamicEndpointFeatureMap; } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp index 3d8ea4fca5f371..363a629db2c9e5 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp @@ -34,9 +34,8 @@ JNIDACProvider::JNIDACProvider(jobject provider) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for JNIDACProvider")); - mJNIDACProviderObject = env->NewGlobalRef(provider); - VerifyOrReturn(mJNIDACProviderObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef JNIDACProvider")); - + VerifyOrReturn(mJNIDACProviderObject.Init(provider) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to Init mJNIDACProviderObject")); jclass JNIDACProviderClass = env->GetObjectClass(provider); VerifyOrReturn(JNIDACProviderClass != nullptr, ChipLogError(Zcl, "Failed to get JNIDACProvider Java class")); @@ -80,11 +79,11 @@ JNIDACProvider::JNIDACProvider(jobject provider) CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, MutableByteSpan & out_buffer) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mJNIDACProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mJNIDACProviderObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(method != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject, method); + jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject.ObjectRef(), method); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in get Method"); @@ -106,14 +105,14 @@ CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, MutableByteSpan CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, const ByteSpan & in_buffer, MutableByteSpan & out_buffer) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mJNIDACProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mJNIDACProviderObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(method != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); jbyteArray in_buffer_jbyteArray = env->NewByteArray((jsize) (in_buffer.size())); env->SetByteArrayRegion(in_buffer_jbyteArray, 0, (int) in_buffer.size(), reinterpret_cast(in_buffer.data())); - jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject, method, in_buffer_jbyteArray); + jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject.ObjectRef(), method, in_buffer_jbyteArray); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in get Method"); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h index 9c419367253c5f..d8d774f41f3061 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.h @@ -19,6 +19,7 @@ #include "lib/support/logging/CHIPLogging.h" #include #include +#include class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsProvider { @@ -34,7 +35,7 @@ class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsPro private: CHIP_ERROR GetJavaByteByMethod(jmethodID method, chip::MutableByteSpan & out_buffer); CHIP_ERROR GetJavaByteByMethod(jmethodID method, const chip::ByteSpan & in_buffer, chip::MutableByteSpan & out_buffer); - jobject mJNIDACProviderObject = nullptr; + chip::JniGlobalReference mJNIDACProviderObject; jmethodID mGetCertificationDeclarationMethod = nullptr; jmethodID mGetFirmwareInformationMethod = nullptr; jmethodID mGetDeviceAttestationCertMethod = nullptr; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp index 30c1e1d233c2cb..f39dc4b04f2d30 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp @@ -25,10 +25,9 @@ CHIP_ERROR CallbackBaseJNI::SetUp(JNIEnv * env, jobject inHandler) ChipLogProgress(AppServer, "CallbackBaseJNI::SetUp called"); CHIP_ERROR err = CHIP_NO_ERROR; - mObject = env->NewGlobalRef(inHandler); - VerifyOrExit(mObject != nullptr, ChipLogError(AppServer, "Failed to NewGlobalRef for handler object")); + VerifyOrExit(mObject.Init(inHandler) == CHIP_NO_ERROR, ChipLogError(AppServer, "Failed to Init mObject")); - mClazz = env->GetObjectClass(mObject); + mClazz = env->GetObjectClass(mObject.ObjectRef()); VerifyOrExit(mClazz != nullptr, ChipLogError(AppServer, "Failed to get handler Java class")); mSuperClazz = env->GetSuperclass(mClazz); @@ -60,9 +59,9 @@ void FailureHandlerJNI::Handle(CHIP_ERROR callbackErr) chip::DeviceLayer::StackUnlock unlock; CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - env->CallVoidMethod(mObject, mMethod, static_cast(callbackErr.AsInteger()), jniCallbackErrString.jniValue()); + env->CallVoidMethod(mObject.ObjectRef(), mMethod, static_cast(callbackErr.AsInteger()), jniCallbackErrString.jniValue()); exit: if (err != CHIP_NO_ERROR) { @@ -78,10 +77,10 @@ void SubscriptionEstablishedHandlerJNI::Handle() chip::DeviceLayer::StackUnlock unlock; CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - env->CallVoidMethod(mObject, mMethod); + env->CallVoidMethod(mObject.ObjectRef(), mMethod); exit: if (err != CHIP_NO_ERROR) { diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h index c05eef016f32b3..152dac59737532 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h @@ -37,7 +37,7 @@ class CallbackBaseJNI CHIP_ERROR SetUp(JNIEnv * env, jobject inHandler); protected: - jobject mObject = nullptr; + chip::JniGlobalReference mObject; jclass mClazz = nullptr; jclass mSuperClazz = nullptr; jmethodID mMethod = nullptr; @@ -89,9 +89,9 @@ class SuccessHandlerJNI : public CallbackBaseJNI chip::DeviceLayer::StackUnlock unlock; CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(mObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); - env->CallVoidMethod(mObject, mMethod, jResponseData); + env->CallVoidMethod(mObject.ObjectRef(), mMethod, jResponseData); exit: if (err != CHIP_NO_ERROR) { diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp index 5d531e0164e4db..5838d4039ae6a3 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/core/CastingPlayerDiscovery-JNI.cpp @@ -52,9 +52,9 @@ class DiscoveryDelegateImpl : public DiscoveryDelegate void operator=(const DiscoveryDelegateImpl &) = delete; public: - jobject castingPlayerChangeListenerJavaObject = nullptr; - jmethodID onAddedCallbackJavaMethodID = nullptr; - jmethodID onChangedCallbackJavaMethodID = nullptr; + JniGlobalReference castingPlayerChangeListenerJavaObject; + jmethodID onAddedCallbackJavaMethodID = nullptr; + jmethodID onChangedCallbackJavaMethodID = nullptr; // jmethodID onRemovedCallbackJavaMethodID = nullptr; static DiscoveryDelegateImpl * GetInstance() @@ -72,7 +72,7 @@ class DiscoveryDelegateImpl : public DiscoveryDelegate "CastingPlayerDiscovery-JNI::DiscoveryDelegateImpl::HandleOnAdded() called with CastingPlayer, ID: %s", player->GetId()); - VerifyOrReturn(castingPlayerChangeListenerJavaObject != nullptr, + VerifyOrReturn(castingPlayerChangeListenerJavaObject.HasValidObjectRef(), ChipLogError(AppServer, "CastingPlayerDiscovery-JNI::DiscoveryDelegateImpl::HandleOnAdded() Warning: Not set, " "CastingPlayerChangeListener == nullptr")); @@ -89,7 +89,8 @@ class DiscoveryDelegateImpl : public DiscoveryDelegate JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); chip::DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(castingPlayerChangeListenerJavaObject, onAddedCallbackJavaMethodID, matterCastingPlayerJavaObject); + env->CallVoidMethod(castingPlayerChangeListenerJavaObject.ObjectRef(), onAddedCallbackJavaMethodID, + matterCastingPlayerJavaObject); } void HandleOnUpdated(matter::casting::memory::Strong player) override @@ -98,7 +99,7 @@ class DiscoveryDelegateImpl : public DiscoveryDelegate "CastingPlayerDiscovery-JNI DiscoveryDelegateImpl::HandleOnUpdated() called with CastingPlayer, ID: %s", player->GetId()); - VerifyOrReturn(castingPlayerChangeListenerJavaObject != nullptr, + VerifyOrReturn(castingPlayerChangeListenerJavaObject.HasValidObjectRef(), ChipLogError(AppServer, "CastingPlayerDiscovery-JNI::DiscoveryDelegateImpl::HandleOnUpdated() Warning: Not set, " "CastingPlayerChangeListener == nullptr")); @@ -115,7 +116,8 @@ class DiscoveryDelegateImpl : public DiscoveryDelegate JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); chip::DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(castingPlayerChangeListenerJavaObject, onChangedCallbackJavaMethodID, matterCastingPlayerJavaObject); + env->CallVoidMethod(castingPlayerChangeListenerJavaObject.ObjectRef(), onChangedCallbackJavaMethodID, + matterCastingPlayerJavaObject); } // TODO: In following PRs. Implement HandleOnRemoved after implemented in tv-casting-commom CastingPlayerDiscovery.h/cpp @@ -186,7 +188,7 @@ JNI_METHOD(jobject, addCastingPlayerChangeListener)(JNIEnv * env, jobject, jobje ChipLogProgress(AppServer, "CastingPlayerDiscovery-JNI::addCastingPlayerChangeListener() called"); VerifyOrReturnValue(castingPlayerChangeListenerJavaObject != nullptr, support::createJMatterError(CHIP_ERROR_INCORRECT_STATE)); - if (DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject != nullptr) + if (DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject.HasValidObjectRef()) { ChipLogError(AppServer, "CastingPlayerDiscovery-JNI::addCastingPlayerChangeListener() Warning: Call removeCastingPlayerChangeListener " @@ -209,8 +211,13 @@ JNI_METHOD(jobject, addCastingPlayerChangeListener)(JNIEnv * env, jobject, jobje // support::createJMatterError(CHIP_ERROR_INCORRECT_STATE)); // Set Java callbacks in the DiscoveryDelegateImpl Singleton - DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject = - env->NewGlobalRef(castingPlayerChangeListenerJavaObject); + CHIP_ERROR err = + DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject.Init(castingPlayerChangeListenerJavaObject); + if (err != CHIP_NO_ERROR) + { + return support::createJMatterError(err); + } + DiscoveryDelegateImpl::GetInstance()->onAddedCallbackJavaMethodID = onAddedJavaMethodID; DiscoveryDelegateImpl::GetInstance()->onChangedCallbackJavaMethodID = onChangedJavaMethodID; // DiscoveryDelegateImpl::GetInstance()->onRemovedCallbackJavaMethodID = onRemovedJavaMethodID; @@ -224,15 +231,13 @@ JNI_METHOD(jobject, removeCastingPlayerChangeListener)(JNIEnv * env, jobject, jo ChipLogProgress(AppServer, "CastingPlayerDiscovery-JNI::removeCastingPlayerChangeListener() called"); // Check if the passed object is the same as the one added in addCastingPlayerChangeListener() JNI method - jboolean isSameObject = env->IsSameObject(castingPlayerChangeListenerJavaObject, - DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject); + jboolean isSameObject = + env->IsSameObject(castingPlayerChangeListenerJavaObject, + DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject.ObjectRef()); if ((bool) isSameObject) { - // Delete the global reference to the Java object - env->DeleteGlobalRef(DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject); - // Remove the Java callbacks in the DiscoveryDelegateImpl Singleton - DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject = nullptr; + DiscoveryDelegateImpl::GetInstance()->castingPlayerChangeListenerJavaObject.Reset(); // No explicit cleanup required DiscoveryDelegateImpl::GetInstance()->onAddedCallbackJavaMethodID = nullptr; DiscoveryDelegateImpl::GetInstance()->onChangedCallbackJavaMethodID = nullptr; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.cpp index e010b56da36b28..f1d29cd063c450 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.cpp @@ -36,9 +36,7 @@ CHIP_ERROR RotatingDeviceIdUniqueIdProviderJNI::Initialize(jobject provider) VerifyOrReturnValue(env != nullptr, CHIP_ERROR_INCORRECT_STATE, ChipLogError(AppServer, "Failed to GetEnvForCurrentThread for RotatingDeviceIdUniqueIdProviderJNI")); - mJNIProviderObject = env->NewGlobalRef(provider); - VerifyOrReturnValue(mJNIProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE, - ChipLogError(AppServer, "Failed to NewGlobalRef JNIProvider")); + ReturnLogErrorOnFailure(mJNIProviderObject.Init(provider)); jclass JNIProviderClass = env->GetObjectClass(provider); VerifyOrReturnValue(JNIProviderClass != nullptr, CHIP_ERROR_INCORRECT_STATE, @@ -56,11 +54,11 @@ CHIP_ERROR RotatingDeviceIdUniqueIdProviderJNI::Initialize(jobject provider) CHIP_ERROR RotatingDeviceIdUniqueIdProviderJNI::GetJavaByteByMethod(jmethodID method, MutableByteSpan & out_buffer) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mJNIProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mJNIProviderObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(method != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIProviderObject, method); + jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIProviderObject.ObjectRef(), method); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in get Method"); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.h index fdec7744684834..4efd7074c21e54 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/RotatingDeviceIdUniqueIdProvider-JNI.h @@ -19,6 +19,7 @@ #include "core/Types.h" #include +#include namespace matter { namespace casting { @@ -32,8 +33,8 @@ class RotatingDeviceIdUniqueIdProviderJNI : public MutableByteSpanDataProvider private: CHIP_ERROR GetJavaByteByMethod(jmethodID method, chip::MutableByteSpan & out_buffer); - jobject mJNIProviderObject = nullptr; - jmethodID mGetMethod = nullptr; + chip::JniGlobalReference mJNIProviderObject; + jmethodID mGetMethod = nullptr; chip::MutableByteSpan mRotatingDeviceIdUniqueIdSpan; uint8_t mRotatingDeviceIdUniqueId[chip::DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength]; diff --git a/examples/virtual-device-app/android/java/ColorControlManager.cpp b/examples/virtual-device-app/android/java/ColorControlManager.cpp index 0386f96272f66e..1a4dfbe26c09f6 100644 --- a/examples/virtual-device-app/android/java/ColorControlManager.cpp +++ b/examples/virtual-device-app/android/java/ColorControlManager.cpp @@ -26,7 +26,7 @@ using namespace chip; -static constexpr size_t kColorControlManagerTableSize = EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT; +static constexpr size_t kColorControlManagerTableSize = MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT; namespace { @@ -45,7 +45,7 @@ void ColorControlManager::NewManager(jint endpoint, jobject manager) { ChipLogProgress(Zcl, "Device App: ColorControlManager::NewManager"); uint16_t ep = emberAfGetClusterServerEndpointIndex(static_cast(endpoint), app::Clusters::ColorControl::Id, - EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturn(ep < kColorControlManagerTableSize, ChipLogError(Zcl, "Device App::ColorControl::NewManager: endpoint %d not found", endpoint)); @@ -67,7 +67,7 @@ void ColorControlManager::NewManager(jint endpoint, jobject manager) static ColorControlManager * GetColorControlManager(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::ColorControl::Id, - EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kColorControlManagerTableSize ? nullptr : gColorControlManagerTable[ep]); } @@ -121,8 +121,7 @@ CHIP_ERROR ColorControlManager::InitializeWithObjects(jobject managerObject) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); - mColorControlManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturnLogError(mColorControlManagerObject != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + ReturnLogErrorOnFailure(mColorControlManagerObject.Init(managerObject)); jclass ColorControlManagerClass = env->GetObjectClass(managerObject); VerifyOrReturnLogError(ColorControlManagerClass != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -176,11 +175,11 @@ void ColorControlManager::HandleCurrentHueChanged(int value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mColorControlManagerObject != nullptr, ChipLogProgress(Zcl, "mColorControlManagerObject null")); + VerifyOrReturn(mColorControlManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mColorControlManagerObject null")); VerifyOrReturn(mHandleCurrentHueChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleCurrentHueChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mColorControlManagerObject, mHandleCurrentHueChangedMethod, value); + env->CallVoidMethod(mColorControlManagerObject.ObjectRef(), mHandleCurrentHueChangedMethod, value); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in ColorControlManager::HandleCurrentHueChanged"); @@ -195,12 +194,12 @@ void ColorControlManager::HandleCurrentSaturationChanged(int value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mColorControlManagerObject != nullptr, ChipLogProgress(Zcl, "mColorControlManagerObject null")); + VerifyOrReturn(mColorControlManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mColorControlManagerObject null")); VerifyOrReturn(mHandleCurrentSaturationChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleCurrentSaturationChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mColorControlManagerObject, mHandleCurrentSaturationChangedMethod, value); + env->CallVoidMethod(mColorControlManagerObject.ObjectRef(), mHandleCurrentSaturationChangedMethod, value); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in ColorControlManager::HandleCurrentSaturationChanged"); @@ -215,12 +214,12 @@ void ColorControlManager::HandleColorTemperatureChanged(int value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mColorControlManagerObject != nullptr, ChipLogProgress(Zcl, "mColorControlManagerObject null")); + VerifyOrReturn(mColorControlManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mColorControlManagerObject null")); VerifyOrReturn(mHandleColorTemperatureChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleColorTemperatureChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mColorControlManagerObject, mHandleColorTemperatureChangedMethod, value); + env->CallVoidMethod(mColorControlManagerObject.ObjectRef(), mHandleColorTemperatureChangedMethod, value); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in ColorControlManager::mHandleColorTemperatureChanged"); @@ -235,11 +234,11 @@ void ColorControlManager::HandleColorModeChanged(int value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mColorControlManagerObject != nullptr, ChipLogProgress(Zcl, "mColorControlManagerObject null")); + VerifyOrReturn(mColorControlManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mColorControlManagerObject null")); VerifyOrReturn(mHandleColorModeChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleColorModeChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mColorControlManagerObject, mHandleColorModeChangedMethod, value); + env->CallVoidMethod(mColorControlManagerObject.ObjectRef(), mHandleColorModeChangedMethod, value); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in ColorControlManager::HandleColorModeChanged"); @@ -254,12 +253,12 @@ void ColorControlManager::HandleEnhancedColorModeChanged(int value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mColorControlManagerObject != nullptr, ChipLogProgress(Zcl, "mColorControlManagerObject null")); + VerifyOrReturn(mColorControlManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mColorControlManagerObject null")); VerifyOrReturn(mHandleEnhancedColorModeChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleEnhancedColorModeChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mColorControlManagerObject, mHandleEnhancedColorModeChangedMethod, value); + env->CallVoidMethod(mColorControlManagerObject.ObjectRef(), mHandleEnhancedColorModeChangedMethod, value); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in ColorControlManager::HandleEnhancedColorModeChanged"); diff --git a/examples/virtual-device-app/android/java/ColorControlManager.h b/examples/virtual-device-app/android/java/ColorControlManager.h index be1022348c900c..ec909f2443eb59 100644 --- a/examples/virtual-device-app/android/java/ColorControlManager.h +++ b/examples/virtual-device-app/android/java/ColorControlManager.h @@ -18,6 +18,7 @@ #include #include +#include class ColorControlManager { @@ -46,7 +47,7 @@ class ColorControlManager private: CHIP_ERROR InitializeWithObjects(jobject managerObject); - jobject mColorControlManagerObject = nullptr; + chip::JniGlobalReference mColorControlManagerObject; jmethodID mHandleCurrentHueChangedMethod = nullptr; jmethodID mHandleCurrentSaturationChangedMethod = nullptr; jmethodID mHandleColorTemperatureChangedMethod = nullptr; diff --git a/examples/virtual-device-app/android/java/DeviceApp-JNI.cpp b/examples/virtual-device-app/android/java/DeviceApp-JNI.cpp index cb80a1dbda3865..8175ce0b955157 100644 --- a/examples/virtual-device-app/android/java/DeviceApp-JNI.cpp +++ b/examples/virtual-device-app/android/java/DeviceApp-JNI.cpp @@ -56,10 +56,9 @@ void DeviceAppJNI::InitializeWithObjects(jobject app) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for DeviceAppJNI")); - mDeviceAppObject = env->NewGlobalRef(app); - VerifyOrReturn(mDeviceAppObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef DeviceAppJNI")); + VerifyOrReturn(mDeviceAppObject.Init(app) == CHIP_NO_ERROR, ChipLogError(Zcl, "Failed to init mDeviceAppObject")); - jclass managerClass = env->GetObjectClass(mDeviceAppObject); + jclass managerClass = env->GetObjectClass(app); VerifyOrReturn(managerClass != nullptr, ChipLogError(Zcl, "Failed to get DeviceAppJNI Java class")); mPostClusterInitMethod = env->GetMethodID(managerClass, "postClusterInit", "(JI)V"); @@ -81,10 +80,11 @@ void DeviceAppJNI::PostClusterInit(int clusterId, int endpoint) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for DeviceAppJNI::PostClusterInit")); - VerifyOrReturn(mDeviceAppObject != nullptr, ChipLogError(Zcl, "DeviceAppJNI::mDeviceAppObject null")); + VerifyOrReturn(mDeviceAppObject.HasValidObjectRef(), ChipLogError(Zcl, "DeviceAppJNI::mDeviceAppObject null")); VerifyOrReturn(mPostClusterInitMethod != nullptr, ChipLogError(Zcl, "DeviceAppJNI::mPostClusterInitMethod null")); - env->CallVoidMethod(mDeviceAppObject, mPostClusterInitMethod, static_cast(clusterId), static_cast(endpoint)); + env->CallVoidMethod(mDeviceAppObject.ObjectRef(), mPostClusterInitMethod, static_cast(clusterId), + static_cast(endpoint)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Failed to call DeviceAppJNI 'postClusterInit' method"); @@ -96,10 +96,10 @@ void DeviceAppJNI::PostEvent(int event) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for DeviceAppJNI::PostEvent")); - VerifyOrReturn(mDeviceAppObject != nullptr, ChipLogError(Zcl, "DeviceAppJNI::mDeviceAppObject null")); + VerifyOrReturn(mDeviceAppObject.HasValidObjectRef(), ChipLogError(Zcl, "DeviceAppJNI::mDeviceAppObject null")); VerifyOrReturn(mPostEventMethod != nullptr, ChipLogError(Zcl, "DeviceAppJNI::mPostEventMethod null")); - env->CallVoidMethod(mDeviceAppObject, mPostEventMethod, static_cast(event)); + env->CallVoidMethod(mDeviceAppObject.ObjectRef(), mPostEventMethod, static_cast(event)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Failed to call DeviceAppJNI 'postEventMethod' method"); diff --git a/examples/virtual-device-app/android/java/DeviceApp-JNI.h b/examples/virtual-device-app/android/java/DeviceApp-JNI.h index e6772a41b16902..2187b91bdf91be 100644 --- a/examples/virtual-device-app/android/java/DeviceApp-JNI.h +++ b/examples/virtual-device-app/android/java/DeviceApp-JNI.h @@ -19,6 +19,7 @@ #pragma once #include +#include class DeviceAppJNI { @@ -31,7 +32,7 @@ class DeviceAppJNI friend DeviceAppJNI & DeviceAppJNIMgr(); static DeviceAppJNI sInstance; - jobject mDeviceAppObject = nullptr; + chip::JniGlobalReference mDeviceAppObject; jmethodID mPostClusterInitMethod = nullptr; jmethodID mPostEventMethod = nullptr; }; diff --git a/examples/virtual-device-app/android/java/DoorLockManager.cpp b/examples/virtual-device-app/android/java/DoorLockManager.cpp index 9a2c5748635dbd..5e85ffc817b4c9 100644 --- a/examples/virtual-device-app/android/java/DoorLockManager.cpp +++ b/examples/virtual-device-app/android/java/DoorLockManager.cpp @@ -36,7 +36,7 @@ using namespace chip::app::Clusters::DoorLock; using namespace chip::DeviceLayer; static constexpr size_t kDoorLockManagerTableSize = - EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; namespace { @@ -76,7 +76,7 @@ void DoorLockManager::NewManager(jint endpoint, jobject manager) { ChipLogProgress(Zcl, "Device App: DoorLockManager::NewManager"); uint16_t ep = emberAfGetClusterServerEndpointIndex(static_cast(endpoint), app::Clusters::DoorLock::Id, - EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturn(ep < kDoorLockManagerTableSize, ChipLogError(Zcl, "Device App::DoorLock::NewManager: endpoint %d not found", endpoint)); @@ -98,7 +98,7 @@ void DoorLockManager::NewManager(jint endpoint, jobject manager) DoorLockManager * GetDoorLockManager(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::DoorLock::Id, - EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); return ((ep >= kDoorLockManagerTableSize) ? nullptr : gDoorLockManagerTable[ep]); } @@ -158,8 +158,7 @@ CHIP_ERROR DoorLockManager::InitializeWithObjects(jobject managerObject) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); - mDoorLockManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturnLogError(mDoorLockManagerObject != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + ReturnLogErrorOnFailure(mDoorLockManagerObject.Init(managerObject)); jclass DoorLockManagerClass = env->GetObjectClass(managerObject); VerifyOrReturnLogError(DoorLockManagerClass != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -181,11 +180,11 @@ void DoorLockManager::HandleLockStateChanged(jint endpoint, jint value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mDoorLockManagerObject != nullptr, ChipLogProgress(Zcl, "mDoorLockManagerObject null")); + VerifyOrReturn(mDoorLockManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mDoorLockManagerObject null")); VerifyOrReturn(mHandleLockStateChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleLockStateChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mDoorLockManagerObject, mHandleLockStateChangedMethod, value); + env->CallVoidMethod(mDoorLockManagerObject.ObjectRef(), mHandleLockStateChangedMethod, value); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in DoorLockManager::HandleLockStateChanged"); diff --git a/examples/virtual-device-app/android/java/DoorLockManager.h b/examples/virtual-device-app/android/java/DoorLockManager.h index d6dac144f362a9..0962a94f35e752 100644 --- a/examples/virtual-device-app/android/java/DoorLockManager.h +++ b/examples/virtual-device-app/android/java/DoorLockManager.h @@ -22,6 +22,7 @@ #include #include #include +#include /** * @brief Handles interfacing between java code and C++ code for the purposes of DoorLock clusters. @@ -62,6 +63,6 @@ class DoorLockManager private: // init with java objects CHIP_ERROR InitializeWithObjects(jobject managerObject); - jobject mDoorLockManagerObject = nullptr; + chip::JniGlobalReference mDoorLockManagerObject; jmethodID mHandleLockStateChangedMethod = nullptr; }; diff --git a/examples/virtual-device-app/android/java/JNIDACProvider.cpp b/examples/virtual-device-app/android/java/JNIDACProvider.cpp index 3bc5ab0a9c23d1..ed2de8cdf7cb54 100644 --- a/examples/virtual-device-app/android/java/JNIDACProvider.cpp +++ b/examples/virtual-device-app/android/java/JNIDACProvider.cpp @@ -33,9 +33,8 @@ JNIDACProvider::JNIDACProvider(jobject provider) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Failed to GetEnvForCurrentThread for JNIDACProvider")); - - mJNIDACProviderObject = env->NewGlobalRef(provider); - VerifyOrReturn(mJNIDACProviderObject != nullptr, ChipLogError(Zcl, "Failed to NewGlobalRef JNIDACProvider")); + VerifyOrReturn(mJNIDACProviderObject.Init(provider) == CHIP_NO_ERROR, + ChipLogError(Zcl, "Failed to Init mJNIDACProviderObject")); jclass JNIDACProviderClass = env->GetObjectClass(provider); VerifyOrReturn(JNIDACProviderClass != nullptr, ChipLogError(Zcl, "Failed to get JNIDACProvider Java class")); @@ -88,11 +87,11 @@ JNIDACProvider::JNIDACProvider(jobject provider) CHIP_ERROR JNIDACProvider::GetJavaByteByMethod(jmethodID method, MutableByteSpan & out_buffer) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mJNIDACProviderObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mJNIDACProviderObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(method != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject, method); + jbyteArray outArray = (jbyteArray) env->CallObjectMethod(mJNIDACProviderObject.ObjectRef(), method); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in get Method"); diff --git a/examples/virtual-device-app/android/java/JNIDACProvider.h b/examples/virtual-device-app/android/java/JNIDACProvider.h index e2bad80e226f9f..92a75c177ca8d9 100644 --- a/examples/virtual-device-app/android/java/JNIDACProvider.h +++ b/examples/virtual-device-app/android/java/JNIDACProvider.h @@ -19,6 +19,7 @@ #include "lib/support/logging/CHIPLogging.h" #include #include +#include class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsProvider { @@ -33,7 +34,7 @@ class JNIDACProvider : public chip::Credentials::DeviceAttestationCredentialsPro private: CHIP_ERROR GetJavaByteByMethod(jmethodID method, chip::MutableByteSpan & out_buffer); - jobject mJNIDACProviderObject = nullptr; + chip::JniGlobalReference mJNIDACProviderObject; jmethodID mGetCertificationDeclarationMethod = nullptr; jmethodID mGetFirmwareInformationMethod = nullptr; jmethodID mGetDeviceAttestationCertMethod = nullptr; diff --git a/examples/virtual-device-app/android/java/OnOffManager.cpp b/examples/virtual-device-app/android/java/OnOffManager.cpp index c5a12dfebf30bf..2dcede64a8bce5 100644 --- a/examples/virtual-device-app/android/java/OnOffManager.cpp +++ b/examples/virtual-device-app/android/java/OnOffManager.cpp @@ -27,7 +27,7 @@ using namespace chip; -static constexpr size_t kOnffManagerTableSize = EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT; +static constexpr size_t kOnffManagerTableSize = MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT; namespace { @@ -46,7 +46,7 @@ void OnOffManager::NewManager(jint endpoint, jobject manager) { ChipLogProgress(Zcl, "Device App: OnOffManager::NewManager"); uint16_t ep = emberAfGetClusterServerEndpointIndex(static_cast(endpoint), app::Clusters::OnOff::Id, - EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturn(ep < kOnffManagerTableSize, ChipLogError(Zcl, "Device App::OnOff::NewManager: endpoint %d not found", endpoint)); VerifyOrReturn(gOnOffManagerTable[ep] == nullptr, @@ -67,7 +67,7 @@ void OnOffManager::NewManager(jint endpoint, jobject manager) OnOffManager * GetOnOffManager(EndpointId endpoint) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::OnOff::Id, EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::OnOff::Id, MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kOnffManagerTableSize ? nullptr : gOnOffManagerTable[ep]); } @@ -90,9 +90,7 @@ CHIP_ERROR OnOffManager::InitializeWithObjects(jobject managerObject) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); - - mOnOffManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturnLogError(mOnOffManagerObject != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + ReturnLogErrorOnFailure(mOnOffManagerObject.Init(managerObject)); jclass OnOffManagerClass = env->GetObjectClass(managerObject); VerifyOrReturnLogError(OnOffManagerClass != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -114,11 +112,11 @@ void OnOffManager::HandleOnOffChanged(bool value) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != NULL, ChipLogProgress(Zcl, "env null")); - VerifyOrReturn(mOnOffManagerObject != nullptr, ChipLogProgress(Zcl, "mOnOffManagerObject null")); + VerifyOrReturn(mOnOffManagerObject.HasValidObjectRef(), ChipLogProgress(Zcl, "mOnOffManagerObject null")); VerifyOrReturn(mHandleOnOffChangedMethod != nullptr, ChipLogProgress(Zcl, "mHandleOnOffChangedMethod null")); env->ExceptionClear(); - env->CallVoidMethod(mOnOffManagerObject, mHandleOnOffChangedMethod, static_cast(value)); + env->CallVoidMethod(mOnOffManagerObject.ObjectRef(), mHandleOnOffChangedMethod, static_cast(value)); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnOffManager::HandleOnOffChanged"); diff --git a/examples/virtual-device-app/android/java/OnOffManager.h b/examples/virtual-device-app/android/java/OnOffManager.h index 7305d10c46b22e..8056a16f1c1a8d 100644 --- a/examples/virtual-device-app/android/java/OnOffManager.h +++ b/examples/virtual-device-app/android/java/OnOffManager.h @@ -18,6 +18,7 @@ #include #include +#include /** * @brief Handles interfacing between java code and C++ code for the purposes of On/Off clusters. @@ -40,6 +41,6 @@ class OnOffManager private: // init with java objects CHIP_ERROR InitializeWithObjects(jobject managerObject); - jobject mOnOffManagerObject = nullptr; + chip::JniGlobalReference mOnOffManagerObject; jmethodID mHandleOnOffChangedMethod = nullptr; }; diff --git a/examples/virtual-device-app/android/java/PowerSourceManager.cpp b/examples/virtual-device-app/android/java/PowerSourceManager.cpp index 0d56b587448e40..afbdcca23bacb7 100644 --- a/examples/virtual-device-app/android/java/PowerSourceManager.cpp +++ b/examples/virtual-device-app/android/java/PowerSourceManager.cpp @@ -35,7 +35,7 @@ using namespace chip::app::Clusters; using namespace chip::app::Clusters::PowerSource; static constexpr size_t kPowerSourceManagerTableSize = - EMBER_AF_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; namespace { @@ -53,7 +53,7 @@ void PowerSourceManager::NewManager(jint endpoint, jobject manager) { ChipLogProgress(Zcl, "Device App: PowerSourceManager::NewManager"); uint16_t ep = emberAfGetClusterServerEndpointIndex(static_cast(endpoint), app::Clusters::PowerSource::Id, - EMBER_AF_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturn(ep < kPowerSourceManagerTableSize, ChipLogError(Zcl, "Device App::PowerSource::NewManager: endpoint %d not found", endpoint)); @@ -75,7 +75,7 @@ void PowerSourceManager::NewManager(jint endpoint, jobject manager) PowerSourceManager * GetPowerSourceManager(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, app::Clusters::PowerSource::Id, - EMBER_AF_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT); return ((ep >= kPowerSourceManagerTableSize) ? nullptr : gPowerSourceManagerTable[ep]); } @@ -96,9 +96,7 @@ CHIP_ERROR PowerSourceManager::InitializeWithObjects(jobject managerObject) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); - - mPowerSourceManagerObject = env->NewGlobalRef(managerObject); - VerifyOrReturnLogError(mPowerSourceManagerObject != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + ReturnLogErrorOnFailure(mPowerSourceManagerObject.Init(managerObject)); jclass PowerSourceManagerClass = env->GetObjectClass(managerObject); VerifyOrReturnLogError(PowerSourceManagerClass != nullptr, CHIP_ERROR_INVALID_ARGUMENT); diff --git a/examples/virtual-device-app/android/java/PowerSourceManager.h b/examples/virtual-device-app/android/java/PowerSourceManager.h index 54b2c68c8b7011..7154558ac02c42 100644 --- a/examples/virtual-device-app/android/java/PowerSourceManager.h +++ b/examples/virtual-device-app/android/java/PowerSourceManager.h @@ -21,6 +21,7 @@ #include #include #include +#include /** * @brief Handles interfacing between java code and C++ code for the purposes of PowerSource clusters. @@ -35,5 +36,5 @@ class PowerSourceManager private: // init with java objects CHIP_ERROR InitializeWithObjects(jobject managerObject); - jobject mPowerSourceManagerObject = nullptr; + chip::JniGlobalReference mPowerSourceManagerObject; }; diff --git a/scripts/tools/not_known_to_gn.py b/scripts/tools/not_known_to_gn.py new file mode 100755 index 00000000000000..613f8a23ecb707 --- /dev/null +++ b/scripts/tools/not_known_to_gn.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +""" +Lists files specific files from a source tree and ensures +they are covered by GN in some way. + +'Covered' is very loosely and it just tries to see if the GN text +contains that word without trying to validate if this is a +comment or some actual 'source' element. + +It is intended as a failsafe to not foget adding source files +to gn. +""" +import logging +import os +import sys +from pathlib import Path, PurePath +from typing import Dict, Set + +import click +import coloredlogs + +__LOG_LEVELS__ = { + 'debug': logging.DEBUG, + 'info': logging.INFO, + 'warn': logging.WARN, + 'fatal': logging.FATAL, +} + + +class OrphanChecker: + def __init__(self): + self.gn_data: Dict[str, str] = {} + self.known_failures: Set[str] = set() + self.fatal_failures = 0 + self.failures = 0 + self.found_failures: Set[str] = set() + + def AppendGnData(self, gn: PurePath): + """Adds a GN file to the list of internally known GN data. + + Will read the entire content of the GN file in memory for future reference. + """ + logging.debug(f'Adding GN {gn!s} for {gn.parent!s}') + self.gn_data[str(gn.parent)] = gn.read_text('utf-8') + + def AddKnownFailure(self, k: str): + self.known_failures.add(k) + + def _IsKnownFailure(self, path: str) -> bool: + """check if failing on the given path is a known/acceptable failure""" + for k in self.known_failures: + if path == k or path.endswith(os.path.sep + k): + # mark some found failures to report if something is supposed + # to be known but it is not + self.found_failures.add(k) + return True + return False + + def Check(self, top_dir: str, file: PurePath): + """ + Validates that the given path is somehow referenced in GN files in any + of the parent sub-directories of the file. + + `file` must be relative to `top_dir`. Top_dir is used to resolve relative + paths in error reports and known failure checks. + """ + # Check logic: + # - ensure the file name is included in some GN file inside this or + # upper directory (although upper directory is not ideal) + for p in file.parents: + data = self.gn_data.get(str(p), None) + if not data: + continue + + if file.name in data: + logging.debug("%s found in BUILD.gn for %s", file, p) + return + + path = str(file.relative_to(top_dir)) + if not self._IsKnownFailure(path): + logging.error("UNKNOWN to gn: %s", path) + self.fatal_failures += 1 + else: + logging.warning("UNKNOWN to gn: %s (known error)", path) + + self.failures += 1 + + +@click.command() +@click.option( + '--log-level', + default='INFO', + type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), + help='Determines the verbosity of script output', +) +@click.option( + '--extensions', + default=["cpp", "cc", "c", "h", "hpp"], + type=str, multiple=True, + help='What file extensions to consider', +) +@click.option( + '--known-failure', + type=str, multiple=True, + help='What paths are known to fail', +) +@click.option( + '--skip-dir', + type=str, + multiple=True, + help='Skip a specific sub-directory from checks', +) +@click.argument('dirs', + type=click.Path(exists=True, file_okay=False, resolve_path=True), nargs=-1) +def main(log_level, extensions, dirs, known_failure, skip_dir): + coloredlogs.install(level=__LOG_LEVELS__[log_level], + fmt='%(asctime)s %(levelname)-7s %(message)s') + + if not dirs: + logging.error("Please provide at least one directory to scan") + sys.exit(1) + + if not extensions: + logging.error("Need at least one extension") + sys.exit(1) + + checker = OrphanChecker() + for k in known_failure: + checker.AddKnownFailure(k) + + # ensure all GN data is loaded + for directory in dirs: + for name in Path(directory).rglob("BUILD.gn"): + checker.AppendGnData(name) + + skip_dir = set(skip_dir) + + # Go through all files and check for orphaned (if any) + extensions = set(extensions) + for directory in dirs: + for path, dirnames, filenames in os.walk(directory): + if any([s in path for s in skip_dir]): + continue + for f in filenames: + full_path = Path(os.path.join(path, f)) + if not full_path.suffix or full_path.suffix[1:] not in extensions: + continue + checker.Check(directory, full_path) + + if checker.failures: + logging.warning("%d files not known to GN (%d fatal)", checker.failures, checker.fatal_failures) + + if checker.known_failures != checker.found_failures: + not_failing = checker.known_failures - checker.found_failures + logging.warning("NOTE: %d failures are not found anymore:", len(not_failing)) + for name in not_failing: + logging.warning(" - %s", name) + # Assume this is fatal - remove some of the "known-failing" should be easy. + # This forces scripts to always be correct and not accumulate bad input. + sys.exit(1) + + if checker.fatal_failures > 0: + sys.exit(1) + + +if __name__ == '__main__': + main(auto_envvar_prefix='CHIP') diff --git a/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/gen_config.h b/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/gen_config.h index 8324cf19058453..e4347a93f273b1 100644 --- a/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/gen_config.h +++ b/scripts/tools/zap/tests/outputs/all-clusters-app/app-templates/gen_config.h @@ -21,244 +21,244 @@ #pragma once /**** Cluster endpoint counts ****/ -#define EMBER_AF_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT (3) -#define EMBER_AF_GROUPS_CLUSTER_SERVER_ENDPOINT_COUNT (3) -#define EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_ON_OFF_SWITCH_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_BINARY_INPUT_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_DESCRIPTOR_CLUSTER_SERVER_ENDPOINT_COUNT (4) -#define EMBER_AF_BINDING_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_ACCESS_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ACTIONS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_BASIC_INFORMATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_CLIENT_ENDPOINT_COUNT (1) -#define EMBER_AF_OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_UNIT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT (3) -#define EMBER_AF_GENERAL_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_NETWORK_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_GENERAL_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_SWITCH_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_FIXED_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_USER_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_BOOLEAN_STATE_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_SCENES_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_BARRIER_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_PUMP_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_THERMOSTAT_USER_INTERFACE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ILLUMINANCE_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_TEMPERATURE_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_PRESSURE_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_FLOW_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_OCCUPANCY_SENSING_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ELECTRICAL_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_UNIT_TESTING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_FAULT_INJECTION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT (3) +#define MATTER_DM_GROUPS_CLUSTER_SERVER_ENDPOINT_COUNT (3) +#define MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_ON_OFF_SWITCH_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_BINARY_INPUT_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_DESCRIPTOR_CLUSTER_SERVER_ENDPOINT_COUNT (4) +#define MATTER_DM_BINDING_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_ACCESS_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ACTIONS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_BASIC_INFORMATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_CLIENT_ENDPOINT_COUNT (1) +#define MATTER_DM_OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_UNIT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT (3) +#define MATTER_DM_GENERAL_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_NETWORK_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_GENERAL_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_SWITCH_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_FIXED_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_USER_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_BOOLEAN_STATE_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_MODE_SELECT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_SCENES_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_BARRIER_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_PUMP_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_THERMOSTAT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_THERMOSTAT_USER_INTERFACE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ILLUMINANCE_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_TEMPERATURE_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_PRESSURE_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_FLOW_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_OCCUPANCY_SENSING_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ELECTRICAL_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_UNIT_TESTING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_FAULT_INJECTION_CLUSTER_SERVER_ENDPOINT_COUNT (1) /**** Cluster Plugins ****/ // Use this macro to check if the server side of the Identify cluster is included #define ZCL_USING_IDENTIFY_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_IDENTIFY_SERVER -#define EMBER_AF_PLUGIN_IDENTIFY +#define MATTER_DM_PLUGIN_IDENTIFY_SERVER +#define MATTER_DM_PLUGIN_IDENTIFY // Use this macro to check if the server side of the Groups cluster is included #define ZCL_USING_GROUPS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GROUPS_SERVER -#define EMBER_AF_PLUGIN_GROUPS +#define MATTER_DM_PLUGIN_GROUPS_SERVER +#define MATTER_DM_PLUGIN_GROUPS // Use this macro to check if the server side of the On/Off cluster is included #define ZCL_USING_ON_OFF_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ON_OFF_SERVER -#define EMBER_AF_PLUGIN_ON_OFF +#define MATTER_DM_PLUGIN_ON_OFF_SERVER +#define MATTER_DM_PLUGIN_ON_OFF // Use this macro to check if the server side of the On/off Switch Configuration cluster is included #define ZCL_USING_ON_OFF_SWITCH_CONFIGURATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ON_OFF_SWITCH_CONFIGURATION_SERVER -#define EMBER_AF_PLUGIN_ON_OFF_SWITCH_CONFIGURATION +#define MATTER_DM_PLUGIN_ON_OFF_SWITCH_CONFIGURATION_SERVER +#define MATTER_DM_PLUGIN_ON_OFF_SWITCH_CONFIGURATION // Use this macro to check if the server side of the Level Control cluster is included #define ZCL_USING_LEVEL_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_SERVER -#define EMBER_AF_PLUGIN_LEVEL_CONTROL +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_SERVER +#define MATTER_DM_PLUGIN_LEVEL_CONTROL // User options for server plugin Level Control -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254 -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0 -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE 0 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_RATE 0 // Use this macro to check if the server side of the Binary Input (Basic) cluster is included #define ZCL_USING_BINARY_INPUT_BASIC_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_BINARY_INPUT_BASIC_SERVER -#define EMBER_AF_PLUGIN_BINARY_INPUT_BASIC +#define MATTER_DM_PLUGIN_BINARY_INPUT_BASIC_SERVER +#define MATTER_DM_PLUGIN_BINARY_INPUT_BASIC // Use this macro to check if the server side of the Descriptor cluster is included #define ZCL_USING_DESCRIPTOR_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_DESCRIPTOR_SERVER -#define EMBER_AF_PLUGIN_DESCRIPTOR +#define MATTER_DM_PLUGIN_DESCRIPTOR_SERVER +#define MATTER_DM_PLUGIN_DESCRIPTOR // Use this macro to check if the server side of the Binding cluster is included #define ZCL_USING_BINDING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_BINDING_SERVER -#define EMBER_AF_PLUGIN_BINDING +#define MATTER_DM_PLUGIN_BINDING_SERVER +#define MATTER_DM_PLUGIN_BINDING // Use this macro to check if the server side of the Access Control cluster is included #define ZCL_USING_ACCESS_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ACCESS_CONTROL_SERVER -#define EMBER_AF_PLUGIN_ACCESS_CONTROL +#define MATTER_DM_PLUGIN_ACCESS_CONTROL_SERVER +#define MATTER_DM_PLUGIN_ACCESS_CONTROL // Use this macro to check if the server side of the Actions cluster is included #define ZCL_USING_ACTIONS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ACTIONS_SERVER -#define EMBER_AF_PLUGIN_ACTIONS +#define MATTER_DM_PLUGIN_ACTIONS_SERVER +#define MATTER_DM_PLUGIN_ACTIONS // Use this macro to check if the server side of the Basic Information cluster is included #define ZCL_USING_BASIC_INFORMATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_BASIC_INFORMATION_SERVER -#define EMBER_AF_PLUGIN_BASIC_INFORMATION +#define MATTER_DM_PLUGIN_BASIC_INFORMATION_SERVER +#define MATTER_DM_PLUGIN_BASIC_INFORMATION // Use this macro to check if the client side of the OTA Software Update Provider cluster is included #define ZCL_USING_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_CLIENT -#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_PROVIDER_CLIENT +#define MATTER_DM_PLUGIN_OTA_SOFTWARE_UPDATE_PROVIDER_CLIENT // Use this macro to check if the server side of the OTA Software Update Requestor cluster is included #define ZCL_USING_OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR_SERVER -#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR +#define MATTER_DM_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR_SERVER +#define MATTER_DM_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR // Use this macro to check if the server side of the Localization Configuration cluster is included #define ZCL_USING_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_LOCALIZATION_CONFIGURATION_SERVER -#define EMBER_AF_PLUGIN_LOCALIZATION_CONFIGURATION +#define MATTER_DM_PLUGIN_LOCALIZATION_CONFIGURATION_SERVER +#define MATTER_DM_PLUGIN_LOCALIZATION_CONFIGURATION // Use this macro to check if the server side of the Time Format Localization cluster is included #define ZCL_USING_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_TIME_FORMAT_LOCALIZATION_SERVER -#define EMBER_AF_PLUGIN_TIME_FORMAT_LOCALIZATION +#define MATTER_DM_PLUGIN_TIME_FORMAT_LOCALIZATION_SERVER +#define MATTER_DM_PLUGIN_TIME_FORMAT_LOCALIZATION // Use this macro to check if the server side of the Unit Localization cluster is included #define ZCL_USING_UNIT_LOCALIZATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_UNIT_LOCALIZATION_SERVER -#define EMBER_AF_PLUGIN_UNIT_LOCALIZATION +#define MATTER_DM_PLUGIN_UNIT_LOCALIZATION_SERVER +#define MATTER_DM_PLUGIN_UNIT_LOCALIZATION // Use this macro to check if the server side of the Power Source cluster is included #define ZCL_USING_POWER_SOURCE_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_POWER_SOURCE_SERVER -#define EMBER_AF_PLUGIN_POWER_SOURCE +#define MATTER_DM_PLUGIN_POWER_SOURCE_SERVER +#define MATTER_DM_PLUGIN_POWER_SOURCE // Use this macro to check if the server side of the General Commissioning cluster is included #define ZCL_USING_GENERAL_COMMISSIONING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING_SERVER -#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING +#define MATTER_DM_PLUGIN_GENERAL_COMMISSIONING_SERVER +#define MATTER_DM_PLUGIN_GENERAL_COMMISSIONING // Use this macro to check if the server side of the Network Commissioning cluster is included #define ZCL_USING_NETWORK_COMMISSIONING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING_SERVER -#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING +#define MATTER_DM_PLUGIN_NETWORK_COMMISSIONING_SERVER +#define MATTER_DM_PLUGIN_NETWORK_COMMISSIONING // Use this macro to check if the server side of the Diagnostic Logs cluster is included #define ZCL_USING_DIAGNOSTIC_LOGS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_DIAGNOSTIC_LOGS_SERVER -#define EMBER_AF_PLUGIN_DIAGNOSTIC_LOGS +#define MATTER_DM_PLUGIN_DIAGNOSTIC_LOGS_SERVER +#define MATTER_DM_PLUGIN_DIAGNOSTIC_LOGS // Use this macro to check if the server side of the General Diagnostics cluster is included #define ZCL_USING_GENERAL_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GENERAL_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_GENERAL_DIAGNOSTICS +#define MATTER_DM_PLUGIN_GENERAL_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_GENERAL_DIAGNOSTICS // Use this macro to check if the server side of the Software Diagnostics cluster is included #define ZCL_USING_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS +#define MATTER_DM_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_SOFTWARE_DIAGNOSTICS // Use this macro to check if the server side of the Thread Network Diagnostics cluster is included #define ZCL_USING_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_THREAD_NETWORK_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_THREAD_NETWORK_DIAGNOSTICS +#define MATTER_DM_PLUGIN_THREAD_NETWORK_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_THREAD_NETWORK_DIAGNOSTICS // Use this macro to check if the server side of the WiFi Network Diagnostics cluster is included #define ZCL_USING_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS +#define MATTER_DM_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS // Use this macro to check if the server side of the Ethernet Network Diagnostics cluster is included #define ZCL_USING_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS +#define MATTER_DM_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS // Use this macro to check if the server side of the Switch cluster is included #define ZCL_USING_SWITCH_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_SWITCH_SERVER -#define EMBER_AF_PLUGIN_SWITCH +#define MATTER_DM_PLUGIN_SWITCH_SERVER +#define MATTER_DM_PLUGIN_SWITCH // Use this macro to check if the server side of the Administrator Commissioning cluster is included #define ZCL_USING_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ADMINISTRATOR_COMMISSIONING_SERVER -#define EMBER_AF_PLUGIN_ADMINISTRATOR_COMMISSIONING +#define MATTER_DM_PLUGIN_ADMINISTRATOR_COMMISSIONING_SERVER +#define MATTER_DM_PLUGIN_ADMINISTRATOR_COMMISSIONING // Use this macro to check if the server side of the Operational Credentials cluster is included #define ZCL_USING_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS_SERVER -#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS +#define MATTER_DM_PLUGIN_OPERATIONAL_CREDENTIALS_SERVER +#define MATTER_DM_PLUGIN_OPERATIONAL_CREDENTIALS // Use this macro to check if the server side of the Group Key Management cluster is included #define ZCL_USING_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GROUP_KEY_MANAGEMENT_SERVER -#define EMBER_AF_PLUGIN_GROUP_KEY_MANAGEMENT +#define MATTER_DM_PLUGIN_GROUP_KEY_MANAGEMENT_SERVER +#define MATTER_DM_PLUGIN_GROUP_KEY_MANAGEMENT // Use this macro to check if the server side of the Fixed Label cluster is included #define ZCL_USING_FIXED_LABEL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_FIXED_LABEL_SERVER -#define EMBER_AF_PLUGIN_FIXED_LABEL +#define MATTER_DM_PLUGIN_FIXED_LABEL_SERVER +#define MATTER_DM_PLUGIN_FIXED_LABEL // Use this macro to check if the server side of the User Label cluster is included #define ZCL_USING_USER_LABEL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_USER_LABEL_SERVER -#define EMBER_AF_PLUGIN_USER_LABEL +#define MATTER_DM_PLUGIN_USER_LABEL_SERVER +#define MATTER_DM_PLUGIN_USER_LABEL // Use this macro to check if the server side of the Boolean State cluster is included #define ZCL_USING_BOOLEAN_STATE_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_BOOLEAN_STATE_SERVER -#define EMBER_AF_PLUGIN_BOOLEAN_STATE +#define MATTER_DM_PLUGIN_BOOLEAN_STATE_SERVER +#define MATTER_DM_PLUGIN_BOOLEAN_STATE // Use this macro to check if the server side of the Mode Select cluster is included #define ZCL_USING_MODE_SELECT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_MODE_SELECT_SERVER -#define EMBER_AF_PLUGIN_MODE_SELECT +#define MATTER_DM_PLUGIN_MODE_SELECT_SERVER +#define MATTER_DM_PLUGIN_MODE_SELECT // Use this macro to check if the server side of the Scenes Management cluster is included #define ZCL_USING_SCENES_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_SCENES_MANAGEMENT_SERVER -#define EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#define MATTER_DM_PLUGIN_SCENES_MANAGEMENT_SERVER +#define MATTER_DM_PLUGIN_SCENES_MANAGEMENT // User options for server plugin Scenes Management // Scenes FeatureMap Attribute Toggle Scenes Name feature // App cluster specs 1.4.4 @@ -271,149 +271,149 @@ // Use this macro to check if the server side of the Door Lock cluster is included #define ZCL_USING_DOOR_LOCK_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_DOOR_LOCK_SERVER -#define EMBER_AF_PLUGIN_DOOR_LOCK +#define MATTER_DM_PLUGIN_DOOR_LOCK_SERVER +#define MATTER_DM_PLUGIN_DOOR_LOCK // Use this macro to check if the server side of the Window Covering cluster is included #define ZCL_USING_WINDOW_COVERING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_WINDOW_COVERING_SERVER -#define EMBER_AF_PLUGIN_WINDOW_COVERING +#define MATTER_DM_PLUGIN_WINDOW_COVERING_SERVER +#define MATTER_DM_PLUGIN_WINDOW_COVERING // Use this macro to check if the server side of the Barrier Control cluster is included #define ZCL_USING_BARRIER_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_BARRIER_CONTROL_SERVER -#define EMBER_AF_PLUGIN_BARRIER_CONTROL +#define MATTER_DM_PLUGIN_BARRIER_CONTROL_SERVER +#define MATTER_DM_PLUGIN_BARRIER_CONTROL // Use this macro to check if the server side of the Pump Configuration and Control cluster is included #define ZCL_USING_PUMP_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_PUMP_CONFIGURATION_AND_CONTROL_SERVER -#define EMBER_AF_PLUGIN_PUMP_CONFIGURATION_AND_CONTROL +#define MATTER_DM_PLUGIN_PUMP_CONFIGURATION_AND_CONTROL_SERVER +#define MATTER_DM_PLUGIN_PUMP_CONFIGURATION_AND_CONTROL // Use this macro to check if the server side of the Thermostat cluster is included #define ZCL_USING_THERMOSTAT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_THERMOSTAT_SERVER -#define EMBER_AF_PLUGIN_THERMOSTAT +#define MATTER_DM_PLUGIN_THERMOSTAT_SERVER +#define MATTER_DM_PLUGIN_THERMOSTAT // Use this macro to check if the server side of the Fan Control cluster is included #define ZCL_USING_FAN_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_FAN_CONTROL_SERVER -#define EMBER_AF_PLUGIN_FAN_CONTROL +#define MATTER_DM_PLUGIN_FAN_CONTROL_SERVER +#define MATTER_DM_PLUGIN_FAN_CONTROL // Use this macro to check if the server side of the Thermostat User Interface Configuration cluster is included #define ZCL_USING_THERMOSTAT_USER_INTERFACE_CONFIGURATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_THERMOSTAT_USER_INTERFACE_CONFIGURATION_SERVER -#define EMBER_AF_PLUGIN_THERMOSTAT_USER_INTERFACE_CONFIGURATION +#define MATTER_DM_PLUGIN_THERMOSTAT_USER_INTERFACE_CONFIGURATION_SERVER +#define MATTER_DM_PLUGIN_THERMOSTAT_USER_INTERFACE_CONFIGURATION // Use this macro to check if the server side of the Color Control cluster is included #define ZCL_USING_COLOR_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER -#define EMBER_AF_PLUGIN_COLOR_CONTROL +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER +#define MATTER_DM_PLUGIN_COLOR_CONTROL // User options for server plugin Color Control -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV // Use this macro to check if the server side of the Illuminance Measurement cluster is included #define ZCL_USING_ILLUMINANCE_MEASUREMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ILLUMINANCE_MEASUREMENT_SERVER -#define EMBER_AF_PLUGIN_ILLUMINANCE_MEASUREMENT +#define MATTER_DM_PLUGIN_ILLUMINANCE_MEASUREMENT_SERVER +#define MATTER_DM_PLUGIN_ILLUMINANCE_MEASUREMENT // Use this macro to check if the server side of the Temperature Measurement cluster is included #define ZCL_USING_TEMPERATURE_MEASUREMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_TEMPERATURE_MEASUREMENT_SERVER -#define EMBER_AF_PLUGIN_TEMPERATURE_MEASUREMENT +#define MATTER_DM_PLUGIN_TEMPERATURE_MEASUREMENT_SERVER +#define MATTER_DM_PLUGIN_TEMPERATURE_MEASUREMENT // Use this macro to check if the server side of the Pressure Measurement cluster is included #define ZCL_USING_PRESSURE_MEASUREMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_PRESSURE_MEASUREMENT_SERVER -#define EMBER_AF_PLUGIN_PRESSURE_MEASUREMENT +#define MATTER_DM_PLUGIN_PRESSURE_MEASUREMENT_SERVER +#define MATTER_DM_PLUGIN_PRESSURE_MEASUREMENT // Use this macro to check if the server side of the Flow Measurement cluster is included #define ZCL_USING_FLOW_MEASUREMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_FLOW_MEASUREMENT_SERVER -#define EMBER_AF_PLUGIN_FLOW_MEASUREMENT +#define MATTER_DM_PLUGIN_FLOW_MEASUREMENT_SERVER +#define MATTER_DM_PLUGIN_FLOW_MEASUREMENT // Use this macro to check if the server side of the Relative Humidity Measurement cluster is included #define ZCL_USING_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_RELATIVE_HUMIDITY_MEASUREMENT_SERVER -#define EMBER_AF_PLUGIN_RELATIVE_HUMIDITY_MEASUREMENT +#define MATTER_DM_PLUGIN_RELATIVE_HUMIDITY_MEASUREMENT_SERVER +#define MATTER_DM_PLUGIN_RELATIVE_HUMIDITY_MEASUREMENT // Use this macro to check if the server side of the Occupancy Sensing cluster is included #define ZCL_USING_OCCUPANCY_SENSING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_OCCUPANCY_SENSING_SERVER -#define EMBER_AF_PLUGIN_OCCUPANCY_SENSING +#define MATTER_DM_PLUGIN_OCCUPANCY_SENSING_SERVER +#define MATTER_DM_PLUGIN_OCCUPANCY_SENSING // Use this macro to check if the server side of the Wake on LAN cluster is included #define ZCL_USING_WAKE_ON_LAN_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_WAKE_ON_LAN_SERVER -#define EMBER_AF_PLUGIN_WAKE_ON_LAN +#define MATTER_DM_PLUGIN_WAKE_ON_LAN_SERVER +#define MATTER_DM_PLUGIN_WAKE_ON_LAN // Use this macro to check if the server side of the Channel cluster is included #define ZCL_USING_CHANNEL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_CHANNEL_SERVER -#define EMBER_AF_PLUGIN_CHANNEL +#define MATTER_DM_PLUGIN_CHANNEL_SERVER +#define MATTER_DM_PLUGIN_CHANNEL // Use this macro to check if the server side of the Target Navigator cluster is included #define ZCL_USING_TARGET_NAVIGATOR_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_TARGET_NAVIGATOR_SERVER -#define EMBER_AF_PLUGIN_TARGET_NAVIGATOR +#define MATTER_DM_PLUGIN_TARGET_NAVIGATOR_SERVER +#define MATTER_DM_PLUGIN_TARGET_NAVIGATOR // Use this macro to check if the server side of the Media Playback cluster is included #define ZCL_USING_MEDIA_PLAYBACK_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_MEDIA_PLAYBACK_SERVER -#define EMBER_AF_PLUGIN_MEDIA_PLAYBACK +#define MATTER_DM_PLUGIN_MEDIA_PLAYBACK_SERVER +#define MATTER_DM_PLUGIN_MEDIA_PLAYBACK // Use this macro to check if the server side of the Media Input cluster is included #define ZCL_USING_MEDIA_INPUT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_MEDIA_INPUT_SERVER -#define EMBER_AF_PLUGIN_MEDIA_INPUT +#define MATTER_DM_PLUGIN_MEDIA_INPUT_SERVER +#define MATTER_DM_PLUGIN_MEDIA_INPUT // Use this macro to check if the server side of the Low Power cluster is included #define ZCL_USING_LOW_POWER_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_LOW_POWER_SERVER -#define EMBER_AF_PLUGIN_LOW_POWER +#define MATTER_DM_PLUGIN_LOW_POWER_SERVER +#define MATTER_DM_PLUGIN_LOW_POWER // Use this macro to check if the server side of the Keypad Input cluster is included #define ZCL_USING_KEYPAD_INPUT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_KEYPAD_INPUT_SERVER -#define EMBER_AF_PLUGIN_KEYPAD_INPUT +#define MATTER_DM_PLUGIN_KEYPAD_INPUT_SERVER +#define MATTER_DM_PLUGIN_KEYPAD_INPUT // Use this macro to check if the server side of the Content Launcher cluster is included #define ZCL_USING_CONTENT_LAUNCHER_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_CONTENT_LAUNCHER_SERVER -#define EMBER_AF_PLUGIN_CONTENT_LAUNCHER +#define MATTER_DM_PLUGIN_CONTENT_LAUNCHER_SERVER +#define MATTER_DM_PLUGIN_CONTENT_LAUNCHER // Use this macro to check if the server side of the Audio Output cluster is included #define ZCL_USING_AUDIO_OUTPUT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_AUDIO_OUTPUT_SERVER -#define EMBER_AF_PLUGIN_AUDIO_OUTPUT +#define MATTER_DM_PLUGIN_AUDIO_OUTPUT_SERVER +#define MATTER_DM_PLUGIN_AUDIO_OUTPUT // Use this macro to check if the server side of the Application Launcher cluster is included #define ZCL_USING_APPLICATION_LAUNCHER_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_APPLICATION_LAUNCHER_SERVER -#define EMBER_AF_PLUGIN_APPLICATION_LAUNCHER +#define MATTER_DM_PLUGIN_APPLICATION_LAUNCHER_SERVER +#define MATTER_DM_PLUGIN_APPLICATION_LAUNCHER // Use this macro to check if the server side of the Application Basic cluster is included #define ZCL_USING_APPLICATION_BASIC_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_APPLICATION_BASIC_SERVER -#define EMBER_AF_PLUGIN_APPLICATION_BASIC +#define MATTER_DM_PLUGIN_APPLICATION_BASIC_SERVER +#define MATTER_DM_PLUGIN_APPLICATION_BASIC // Use this macro to check if the server side of the Account Login cluster is included #define ZCL_USING_ACCOUNT_LOGIN_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ACCOUNT_LOGIN_SERVER -#define EMBER_AF_PLUGIN_ACCOUNT_LOGIN +#define MATTER_DM_PLUGIN_ACCOUNT_LOGIN_SERVER +#define MATTER_DM_PLUGIN_ACCOUNT_LOGIN // Use this macro to check if the server side of the Electrical Measurement cluster is included #define ZCL_USING_ELECTRICAL_MEASUREMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ELECTRICAL_MEASUREMENT_SERVER -#define EMBER_AF_PLUGIN_ELECTRICAL_MEASUREMENT +#define MATTER_DM_PLUGIN_ELECTRICAL_MEASUREMENT_SERVER +#define MATTER_DM_PLUGIN_ELECTRICAL_MEASUREMENT // Use this macro to check if the server side of the Unit Testing cluster is included #define ZCL_USING_UNIT_TESTING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_UNIT_TESTING_SERVER -#define EMBER_AF_PLUGIN_UNIT_TESTING +#define MATTER_DM_PLUGIN_UNIT_TESTING_SERVER +#define MATTER_DM_PLUGIN_UNIT_TESTING // Use this macro to check if the server side of the Fault Injection cluster is included #define ZCL_USING_FAULT_INJECTION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_FAULT_INJECTION_SERVER -#define EMBER_AF_PLUGIN_FAULT_INJECTION +#define MATTER_DM_PLUGIN_FAULT_INJECTION_SERVER +#define MATTER_DM_PLUGIN_FAULT_INJECTION diff --git a/scripts/tools/zap/tests/outputs/lighting-app/app-templates/gen_config.h b/scripts/tools/zap/tests/outputs/lighting-app/app-templates/gen_config.h index 0c29e4f6258917..7002f3ef3bd806 100644 --- a/scripts/tools/zap/tests/outputs/lighting-app/app-templates/gen_config.h +++ b/scripts/tools/zap/tests/outputs/lighting-app/app-templates/gen_config.h @@ -21,174 +21,174 @@ #pragma once /**** Cluster endpoint counts ****/ -#define EMBER_AF_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_GROUPS_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_DESCRIPTOR_CLUSTER_SERVER_ENDPOINT_COUNT (2) -#define EMBER_AF_ACCESS_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_BASIC_INFORMATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_CLIENT_ENDPOINT_COUNT (1) -#define EMBER_AF_OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_GENERAL_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_NETWORK_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_GENERAL_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_SWITCH_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_FIXED_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_USER_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) -#define EMBER_AF_OCCUPANCY_SENSING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_GROUPS_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_DESCRIPTOR_CLUSTER_SERVER_ENDPOINT_COUNT (2) +#define MATTER_DM_ACCESS_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_BASIC_INFORMATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_CLIENT_ENDPOINT_COUNT (1) +#define MATTER_DM_OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_GENERAL_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_NETWORK_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_GENERAL_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_SWITCH_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_FIXED_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_USER_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1) +#define MATTER_DM_OCCUPANCY_SENSING_CLUSTER_SERVER_ENDPOINT_COUNT (1) /**** Cluster Plugins ****/ // Use this macro to check if the server side of the Identify cluster is included #define ZCL_USING_IDENTIFY_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_IDENTIFY_SERVER -#define EMBER_AF_PLUGIN_IDENTIFY +#define MATTER_DM_PLUGIN_IDENTIFY_SERVER +#define MATTER_DM_PLUGIN_IDENTIFY // Use this macro to check if the server side of the Groups cluster is included #define ZCL_USING_GROUPS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GROUPS_SERVER -#define EMBER_AF_PLUGIN_GROUPS +#define MATTER_DM_PLUGIN_GROUPS_SERVER +#define MATTER_DM_PLUGIN_GROUPS // Use this macro to check if the server side of the On/Off cluster is included #define ZCL_USING_ON_OFF_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ON_OFF_SERVER -#define EMBER_AF_PLUGIN_ON_OFF +#define MATTER_DM_PLUGIN_ON_OFF_SERVER +#define MATTER_DM_PLUGIN_ON_OFF // Use this macro to check if the server side of the Level Control cluster is included #define ZCL_USING_LEVEL_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_SERVER -#define EMBER_AF_PLUGIN_LEVEL_CONTROL +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_SERVER +#define MATTER_DM_PLUGIN_LEVEL_CONTROL // User options for server plugin Level Control -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254 -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0 -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE 0 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_RATE 0 // Use this macro to check if the server side of the Descriptor cluster is included #define ZCL_USING_DESCRIPTOR_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_DESCRIPTOR_SERVER -#define EMBER_AF_PLUGIN_DESCRIPTOR +#define MATTER_DM_PLUGIN_DESCRIPTOR_SERVER +#define MATTER_DM_PLUGIN_DESCRIPTOR // Use this macro to check if the server side of the Access Control cluster is included #define ZCL_USING_ACCESS_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ACCESS_CONTROL_SERVER -#define EMBER_AF_PLUGIN_ACCESS_CONTROL +#define MATTER_DM_PLUGIN_ACCESS_CONTROL_SERVER +#define MATTER_DM_PLUGIN_ACCESS_CONTROL // Use this macro to check if the server side of the Basic Information cluster is included #define ZCL_USING_BASIC_INFORMATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_BASIC_INFORMATION_SERVER -#define EMBER_AF_PLUGIN_BASIC_INFORMATION +#define MATTER_DM_PLUGIN_BASIC_INFORMATION_SERVER +#define MATTER_DM_PLUGIN_BASIC_INFORMATION // Use this macro to check if the client side of the OTA Software Update Provider cluster is included #define ZCL_USING_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_CLIENT -#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_PROVIDER_CLIENT +#define MATTER_DM_PLUGIN_OTA_SOFTWARE_UPDATE_PROVIDER_CLIENT // Use this macro to check if the server side of the OTA Software Update Requestor cluster is included #define ZCL_USING_OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR_SERVER -#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR +#define MATTER_DM_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR_SERVER +#define MATTER_DM_PLUGIN_OTA_SOFTWARE_UPDATE_REQUESTOR // Use this macro to check if the server side of the Localization Configuration cluster is included #define ZCL_USING_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_LOCALIZATION_CONFIGURATION_SERVER -#define EMBER_AF_PLUGIN_LOCALIZATION_CONFIGURATION +#define MATTER_DM_PLUGIN_LOCALIZATION_CONFIGURATION_SERVER +#define MATTER_DM_PLUGIN_LOCALIZATION_CONFIGURATION // Use this macro to check if the server side of the Time Format Localization cluster is included #define ZCL_USING_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_TIME_FORMAT_LOCALIZATION_SERVER -#define EMBER_AF_PLUGIN_TIME_FORMAT_LOCALIZATION +#define MATTER_DM_PLUGIN_TIME_FORMAT_LOCALIZATION_SERVER +#define MATTER_DM_PLUGIN_TIME_FORMAT_LOCALIZATION // Use this macro to check if the server side of the General Commissioning cluster is included #define ZCL_USING_GENERAL_COMMISSIONING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING_SERVER -#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING +#define MATTER_DM_PLUGIN_GENERAL_COMMISSIONING_SERVER +#define MATTER_DM_PLUGIN_GENERAL_COMMISSIONING // Use this macro to check if the server side of the Network Commissioning cluster is included #define ZCL_USING_NETWORK_COMMISSIONING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING_SERVER -#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING +#define MATTER_DM_PLUGIN_NETWORK_COMMISSIONING_SERVER +#define MATTER_DM_PLUGIN_NETWORK_COMMISSIONING // Use this macro to check if the server side of the Diagnostic Logs cluster is included #define ZCL_USING_DIAGNOSTIC_LOGS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_DIAGNOSTIC_LOGS_SERVER -#define EMBER_AF_PLUGIN_DIAGNOSTIC_LOGS +#define MATTER_DM_PLUGIN_DIAGNOSTIC_LOGS_SERVER +#define MATTER_DM_PLUGIN_DIAGNOSTIC_LOGS // Use this macro to check if the server side of the General Diagnostics cluster is included #define ZCL_USING_GENERAL_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GENERAL_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_GENERAL_DIAGNOSTICS +#define MATTER_DM_PLUGIN_GENERAL_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_GENERAL_DIAGNOSTICS // Use this macro to check if the server side of the Software Diagnostics cluster is included #define ZCL_USING_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS +#define MATTER_DM_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_SOFTWARE_DIAGNOSTICS // Use this macro to check if the server side of the Thread Network Diagnostics cluster is included #define ZCL_USING_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_THREAD_NETWORK_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_THREAD_NETWORK_DIAGNOSTICS +#define MATTER_DM_PLUGIN_THREAD_NETWORK_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_THREAD_NETWORK_DIAGNOSTICS // Use this macro to check if the server side of the WiFi Network Diagnostics cluster is included #define ZCL_USING_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS +#define MATTER_DM_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS // Use this macro to check if the server side of the Ethernet Network Diagnostics cluster is included #define ZCL_USING_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS_SERVER -#define EMBER_AF_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS +#define MATTER_DM_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS_SERVER +#define MATTER_DM_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS // Use this macro to check if the server side of the Switch cluster is included #define ZCL_USING_SWITCH_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_SWITCH_SERVER -#define EMBER_AF_PLUGIN_SWITCH +#define MATTER_DM_PLUGIN_SWITCH_SERVER +#define MATTER_DM_PLUGIN_SWITCH // Use this macro to check if the server side of the Administrator Commissioning cluster is included #define ZCL_USING_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_ADMINISTRATOR_COMMISSIONING_SERVER -#define EMBER_AF_PLUGIN_ADMINISTRATOR_COMMISSIONING +#define MATTER_DM_PLUGIN_ADMINISTRATOR_COMMISSIONING_SERVER +#define MATTER_DM_PLUGIN_ADMINISTRATOR_COMMISSIONING // Use this macro to check if the server side of the Operational Credentials cluster is included #define ZCL_USING_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS_SERVER -#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS +#define MATTER_DM_PLUGIN_OPERATIONAL_CREDENTIALS_SERVER +#define MATTER_DM_PLUGIN_OPERATIONAL_CREDENTIALS // Use this macro to check if the server side of the Group Key Management cluster is included #define ZCL_USING_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_GROUP_KEY_MANAGEMENT_SERVER -#define EMBER_AF_PLUGIN_GROUP_KEY_MANAGEMENT +#define MATTER_DM_PLUGIN_GROUP_KEY_MANAGEMENT_SERVER +#define MATTER_DM_PLUGIN_GROUP_KEY_MANAGEMENT // Use this macro to check if the server side of the Fixed Label cluster is included #define ZCL_USING_FIXED_LABEL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_FIXED_LABEL_SERVER -#define EMBER_AF_PLUGIN_FIXED_LABEL +#define MATTER_DM_PLUGIN_FIXED_LABEL_SERVER +#define MATTER_DM_PLUGIN_FIXED_LABEL // Use this macro to check if the server side of the User Label cluster is included #define ZCL_USING_USER_LABEL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_USER_LABEL_SERVER -#define EMBER_AF_PLUGIN_USER_LABEL +#define MATTER_DM_PLUGIN_USER_LABEL_SERVER +#define MATTER_DM_PLUGIN_USER_LABEL // Use this macro to check if the server side of the Color Control cluster is included #define ZCL_USING_COLOR_CONTROL_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER -#define EMBER_AF_PLUGIN_COLOR_CONTROL +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER +#define MATTER_DM_PLUGIN_COLOR_CONTROL // User options for server plugin Color Control -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV // Use this macro to check if the server side of the Occupancy Sensing cluster is included #define ZCL_USING_OCCUPANCY_SENSING_CLUSTER_SERVER -#define EMBER_AF_PLUGIN_OCCUPANCY_SENSING_SERVER -#define EMBER_AF_PLUGIN_OCCUPANCY_SENSING +#define MATTER_DM_PLUGIN_OCCUPANCY_SENSING_SERVER +#define MATTER_DM_PLUGIN_OCCUPANCY_SENSING diff --git a/src/app/clusters/account-login-server/account-login-server.cpp b/src/app/clusters/account-login-server/account-login-server.cpp index 1ba2218a69f737..9fc4b1511d35bb 100644 --- a/src/app/clusters/account-login-server/account-login-server.cpp +++ b/src/app/clusters/account-login-server/account-login-server.cpp @@ -49,7 +49,7 @@ using chip::Protocols::InteractionModel::Status; using LoggedOutEvent = chip::app::Clusters::AccountLogin::Events::LoggedOut::Type; static constexpr size_t kAccountLoginDeletageTableSize = - EMBER_AF_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kAccountLoginDeletageTableSize <= kEmberInvalidEndpointIndex, "AccountLogin Delegate table size error"); // ----------------------------------------------------------------------------- @@ -72,7 +72,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "AccountLogin NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, AccountLogin::Id, EMBER_AF_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, AccountLogin::Id, MATTER_DM_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kAccountLoginDeletageTableSize ? nullptr : gDelegateTable[ep]); } @@ -95,7 +95,7 @@ namespace AccountLogin { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, AccountLogin::Id, EMBER_AF_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, AccountLogin::Id, MATTER_DM_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kAccountLoginDeletageTableSize) { diff --git a/src/app/clusters/application-basic-server/application-basic-server.cpp b/src/app/clusters/application-basic-server/application-basic-server.cpp index 4c61cf11a3a97d..ca78bc31d7bc6f 100644 --- a/src/app/clusters/application-basic-server/application-basic-server.cpp +++ b/src/app/clusters/application-basic-server/application-basic-server.cpp @@ -45,7 +45,7 @@ using namespace chip::AppPlatform; #endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED static constexpr size_t kApplicationBasicDelegateTableSize = - EMBER_AF_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kApplicationBasicDelegateTableSize <= kEmberInvalidEndpointIndex, "ApplicationBasic Delegate table size error"); // ----------------------------------------------------------------------------- @@ -70,7 +70,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "ApplicationBasic NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, chip::app::Clusters::ApplicationBasic::Id, - EMBER_AF_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kApplicationBasicDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -93,7 +93,7 @@ namespace ApplicationBasic { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ApplicationBasic::Id, - EMBER_AF_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kApplicationBasicDelegateTableSize) { diff --git a/src/app/clusters/application-launcher-server/application-launcher-server.cpp b/src/app/clusters/application-launcher-server/application-launcher-server.cpp index 18442de56e5dcc..aa72d8ad499620 100644 --- a/src/app/clusters/application-launcher-server/application-launcher-server.cpp +++ b/src/app/clusters/application-launcher-server/application-launcher-server.cpp @@ -49,7 +49,7 @@ using namespace chip::AppPlatform; using namespace chip::Uint8; static constexpr size_t kApplicationLauncherDelegateTableSize = - EMBER_AF_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kApplicationLauncherDelegateTableSize <= kEmberInvalidEndpointIndex, "ApplicationLauncher Delegate table size error"); // ----------------------------------------------------------------------------- @@ -77,7 +77,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "ApplicationLauncher NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ApplicationLauncher::Id, - EMBER_AF_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kApplicationLauncherDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -100,7 +100,7 @@ namespace ApplicationLauncher { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ApplicationLauncher::Id, - EMBER_AF_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kApplicationLauncherDelegateTableSize) { diff --git a/src/app/clusters/audio-output-server/audio-output-server.cpp b/src/app/clusters/audio-output-server/audio-output-server.cpp index d73f340547ce47..f47fc528456a78 100644 --- a/src/app/clusters/audio-output-server/audio-output-server.cpp +++ b/src/app/clusters/audio-output-server/audio-output-server.cpp @@ -39,7 +39,7 @@ using namespace chip::app::Clusters::AudioOutput; using chip::Protocols::InteractionModel::Status; static constexpr size_t kAudioOutputDelegateTableSize = - EMBER_AF_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kAudioOutputDelegateTableSize <= kEmberInvalidEndpointIndex, "AudioOutput Delegate table size error"); // ----------------------------------------------------------------------------- @@ -54,7 +54,7 @@ Delegate * gDelegateTable[kAudioOutputDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, chip::app::Clusters::AudioOutput::Id, - EMBER_AF_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kAudioOutputDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -77,7 +77,7 @@ namespace AudioOutput { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, chip::app::Clusters::AudioOutput::Id, - EMBER_AF_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT); if (ep < kAudioOutputDelegateTableSize) { gDelegateTable[ep] = delegate; diff --git a/src/app/clusters/boolean-state-configuration-server/boolean-state-configuration-server.cpp b/src/app/clusters/boolean-state-configuration-server/boolean-state-configuration-server.cpp index 9ca68da511980d..8fa2f36d3a3aab 100644 --- a/src/app/clusters/boolean-state-configuration-server/boolean-state-configuration-server.cpp +++ b/src/app/clusters/boolean-state-configuration-server/boolean-state-configuration-server.cpp @@ -41,7 +41,7 @@ using chip::app::Clusters::BooleanStateConfiguration::Delegate; using chip::Protocols::InteractionModel::Status; static constexpr size_t kBooleanStateConfigurationDelegateTableSize = - EMBER_AF_BOOLEAN_STATE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_BOOLEAN_STATE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kBooleanStateConfigurationDelegateTableSize <= kEmberInvalidEndpointIndex, "BooleanStateConfiguration Delegate table size error"); @@ -57,7 +57,7 @@ Delegate * gDelegateTable[kBooleanStateConfigurationDelegateTableSize] = { nullp Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, BooleanStateConfiguration::Id, - EMBER_AF_BOOLEAN_STATE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_BOOLEAN_STATE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kBooleanStateConfigurationDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -234,7 +234,7 @@ namespace BooleanStateConfiguration { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, BooleanStateConfiguration::Id, - EMBER_AF_BOOLEAN_STATE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_BOOLEAN_STATE_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kBooleanStateConfigurationDelegateTableSize) { diff --git a/src/app/clusters/channel-server/channel-server.cpp b/src/app/clusters/channel-server/channel-server.cpp index 52d30083075d66..af977653da1749 100644 --- a/src/app/clusters/channel-server/channel-server.cpp +++ b/src/app/clusters/channel-server/channel-server.cpp @@ -39,7 +39,7 @@ using namespace chip::AppPlatform; using chip::Protocols::InteractionModel::Status; static constexpr size_t kChannelDelegateTableSize = - EMBER_AF_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kChannelDelegateTableSize <= kEmberInvalidEndpointIndex, "Channel Delegate table size error"); // ----------------------------------------------------------------------------- @@ -63,7 +63,7 @@ Delegate * GetDelegate(EndpointId endpoint) #endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED ChipLogProgress(Zcl, "Channel NOT returning ContentApp delegate for endpoint:%u", endpoint); - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Channel::Id, EMBER_AF_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Channel::Id, MATTER_DM_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kChannelDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -85,7 +85,7 @@ namespace Channel { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Channel::Id, EMBER_AF_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Channel::Id, MATTER_DM_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kChannelDelegateTableSize) { diff --git a/src/app/clusters/color-control-server/color-control-server.cpp b/src/app/clusters/color-control-server/color-control-server.cpp index 0f24ccd5b01e43..941f9d5a5f5842 100644 --- a/src/app/clusters/color-control-server/color-control-server.cpp +++ b/src/app/clusters/color-control-server/color-control-server.cpp @@ -26,7 +26,7 @@ #include #include -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT #include #endif @@ -60,7 +60,7 @@ constexpr uint8_t kExecuteIfOff = 1; } // namespace app } // namespace chip -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl { public: @@ -206,19 +206,19 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl ReturnErrorOnFailure(attributeValueList.ComputeSize(&attributeCount)); VerifyOrReturnError(attributeCount <= kColorControlScenableAttributesCount, CHIP_ERROR_BUFFER_TOO_SMALL); // Retrieve the buffers for different modes -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::ColorHueTransitionState * colorHueTransitionState = ColorControlServer::Instance().getColorHueTransitionState(endpoint); ColorControlServer::Color16uTransitionState * colorSaturationTransitionState = ColorControlServer::Instance().getSaturationTransitionState(endpoint); #endif -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY ColorControlServer::Color16uTransitionState * colorXTransitionState = ColorControlServer::Instance().getXTransitionState(endpoint); ColorControlServer::Color16uTransitionState * colorYTransitionState = ColorControlServer::Instance().getYTransitionState(endpoint); #endif -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP ColorControlServer::Color16uTransitionState * colorTempTransitionState = ColorControlServer::Instance().getTempTransitionState(endpoint); #endif @@ -319,29 +319,29 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl switch (targetColorMode) { case ColorControl::EnhancedColorMode::kCurrentHueAndCurrentSaturation: -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::Instance().moveToSaturation(static_cast(colorSaturationTransitionState->finalValue), transitionTime10th, endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; case ColorControl::EnhancedColorMode::kCurrentXAndCurrentY: -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY ColorControlServer::Instance().moveToColor(colorXTransitionState->finalValue, colorYTransitionState->finalValue, transitionTime10th, endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY break; case ColorControl::EnhancedColorMode::kColorTemperature: -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP ColorControlServer::Instance().moveToColorTemp( endpoint, static_cast(colorTempTransitionState->finalValue), transitionTime10th); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP break; case ColorControl::EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::Instance().moveToHueAndSaturation( colorHueTransitionState->finalEnhancedHue, static_cast(colorSaturationTransitionState->finalValue), transitionTime10th, true, endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; default: return CHIP_ERROR_INVALID_ARGUMENT; @@ -381,7 +381,7 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl } }; static DefaultColorControlSceneHandler sColorControlSceneHandler; -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS /********************************************************** * Matter timer scheduling glue logic @@ -435,11 +435,11 @@ ColorControlServer & ColorControlServer::Instance() chip::scenes::SceneHandler * ColorControlServer::GetSceneHandler() { -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS return &sColorControlSceneHandler; #else return nullptr; -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS } bool ColorControlServer::HasFeature(chip::EndpointId endpoint, Feature feature) @@ -470,7 +470,7 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c { status = stopAllColorTransitions(endpoint); -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV // Because Hue and Saturation have separate transitions and can be kicked separately, // a new command specific to Hue could resume an old unfinished Saturation transition. Or vice versa. // Init both transition states on stop command to prevent that. @@ -481,7 +481,7 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c initHueTransitionState(endpoint, hueState, false /*isEnhancedHue don't care*/); initSaturationTransitionState(endpoint, saturationState); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV } commandObj->AddStatus(commandPath, status); @@ -666,7 +666,7 @@ uint16_t ColorControlServer::computeTransitionTimeFromStateAndRate(ColorControlS EmberEventControl * ColorControlServer::getEventControl(EndpointId endpoint) { uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); EmberEventControl * event = nullptr; if (index < ArraySize(eventControls)) @@ -785,7 +785,7 @@ bool ColorControlServer::computeNewColor16uValue(ColorControlServer::Color16uTra return false; } -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV /** * @brief Returns ColorHueTransititionState associated to an endpoint @@ -796,7 +796,7 @@ bool ColorControlServer::computeNewColor16uValue(ColorControlServer::Color16uTra ColorControlServer::ColorHueTransitionState * ColorControlServer::getColorHueTransitionState(EndpointId endpoint) { uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); ColorHueTransitionState * state = nullptr; if (index < ArraySize(colorHueTransitionStates)) @@ -815,7 +815,7 @@ ColorControlServer::ColorHueTransitionState * ColorControlServer::getColorHueTra ColorControlServer::Color16uTransitionState * ColorControlServer::getSaturationTransitionState(EndpointId endpoint) { uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); Color16uTransitionState * state = nullptr; if (index < ArraySize(colorSatTransitionStates)) @@ -1611,9 +1611,9 @@ bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * com return true; } Status status = moveToHueAndSaturation(hue, saturation, transitionTime, isEnhanced, commandPath.mEndpointId); -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT commandObj->AddStatus(commandPath, status); return true; } @@ -1819,9 +1819,9 @@ bool ColorControlServer::moveToSaturationCommand(app::CommandHandler * commandOb return true; } Status status = moveToSaturation(commandData.saturation, commandData.transitionTime, commandPath.mEndpointId); -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT commandObj->AddStatus(commandPath, status); return true; } @@ -2005,9 +2005,9 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons } exit: -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT commandObj->AddStatus(commandPath, status); return true; } @@ -2070,9 +2070,9 @@ void ColorControlServer::updateHueSatCommand(EndpointId endpoint) computePwmFromHsv(endpoint); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY /** * @brief Returns Color16uTransitionState for X color associated to an endpoint @@ -2083,7 +2083,7 @@ void ColorControlServer::updateHueSatCommand(EndpointId endpoint) ColorControlServer::Color16uTransitionState * ColorControlServer::getXTransitionState(EndpointId endpoint) { uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); Color16uTransitionState * state = nullptr; if (index < ArraySize(colorXtransitionStates)) @@ -2103,7 +2103,7 @@ ColorControlServer::Color16uTransitionState * ColorControlServer::getXTransition ColorControlServer::Color16uTransitionState * ColorControlServer::getYTransitionState(EndpointId endpoint) { uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); Color16uTransitionState * state = nullptr; if (index < ArraySize(colorYtransitionStates)) @@ -2215,9 +2215,9 @@ bool ColorControlServer::moveToColorCommand(app::CommandHandler * commandObj, co } Status status = moveToColor(commandData.colorX, commandData.colorY, commandData.transitionTime, commandPath.mEndpointId); -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT commandObj->AddStatus(commandPath, status); return true; } @@ -2423,9 +2423,9 @@ void ColorControlServer::updateXYCommand(EndpointId endpoint) computePwmFromXy(endpoint); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP /** * @brief Get the Temp Transition State object associated to the endpoint * @@ -2435,7 +2435,7 @@ void ColorControlServer::updateXYCommand(EndpointId endpoint) ColorControlServer::Color16uTransitionState * ColorControlServer::getTempTransitionState(EndpointId endpoint) { uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ColorControl::Id, MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); Color16uTransitionState * state = nullptr; if (index < ArraySize(colorTempTransitionStates)) @@ -2760,9 +2760,9 @@ bool ColorControlServer::moveToColorTempCommand(app::CommandHandler * commandObj } Status status = moveToColorTemp(commandPath.mEndpointId, commandData.colorTemperatureMireds, commandData.transitionTime); -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT commandObj->AddStatus(commandPath, status); return true; } @@ -2943,13 +2943,13 @@ void ColorControlServer::levelControlColorTempChangeCommand(EndpointId endpoint) } } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP /********************************************************** * Callbacks Implementation *********************************************************/ -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV bool emberAfColorControlClusterMoveHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveHue::DecodableType & commandData) @@ -3046,9 +3046,9 @@ bool emberAfColorControlClusterColorLoopSetCallback(app::CommandHandler * comman return ColorControlServer::Instance().colorLoopCommand(commandObj, commandPath, commandData); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY bool emberAfColorControlClusterMoveToColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToColor::DecodableType & commandData) @@ -3068,9 +3068,9 @@ bool emberAfColorControlClusterStepColorCallback(app::CommandHandler * commandOb return ColorControlServer::Instance().stepColorCommand(commandObj, commandPath, commandData); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP bool emberAfColorControlClusterMoveToColorTemperatureCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, @@ -3098,7 +3098,7 @@ void emberAfPluginLevelControlCoupledColorTempChangeCallback(EndpointId endpoint ColorControlServer::Instance().levelControlColorTempChangeCommand(endpoint); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP bool emberAfColorControlClusterStopMoveStepCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StopMoveStep::DecodableType & commandData) @@ -3109,14 +3109,14 @@ bool emberAfColorControlClusterStopMoveStepCallback(app::CommandHandler * comman void emberAfColorControlClusterServerInitCallback(EndpointId endpoint) { -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP ColorControlServer::Instance().startUpColorTempCommand(endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS // Registers Scene handlers for the color control cluster on the server app::Clusters::ScenesManagement::ScenesServer::Instance().RegisterSceneHandler( endpoint, ColorControlServer::Instance().GetSceneHandler()); -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS } void MatterColorControlClusterServerShutdownCallback(EndpointId endpoint) @@ -3125,7 +3125,7 @@ void MatterColorControlClusterServerShutdownCallback(EndpointId endpoint) ColorControlServer::Instance().cancelEndpointTimerCallback(endpoint); } -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP /** * @brief Callback for temperature update when timer is finished * @@ -3135,9 +3135,9 @@ void emberAfPluginColorControlServerTempTransitionEventHandler(EndpointId endpoi { ColorControlServer::Instance().updateTempCommand(endpoint); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY /** * @brief Callback for color update when timer is finished * @@ -3147,9 +3147,9 @@ void emberAfPluginColorControlServerXyTransitionEventHandler(EndpointId endpoint { ColorControlServer::Instance().updateXYCommand(endpoint); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV /** * @brief Callback for color hue and saturation update when timer is finished * @@ -3159,6 +3159,6 @@ void emberAfPluginColorControlServerHueSatTransitionEventHandler(EndpointId endp { ColorControlServer::Instance().updateHueSatCommand(endpoint); } -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV void MatterColorControlPluginServerInitCallback() {} diff --git a/src/app/clusters/color-control-server/color-control-server.h b/src/app/clusters/color-control-server/color-control-server.h index 56110a33373f8d..5c13c5619c82cf 100644 --- a/src/app/clusters/color-control-server/color-control-server.h +++ b/src/app/clusters/color-control-server/color-control-server.h @@ -141,7 +141,7 @@ class ColorControlServer bool stopMoveStepCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, uint8_t optionsMask, uint8_t optionsOverride); -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV bool moveHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, HueMoveMode moveMode, uint16_t rate, uint8_t optionsMask, uint8_t optionsOverride, bool isEnhanced); bool moveToHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, uint16_t hue, @@ -162,9 +162,9 @@ class ColorControlServer bool colorLoopCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::ColorControl::Commands::ColorLoopSet::DecodableType & commandData); void updateHueSatCommand(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY bool moveToColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::ColorControl::Commands::MoveToColor::DecodableType & commandData); bool moveColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, @@ -172,9 +172,9 @@ class ColorControlServer bool stepColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::ColorControl::Commands::StepColor::DecodableType & commandData); void updateXYCommand(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP bool moveColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::ColorControl::Commands::MoveColorTemperature::DecodableType & commandData); bool @@ -185,7 +185,7 @@ class ColorControlServer void levelControlColorTempChangeCommand(chip::EndpointId endpoint); void startUpColorTempCommand(chip::EndpointId endpoint); void updateTempCommand(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP void cancelEndpointTimerCallback(chip::EndpointId endpoint); @@ -209,7 +209,7 @@ class ColorControlServer void scheduleTimerCallbackMs(EmberEventControl * control, uint32_t delayMs); void cancelEndpointTimerCallback(EmberEventControl * control); -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV chip::Protocols::InteractionModel::Status moveToSaturation(uint8_t saturation, uint16_t transitionTime, chip::EndpointId endpoint); chip::Protocols::InteractionModel::Status moveToHueAndSaturation(uint16_t hue, uint8_t saturation, uint16_t transitionTime, @@ -229,46 +229,46 @@ class ColorControlServer void SetHSVRemainingTime(chip::EndpointId endpoint); bool computeNewHueValue(ColorHueTransitionState * p); EmberEventControl * configureHSVEventControl(chip::EndpointId); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY chip::Protocols::InteractionModel::Status moveToColor(uint16_t colorX, uint16_t colorY, uint16_t transitionTime, chip::EndpointId endpoint); Color16uTransitionState * getXTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getYTransitionState(chip::EndpointId endpoint); uint16_t findNewColorValueFromStep(uint16_t oldValue, int16_t step); EmberEventControl * configureXYEventControl(chip::EndpointId); -#endif // #ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP Color16uTransitionState * getTempTransitionState(chip::EndpointId endpoint); chip::Protocols::InteractionModel::Status moveToColorTemp(chip::EndpointId aEndpoint, uint16_t colorTemperature, uint16_t transitionTime); uint16_t getTemperatureCoupleToLevelMin(chip::EndpointId endpoint); EmberEventControl * configureTempEventControl(chip::EndpointId); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP /********************************************************** * Attributes Declaration *********************************************************/ static ColorControlServer instance; static constexpr size_t kColorControlClusterServerMaxEndpointCount = - EMBER_AF_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_COLOR_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kColorControlClusterServerMaxEndpointCount <= kEmberInvalidEndpointIndex, "ColorControl endpoint count error"); -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorHueTransitionState colorHueTransitionStates[kColorControlClusterServerMaxEndpointCount]; Color16uTransitionState colorSatTransitionStates[kColorControlClusterServerMaxEndpointCount]; #endif -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY Color16uTransitionState colorXtransitionStates[kColorControlClusterServerMaxEndpointCount]; Color16uTransitionState colorYtransitionStates[kColorControlClusterServerMaxEndpointCount]; -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP Color16uTransitionState colorTempTransitionStates[kColorControlClusterServerMaxEndpointCount]; -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP EmberEventControl eventControls[kColorControlClusterServerMaxEndpointCount]; @@ -279,18 +279,18 @@ class ColorControlServer * Callbacks *********************************************************/ -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP void emberAfPluginColorControlServerTempTransitionEventHandler(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY void emberAfPluginColorControlServerXyTransitionEventHandler(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV void emberAfPluginColorControlServerHueSatTransitionEventHandler(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP void emberAfPluginLevelControlCoupledColorTempChangeCallback(chip::EndpointId endpoint); -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP diff --git a/src/app/clusters/content-app-observer/content-app-observer.cpp b/src/app/clusters/content-app-observer/content-app-observer.cpp index 26739027b494af..08ed95c10aa679 100644 --- a/src/app/clusters/content-app-observer/content-app-observer.cpp +++ b/src/app/clusters/content-app-observer/content-app-observer.cpp @@ -46,7 +46,7 @@ using chip::app::Clusters::ContentAppObserver::Delegate; using chip::Protocols::InteractionModel::Status; static constexpr size_t kContentAppObserverDeletageTableSize = - EMBER_AF_CONTENT_APP_OBSERVER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_CONTENT_APP_OBSERVER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kContentAppObserverDeletageTableSize <= kEmberInvalidEndpointIndex, "ContentAppObserver Delegate table size error"); // ----------------------------------------------------------------------------- @@ -69,7 +69,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "ContentAppObserver NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ContentAppObserver::Id, - EMBER_AF_CONTENT_APP_OBSERVER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_CONTENT_APP_OBSERVER_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kContentAppObserverDeletageTableSize ? nullptr : gDelegateTable[ep]); } @@ -92,7 +92,7 @@ namespace ContentAppObserver { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ContentAppObserver::Id, - EMBER_AF_CONTENT_APP_OBSERVER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_CONTENT_APP_OBSERVER_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kContentAppObserverDeletageTableSize) { diff --git a/src/app/clusters/content-control-server/content-control-server.cpp b/src/app/clusters/content-control-server/content-control-server.cpp index 1434e25000f389..60c30f4b71845a 100644 --- a/src/app/clusters/content-control-server/content-control-server.cpp +++ b/src/app/clusters/content-control-server/content-control-server.cpp @@ -49,7 +49,7 @@ using chip::Protocols::InteractionModel::Status; using RemainingScreenTimeExpiredEvent = chip::app::Clusters::ContentControl::Events::RemainingScreenTimeExpired::Type; static constexpr size_t kContentControlDeletageTableSize = - EMBER_AF_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kContentControlDeletageTableSize <= kEmberInvalidEndpointIndex, "ContentControl Delegate table size error"); // ----------------------------------------------------------------------------- @@ -72,7 +72,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "ContentControl NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, ContentControl::Id, EMBER_AF_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ContentControl::Id, MATTER_DM_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kContentControlDeletageTableSize ? nullptr : gDelegateTable[ep]); } @@ -95,7 +95,7 @@ namespace ContentControl { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, ContentControl::Id, EMBER_AF_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ContentControl::Id, MATTER_DM_CONTENT_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kContentControlDeletageTableSize) { diff --git a/src/app/clusters/content-launch-server/content-launch-server.cpp b/src/app/clusters/content-launch-server/content-launch-server.cpp index 405ec7b427f373..d9bba198a9df5c 100644 --- a/src/app/clusters/content-launch-server/content-launch-server.cpp +++ b/src/app/clusters/content-launch-server/content-launch-server.cpp @@ -44,7 +44,7 @@ using namespace chip::AppPlatform; using chip::Protocols::InteractionModel::Status; static constexpr size_t kContentLaunchDelegateTableSize = - EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kContentLaunchDelegateTableSize < kEmberInvalidEndpointIndex, "ContentLaunch Delegate table size error"); // ----------------------------------------------------------------------------- @@ -69,7 +69,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "Content Launcher NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ContentLauncher::Id, - EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kContentLaunchDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -92,7 +92,7 @@ namespace ContentLauncher { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ContentLauncher::Id, - EMBER_AF_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_CONTENT_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kContentLaunchDelegateTableSize) { diff --git a/src/app/clusters/diagnostic-logs-server/diagnostic-logs-server.cpp b/src/app/clusters/diagnostic-logs-server/diagnostic-logs-server.cpp index 5d7de3b077a982..95d9a332819ae3 100644 --- a/src/app/clusters/diagnostic-logs-server/diagnostic-logs-server.cpp +++ b/src/app/clusters/diagnostic-logs-server/diagnostic-logs-server.cpp @@ -24,9 +24,9 @@ #include "BDXDiagnosticLogsProvider.h" -#ifdef EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT +#ifdef MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT static constexpr size_t kDiagnosticLogsDiagnosticLogsProviderDelegateTableSize = - EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kDiagnosticLogsDiagnosticLogsProviderDelegateTableSize < kEmberInvalidEndpointIndex, "DiagnosticLogs: log provider delegate table size error"); @@ -49,7 +49,7 @@ DiagnosticLogsProviderDelegate * gDiagnosticLogsProviderDelegateTable[kDiagnosti DiagnosticLogsProviderDelegate * GetDiagnosticLogsProviderDelegate(EndpointId endpoint) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Id, EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Id, MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT); auto delegate = (ep >= ArraySize(gDiagnosticLogsProviderDelegateTable) ? nullptr : gDiagnosticLogsProviderDelegateTable[ep]); if (delegate == nullptr) @@ -89,7 +89,7 @@ DiagnosticLogsServer DiagnosticLogsServer::sInstance; void DiagnosticLogsServer::SetDiagnosticLogsProviderDelegate(EndpointId endpoint, DiagnosticLogsProviderDelegate * delegate) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Id, EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, Id, MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT); if (ep < kDiagnosticLogsDiagnosticLogsProviderDelegateTableSize) { gDiagnosticLogsProviderDelegateTable[ep] = delegate; @@ -187,4 +187,4 @@ bool emberAfDiagnosticLogsClusterRetrieveLogsRequestCallback(chip::app::CommandH } void MatterDiagnosticLogsPluginServerInitCallback() {} -#endif // #ifdef EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT +#endif // #ifdef MATTER_DM_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT diff --git a/src/app/clusters/dishwasher-alarm-server/dishwasher-alarm-server.cpp b/src/app/clusters/dishwasher-alarm-server/dishwasher-alarm-server.cpp index a89bf17ae4ef9c..aaed13bbded7e4 100644 --- a/src/app/clusters/dishwasher-alarm-server/dishwasher-alarm-server.cpp +++ b/src/app/clusters/dishwasher-alarm-server/dishwasher-alarm-server.cpp @@ -36,7 +36,7 @@ using chip::Protocols::InteractionModel::Status; using namespace std; static constexpr size_t kDishwasherAlarmDelegateTableSize = - EMBER_AF_DISHWASHER_ALARM_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_DISHWASHER_ALARM_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kDishwasherAlarmDelegateTableSize <= kEmberInvalidEndpointIndex, "Dishwasher Alarm Delegate table size error"); @@ -50,14 +50,14 @@ Delegate * gDelegateTable[kDishwasherAlarmDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, DishwasherAlarm::Id, - EMBER_AF_DISHWASHER_ALARM_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_DISHWASHER_ALARM_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kDishwasherAlarmDelegateTableSize ? nullptr : gDelegateTable[ep]); } void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, DishwasherAlarm::Id, - EMBER_AF_DISHWASHER_ALARM_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_DISHWASHER_ALARM_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kDishwasherAlarmDelegateTableSize) { diff --git a/src/app/clusters/door-lock-server/door-lock-server.cpp b/src/app/clusters/door-lock-server/door-lock-server.cpp index b4df96a8e50f4c..fe7bfa76b5e8ef 100644 --- a/src/app/clusters/door-lock-server/door-lock-server.cpp +++ b/src/app/clusters/door-lock-server/door-lock-server.cpp @@ -51,7 +51,7 @@ static constexpr uint8_t DOOR_LOCK_ALIRO_CREDENTIAL_SIZE = 65; static constexpr uint32_t DOOR_LOCK_MAX_LOCK_TIMEOUT_SEC = MAX_INT32U_VALUE / MILLISECOND_TICKS_PER_SECOND; static constexpr size_t kDoorLockDelegateTableSize = - EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kDoorLockDelegateTableSize <= kEmberInvalidEndpointIndex, "Door Lock Delegate table size error"); @@ -64,13 +64,13 @@ Delegate * gDelegateTable[kDoorLockDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, DoorLock::Id, EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, DoorLock::Id, MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kDoorLockDelegateTableSize ? nullptr : gDelegateTable[ep]); } void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, DoorLock::Id, EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, DoorLock::Id, MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < ArraySize(gDelegateTable)) { @@ -3424,7 +3424,7 @@ void DoorLockServer::sendClusterResponse(chip::app::CommandHandler * commandObj, EmberAfDoorLockEndpointContext * DoorLockServer::getContext(chip::EndpointId endpointId) { - auto index = emberAfGetClusterServerEndpointIndex(endpointId, ::Id, EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); + auto index = emberAfGetClusterServerEndpointIndex(endpointId, ::Id, MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT); if (index < kDoorLockClusterServerMaxEndpointCount) { return &mEndpointCtx[index]; diff --git a/src/app/clusters/door-lock-server/door-lock-server.h b/src/app/clusters/door-lock-server/door-lock-server.h index 6f25cd507621bf..9b1a7f6fd27791 100644 --- a/src/app/clusters/door-lock-server/door-lock-server.h +++ b/src/app/clusters/door-lock-server/door-lock-server.h @@ -706,7 +706,7 @@ class DoorLockServer : public chip::app::AttributeAccessInterface const chip::app::Clusters::DoorLock::Commands::ClearAliroReaderConfig::DecodableType & commandData); static constexpr size_t kDoorLockClusterServerMaxEndpointCount = - EMBER_AF_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_DOOR_LOCK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kDoorLockClusterServerMaxEndpointCount <= kEmberInvalidEndpointIndex, "DoorLock Endpoint count error"); std::array mEndpointCtx; diff --git a/src/app/clusters/electrical-energy-measurement-server/electrical-energy-measurement-server.cpp b/src/app/clusters/electrical-energy-measurement-server/electrical-energy-measurement-server.cpp index 38911ff7e54358..a26e1a33844bef 100644 --- a/src/app/clusters/electrical-energy-measurement-server/electrical-energy-measurement-server.cpp +++ b/src/app/clusters/electrical-energy-measurement-server/electrical-energy-measurement-server.cpp @@ -35,8 +35,8 @@ using namespace chip; using namespace chip::app::Clusters::ElectricalEnergyMeasurement::Attributes; using namespace chip::app::Clusters::ElectricalEnergyMeasurement::Structs; -MeasurementData - gMeasurements[EMBER_AF_ELECTRICAL_ENERGY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT]; +MeasurementData gMeasurements[MATTER_DM_ELECTRICAL_ENERGY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT + + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT]; CHIP_ERROR ElectricalEnergyMeasurementAttrAccess::Init() { @@ -143,14 +143,14 @@ bool ElectricalEnergyMeasurementAttrAccess::SupportsOptAttr(OptionalAttributes a MeasurementData * MeasurementDataForEndpoint(EndpointId endpointId) { auto index = emberAfGetClusterServerEndpointIndex(endpointId, app::Clusters::ElectricalEnergyMeasurement::Id, - EMBER_AF_ELECTRICAL_ENERGY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_ELECTRICAL_ENERGY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT); if (index == kEmberInvalidEndpointIndex) { return nullptr; } - if (index >= EMBER_AF_ELECTRICAL_ENERGY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT) + if (index >= MATTER_DM_ELECTRICAL_ENERGY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT) { ChipLogError(NotSpecified, "Internal error: invalid/unexpected energy measurement index."); return nullptr; diff --git a/src/app/clusters/fan-control-server/fan-control-server.cpp b/src/app/clusters/fan-control-server/fan-control-server.cpp index 8359e03610b96e..4ed216b9cad088 100644 --- a/src/app/clusters/fan-control-server/fan-control-server.cpp +++ b/src/app/clusters/fan-control-server/fan-control-server.cpp @@ -45,7 +45,7 @@ using namespace chip::app::Clusters::FanControl::Attributes; namespace { constexpr size_t kFanControlDelegateTableSize = - EMBER_AF_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kFanControlDelegateTableSize <= kEmberInvalidEndpointIndex, "FanControl Delegate table size error"); @@ -61,14 +61,14 @@ namespace FanControl { Delegate * GetDelegate(EndpointId aEndpoint) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(aEndpoint, FanControl::Id, EMBER_AF_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(aEndpoint, FanControl::Id, MATTER_DM_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kFanControlDelegateTableSize ? nullptr : gDelegateTable[ep]); } void SetDefaultDelegate(EndpointId aEndpoint, Delegate * aDelegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(aEndpoint, FanControl::Id, EMBER_AF_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(aEndpoint, FanControl::Id, MATTER_DM_FAN_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kFanControlDelegateTableSize) { diff --git a/src/app/clusters/groups-server/groups-server.cpp b/src/app/clusters/groups-server/groups-server.cpp index a6d502acb18e52..d591c3f3d6e331 100644 --- a/src/app/clusters/groups-server/groups-server.cpp +++ b/src/app/clusters/groups-server/groups-server.cpp @@ -30,9 +30,9 @@ #include #include -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT #include -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT using namespace chip; using namespace app::Clusters; @@ -292,7 +292,7 @@ bool emberAfGroupsClusterRemoveGroupCallback(app::CommandHandler * commandObj, c auto fabricIndex = commandObj->GetAccessingFabricIndex(); Groups::Commands::RemoveGroupResponse::Type response; -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT // If a group is removed the scenes associated with that group SHOULD be removed. ScenesManagement::ScenesServer::Instance().GroupWillBeRemoved(fabricIndex, commandPath.mEndpointId, commandData.groupID); #endif @@ -313,7 +313,7 @@ bool emberAfGroupsClusterRemoveAllGroupsCallback(app::CommandHandler * commandOb VerifyOrExit(nullptr != provider, status = Status::Failure); -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT { GroupDataProvider::EndpointIterator * iter = provider->IterateEndpoints(fabricIndex); GroupDataProvider::GroupEndpoint mapping; diff --git a/src/app/clusters/keypad-input-server/keypad-input-server.cpp b/src/app/clusters/keypad-input-server/keypad-input-server.cpp index bf33427bfcd371..e298a2cb3f2392 100644 --- a/src/app/clusters/keypad-input-server/keypad-input-server.cpp +++ b/src/app/clusters/keypad-input-server/keypad-input-server.cpp @@ -47,7 +47,7 @@ using namespace chip::AppPlatform; using chip::Protocols::InteractionModel::Status; static constexpr size_t kKeypadInputDelegateTableSize = - EMBER_AF_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kKeypadInputDelegateTableSize < kEmberInvalidEndpointIndex, "KeypadInput Delegate table size error"); // ----------------------------------------------------------------------------- @@ -72,7 +72,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "KeypadInput NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, KeypadInput::Id, EMBER_AF_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, KeypadInput::Id, MATTER_DM_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kKeypadInputDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -95,7 +95,7 @@ namespace KeypadInput { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, KeypadInput::Id, EMBER_AF_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, KeypadInput::Id, MATTER_DM_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kKeypadInputDelegateTableSize) { diff --git a/src/app/clusters/laundry-dryer-controls-server/laundry-dryer-controls-server.cpp b/src/app/clusters/laundry-dryer-controls-server/laundry-dryer-controls-server.cpp index 3c3bc524269da7..b672f953a16d56 100644 --- a/src/app/clusters/laundry-dryer-controls-server/laundry-dryer-controls-server.cpp +++ b/src/app/clusters/laundry-dryer-controls-server/laundry-dryer-controls-server.cpp @@ -43,7 +43,7 @@ using namespace chip::app::Clusters::LaundryDryerControls::Attributes; using chip::Protocols::InteractionModel::Status; static constexpr size_t kLaundryDryerControlsDelegateTableSize = - EMBER_AF_LAUNDRY_DRYER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_LAUNDRY_DRYER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; // ----------------------------------------------------------------------------- // Delegate Implementation @@ -56,7 +56,7 @@ namespace { Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, LaundryDryerControls::Id, - EMBER_AF_LAUNDRY_DRYER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LAUNDRY_DRYER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kLaundryDryerControlsDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -70,7 +70,7 @@ LaundryDryerControlsServer LaundryDryerControlsServer::sInstance; void LaundryDryerControlsServer::SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, LaundryDryerControls::Id, - EMBER_AF_LAUNDRY_DRYER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LAUNDRY_DRYER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kLaundryDryerControlsDelegateTableSize) { diff --git a/src/app/clusters/laundry-washer-controls-server/laundry-washer-controls-server.cpp b/src/app/clusters/laundry-washer-controls-server/laundry-washer-controls-server.cpp index a22e86ffe2e108..7800f075d159b7 100644 --- a/src/app/clusters/laundry-washer-controls-server/laundry-washer-controls-server.cpp +++ b/src/app/clusters/laundry-washer-controls-server/laundry-washer-controls-server.cpp @@ -42,7 +42,7 @@ using namespace chip::app::Clusters::LaundryWasherControls::Attributes; using chip::Protocols::InteractionModel::Status; static constexpr size_t kLaundryWasherControlsDelegateTableSize = - EMBER_AF_LAUNDRY_WASHER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_LAUNDRY_WASHER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; // ----------------------------------------------------------------------------- // Delegate Implementation @@ -55,7 +55,7 @@ namespace { Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, LaundryWasherControls::Id, - EMBER_AF_LAUNDRY_WASHER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LAUNDRY_WASHER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kLaundryWasherControlsDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -69,7 +69,7 @@ LaundryWasherControlsServer LaundryWasherControlsServer::sInstance; void LaundryWasherControlsServer::SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, LaundryWasherControls::Id, - EMBER_AF_LAUNDRY_WASHER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LAUNDRY_WASHER_CONTROLS_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kLaundryWasherControlsDelegateTableSize) { diff --git a/src/app/clusters/level-control/level-control.cpp b/src/app/clusters/level-control/level-control.cpp index f3f31d58982d93..5838f604085c56 100644 --- a/src/app/clusters/level-control/level-control.cpp +++ b/src/app/clusters/level-control/level-control.cpp @@ -35,17 +35,17 @@ #include #include -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT #include -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT -#ifdef EMBER_AF_PLUGIN_ON_OFF +#ifdef MATTER_DM_PLUGIN_ON_OFF #include -#endif // EMBER_AF_PLUGIN_ON_OFF +#endif // MATTER_DM_PLUGIN_ON_OFF -#ifdef EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP #include -#endif // EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP #include @@ -58,11 +58,11 @@ using chip::Protocols::InteractionModel::Status; static bool areStartUpLevelControlServerAttributesNonVolatile(EndpointId endpoint); #endif // IGNORE_LEVEL_CONTROL_CLUSTER_START_UP_CURRENT_LEVEL -#if (EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE == 0) +#if (MATTER_DM_PLUGIN_LEVEL_CONTROL_RATE == 0) #define FASTEST_TRANSITION_TIME_MS 0 #else -#define FASTEST_TRANSITION_TIME_MS (MILLISECOND_TICKS_PER_SECOND / EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE) -#endif // EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE +#define FASTEST_TRANSITION_TIME_MS (MILLISECOND_TICKS_PER_SECOND / MATTER_DM_PLUGIN_LEVEL_CONTROL_RATE) +#endif // MATTER_DM_PLUGIN_LEVEL_CONTROL_RATE #define LEVEL_CONTROL_LIGHTING_MIN_LEVEL 0x01 #define LEVEL_CONTROL_LIGHTING_MAX_LEVEL 0xFE @@ -73,7 +73,7 @@ static bool areStartUpLevelControlServerAttributesNonVolatile(EndpointId endpoin #define STARTUP_CURRENT_LEVEL_USE_PREVIOUS_LEVEL 0xFF static constexpr size_t kLevelControlStateTableSize = - EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kLevelControlStateTableSize <= kEmberInvalidEndpointIndex, "LevelControl state table size error"); struct CallbackScheduleState @@ -121,7 +121,7 @@ static void writeRemainingTime(EndpointId endpoint, uint16_t remainingTimeMs); static bool shouldExecuteIfOff(EndpointId endpoint, CommandId commandId, chip::Optional> optionsMask, chip::Optional> optionsOverride); -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS class DefaultLevelControlSceneHandler : public scenes::DefaultSceneHandlerImpl { public: @@ -255,14 +255,14 @@ class DefaultLevelControlSceneHandler : public scenes::DefaultSceneHandlerImpl }; static DefaultLevelControlSceneHandler sLevelControlSceneHandler; -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS -#if !defined(IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS) && defined(EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP) +#if !defined(IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS) && defined(MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP) static void reallyUpdateCoupledColorTemp(EndpointId endpoint); #define updateCoupledColorTemp(endpoint) reallyUpdateCoupledColorTemp(endpoint) #else #define updateCoupledColorTemp(endpoint) -#endif // IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS && EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS && MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP void emberAfLevelControlClusterServerTickCallback(EndpointId endpoint); @@ -330,11 +330,11 @@ static void cancelEndpointTimerCallback(EndpointId endpoint) static EmberAfLevelControlState * getState(EndpointId endpoint) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, LevelControl::Id, EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, LevelControl::Id, MATTER_DM_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kLevelControlStateTableSize ? nullptr : &stateTable[ep]); } -#if !defined(IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS) && defined(EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP) +#if !defined(IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS) && defined(MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP) static void reallyUpdateCoupledColorTemp(EndpointId endpoint) { LevelControl::Attributes::Options::TypeInfo::Type options; @@ -353,7 +353,7 @@ static void reallyUpdateCoupledColorTemp(EndpointId endpoint) } } } -#endif // IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS && EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#endif // IGNORE_LEVEL_CONTROL_CLUSTER_OPTIONS && MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP void emberAfLevelControlClusterServerTickCallback(EndpointId endpoint) { @@ -481,13 +481,13 @@ static void writeRemainingTime(EndpointId endpoint, uint16_t remainingTimeMs) static void setOnOffValue(EndpointId endpoint, bool onOff) { -#ifdef EMBER_AF_PLUGIN_ON_OFF +#ifdef MATTER_DM_PLUGIN_ON_OFF if (emberAfContainsServer(endpoint, OnOff::Id)) { ChipLogProgress(Zcl, "Setting on/off to %s due to level change", onOff ? "ON" : "OFF"); OnOffServer::Instance().setOnOffValue(endpoint, (onOff ? OnOff::Commands::On::Id : OnOff::Commands::Off::Id), true); } -#endif // EMBER_AF_PLUGIN_ON_OFF +#endif // MATTER_DM_PLUGIN_ON_OFF } static bool shouldExecuteIfOff(EndpointId endpoint, CommandId commandId, chip::Optional> optionsMask, @@ -610,11 +610,11 @@ Status MoveToLevel(EndpointId endpointId, const Commands::MoveToLevel::Decodable chip::scenes::SceneHandler * GetSceneHandler() { -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS return &sLevelControlSceneHandler; #else return nullptr; -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS } } // namespace LevelControlServer @@ -791,7 +791,7 @@ static Status moveToLevelHandler(EndpointId endpoint, CommandId commandId, uint8 return Status::Failure; } - if (level > EMBER_AF_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL) + if (level > MATTER_DM_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL) { return Status::InvalidCommand; } @@ -913,25 +913,25 @@ static Status moveToLevelHandler(EndpointId endpoint, CommandId commandId, uint8 state->callbackSchedule.runTime = System::Clock::Milliseconds32(0); -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT // The level has changed, the scene is no longer valid. if (emberAfContainsServer(endpoint, ScenesManagement::Id)) { ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); } -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT // The setup was successful, so mark the new state as active and return. scheduleTimerCallbackMs(endpoint, computeCallbackWaitTimeMs(state->callbackSchedule, state->eventDurationMs)); -#ifdef EMBER_AF_PLUGIN_ON_OFF +#ifdef MATTER_DM_PLUGIN_ON_OFF // Check that the received MoveToLevelWithOnOff produces a On action and that the onoff support the lighting featuremap if (commandId == Commands::MoveToLevelWithOnOff::Id && state->moveToLevel != state->minLevel && OnOffServer::Instance().SupportsLightingApplications(endpoint)) { OnOff::Attributes::GlobalSceneControl::Set(endpoint, true); } -#endif // EMBER_AF_PLUGIN_ON_OFF +#endif // MATTER_DM_PLUGIN_ON_OFF return Status::Success; } @@ -1365,8 +1365,8 @@ void emberAfLevelControlClusterServerInitCallback(EndpointId endpoint) return; } - state->minLevel = EMBER_AF_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL; - state->maxLevel = EMBER_AF_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL; + state->minLevel = MATTER_DM_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL; + state->maxLevel = MATTER_DM_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL; // If these read only attributes are enabled we use those values as our set minLevel and maxLevel // if get isn't possible, value stays at default @@ -1453,10 +1453,10 @@ void emberAfLevelControlClusterServerInitCallback(EndpointId endpoint) } } -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS // Registers Scene handlers for the level control cluster on the server app::Clusters::ScenesManagement::ScenesServer::Instance().RegisterSceneHandler(endpoint, LevelControlServer::GetSceneHandler()); -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS emberAfPluginLevelControlClusterServerPostInitCallback(endpoint); } diff --git a/src/app/clusters/level-control/level-control.h b/src/app/clusters/level-control/level-control.h index ba4bea7816752b..95497cc117e6d2 100644 --- a/src/app/clusters/level-control/level-control.h +++ b/src/app/clusters/level-control/level-control.h @@ -19,9 +19,9 @@ // Rate of level control tick execution. // To increase tick frequency (for more granular updates of device state based -// on level), redefine EMBER_AF_PLUGIN_LEVEL_CONTROL_TICKS_PER_SECOND. -#ifndef EMBER_AF_PLUGIN_LEVEL_CONTROL_TICKS_PER_SECOND -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_TICKS_PER_SECOND 32 +// on level), redefine MATTER_DM_PLUGIN_LEVEL_CONTROL_TICKS_PER_SECOND. +#ifndef MATTER_DM_PLUGIN_LEVEL_CONTROL_TICKS_PER_SECOND +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_TICKS_PER_SECOND 32 #endif #include diff --git a/src/app/clusters/low-power-server/low-power-server.cpp b/src/app/clusters/low-power-server/low-power-server.cpp index 4e8b10e8f082ea..fab5217908afea 100644 --- a/src/app/clusters/low-power-server/low-power-server.cpp +++ b/src/app/clusters/low-power-server/low-power-server.cpp @@ -38,7 +38,7 @@ using namespace chip::app::Clusters; using namespace chip::app::Clusters::LowPower; static constexpr size_t kLowPowerDelegateTableSize = - EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kLowPowerDelegateTableSize <= kEmberInvalidEndpointIndex, "LowPower Delegate table size error"); // ----------------------------------------------------------------------------- @@ -53,7 +53,7 @@ Delegate * gDelegateTable[kLowPowerDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, chip::app::Clusters::LowPower::Id, - EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kLowPowerDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -76,7 +76,7 @@ namespace LowPower { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, chip::app::Clusters::LowPower::Id, - EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT); if (ep < kLowPowerDelegateTableSize) { gDelegateTable[ep] = delegate; diff --git a/src/app/clusters/media-input-server/media-input-server.cpp b/src/app/clusters/media-input-server/media-input-server.cpp index 71e6223b5ce2aa..02b114c648b2fd 100644 --- a/src/app/clusters/media-input-server/media-input-server.cpp +++ b/src/app/clusters/media-input-server/media-input-server.cpp @@ -39,7 +39,7 @@ using namespace chip::app::Clusters::MediaInput; using Protocols::InteractionModel::Status; static constexpr size_t kMediaInputDelegateTableSize = - EMBER_AF_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kMediaInputDelegateTableSize <= kEmberInvalidEndpointIndex, "MediaInput Delegate tablle size error"); // ----------------------------------------------------------------------------- @@ -54,7 +54,7 @@ Delegate * gDelegateTable[kMediaInputDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, MediaInput::Id, EMBER_AF_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, MediaInput::Id, MATTER_DM_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kMediaInputDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -77,7 +77,7 @@ namespace MediaInput { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, MediaInput::Id, EMBER_AF_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, MediaInput::Id, MATTER_DM_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT); if (ep < kMediaInputDelegateTableSize) { gDelegateTable[ep] = delegate; diff --git a/src/app/clusters/media-playback-server/media-playback-server.cpp b/src/app/clusters/media-playback-server/media-playback-server.cpp index ea8f00270aaf30..ee8113382b730a 100644 --- a/src/app/clusters/media-playback-server/media-playback-server.cpp +++ b/src/app/clusters/media-playback-server/media-playback-server.cpp @@ -50,7 +50,7 @@ using StateChangedEvent = chip::app::Clusters::MediaPlayback::Events::StateChang using chip::app::LogEvent; static constexpr size_t kMediaPlaybackDelegateTableSize = - EMBER_AF_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kMediaPlaybackDelegateTableSize <= kEmberInvalidEndpointIndex, "kMediaPlayback Delegate table size error"); // ----------------------------------------------------------------------------- @@ -75,7 +75,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogError(Zcl, "MediaPlayback NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, MediaPlayback::Id, EMBER_AF_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, MediaPlayback::Id, MATTER_DM_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kMediaPlaybackDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -98,7 +98,7 @@ namespace MediaPlayback { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, MediaPlayback::Id, EMBER_AF_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, MediaPlayback::Id, MATTER_DM_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kMediaPlaybackDelegateTableSize) { diff --git a/src/app/clusters/mode-base-server/README.md b/src/app/clusters/mode-base-server/README.md index 432091f041d31c..44505fa83d5f9a 100644 --- a/src/app/clusters/mode-base-server/README.md +++ b/src/app/clusters/mode-base-server/README.md @@ -23,7 +23,7 @@ To use a Mode Base derived cluster, you need to `Server::Init()`. - Alternatively, the last two steps can be done in the `emberAfClusterInitCallback` function. -- Add `#define EMBER_AF_PLUGIN_MODE_BASE` to your +- Add `#define MATTER_DM_PLUGIN_MODE_BASE` to your `chip_device_project_config_include` file. In the examples, this file is `CHIPProjectAppConfig.h`. diff --git a/src/app/clusters/mode-base-server/mode-base-server.cpp b/src/app/clusters/mode-base-server/mode-base-server.cpp index 1d01c10c718ac2..6c5feb1d69c88e 100644 --- a/src/app/clusters/mode-base-server/mode-base-server.cpp +++ b/src/app/clusters/mode-base-server/mode-base-server.cpp @@ -122,7 +122,7 @@ CHIP_ERROR Instance::Init() } } -#ifdef EMBER_AF_PLUGIN_ON_OFF_SERVER +#ifdef MATTER_DM_PLUGIN_ON_OFF_SERVER // OnMode with Power Up // If the On/Off feature is supported and the On/Off cluster attribute StartUpOnOff is present, with a // value of On (turn on at power up), then the CurrentMode attribute SHALL be set to the OnMode attribute @@ -156,7 +156,7 @@ CHIP_ERROR Instance::Init() } } } -#endif // EMBER_AF_PLUGIN_ON_OFF_SERVER +#endif // MATTER_DM_PLUGIN_ON_OFF_SERVER return CHIP_NO_ERROR; } diff --git a/src/app/clusters/mode-select-server/mode-select-server.cpp b/src/app/clusters/mode-select-server/mode-select-server.cpp index 4ca641e8e48d95..57cd6d71312012 100644 --- a/src/app/clusters/mode-select-server/mode-select-server.cpp +++ b/src/app/clusters/mode-select-server/mode-select-server.cpp @@ -34,9 +34,9 @@ #include #include -#ifdef EMBER_AF_PLUGIN_ON_OFF +#ifdef MATTER_DM_PLUGIN_ON_OFF #include -#endif // EMBER_AF_PLUGIN_ON_OFF +#endif // MATTER_DM_PLUGIN_ON_OFF using namespace std; using namespace chip; @@ -140,7 +140,7 @@ void emberAfModeSelectClusterServerInitCallback(EndpointId endpointId) EmberAfStatus status = Attributes::StartUpMode::Get(endpointId, startUpMode); if (status == EMBER_ZCL_STATUS_SUCCESS && !startUpMode.IsNull()) { -#ifdef EMBER_AF_PLUGIN_ON_OFF +#ifdef MATTER_DM_PLUGIN_ON_OFF // OnMode with Power Up // If the On/Off feature is supported and the On/Off cluster attribute StartUpOnOff is present, with a // value of On (turn on at power up), then the CurrentMode attribute SHALL be set to the OnMode attribute @@ -162,7 +162,7 @@ void emberAfModeSelectClusterServerInitCallback(EndpointId endpointId) } } } -#endif // EMBER_AF_PLUGIN_ON_OFF +#endif // MATTER_DM_PLUGIN_ON_OFF BootReasonType bootReason = BootReasonType::kUnspecified; CHIP_ERROR error = DeviceLayer::GetDiagnosticDataProvider().GetBootReason(bootReason); diff --git a/src/app/clusters/on-off-server/on-off-server.cpp b/src/app/clusters/on-off-server/on-off-server.cpp index ea7dd0786a9917..8d0f849d923b3f 100644 --- a/src/app/clusters/on-off-server/on-off-server.cpp +++ b/src/app/clusters/on-off-server/on-off-server.cpp @@ -26,21 +26,21 @@ #include #include -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT #include -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL #include -#endif // EMBER_AF_PLUGIN_LEVEL_CONTROL +#endif // MATTER_DM_PLUGIN_LEVEL_CONTROL -#ifdef EMBER_AF_PLUGIN_MODE_BASE +#ifdef MATTER_DM_PLUGIN_MODE_BASE // nogncheck because the gn dependency checker does not understand // conditional includes, so will fail in an application that has an On/Off // cluster but no ModeBase-derived cluster. #include // nogncheck #include // nogncheck -#endif // EMBER_AF_PLUGIN_MODE_BASE +#endif // MATTER_DM_PLUGIN_MODE_BASE #include #include @@ -52,7 +52,7 @@ using chip::Protocols::InteractionModel::Status; namespace { -#ifdef EMBER_AF_PLUGIN_MODE_BASE +#ifdef MATTER_DM_PLUGIN_MODE_BASE /** * For all ModeBase alias clusters on the given endpoint, if the OnOff feature is supported and @@ -85,11 +85,11 @@ void UpdateModeBaseCurrentModeToOnMode(EndpointId endpoint) } } -#endif // EMBER_AF_PLUGIN_MODE_BASE +#endif // MATTER_DM_PLUGIN_MODE_BASE } // namespace -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL static bool LevelControlWithOnOffFeaturePresent(EndpointId endpoint) { if (!emberAfContainsServer(endpoint, LevelControl::Id)) @@ -99,16 +99,16 @@ static bool LevelControlWithOnOffFeaturePresent(EndpointId endpoint) return LevelControlHasFeature(endpoint, LevelControl::Feature::kOnOff); } -#endif // EMBER_AF_PLUGIN_LEVEL_CONTROL +#endif // MATTER_DM_PLUGIN_LEVEL_CONTROL static constexpr size_t kOnOffMaxEnpointCount = - EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS static void sceneOnOffCallback(EndpointId endpoint); using OnOffEndPointPair = scenes::DefaultSceneHandlerImpl::EndpointStatePair; using OnOffTransitionTimeInterface = - scenes::DefaultSceneHandlerImpl::TransitionTimeInterface; + scenes::DefaultSceneHandlerImpl::TransitionTimeInterface; class DefaultOnOffSceneHandler : public scenes::DefaultSceneHandlerImpl { @@ -209,7 +209,7 @@ class DefaultOnOffSceneHandler : public scenes::DefaultSceneHandlerImpl // handler will take action on the on-off state. This assumes the level control attributes were also saved in the scene. // This is to prevent a behavior where the on off state is set by this handler, and then the level control handler or vice // versa. -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL if (!(LevelControlWithOnOffFeaturePresent(endpoint) && ScenesManagement::ScenesServer::Instance().IsHandlerRegistered(endpoint, LevelControlServer::GetSceneHandler()))) #endif @@ -233,7 +233,7 @@ static void sceneOnOffCallback(EndpointId endpoint) OnOffServer::Instance().setOnOffValue(endpoint, command, false); ReturnOnFailure(sOnOffSceneHandler.mSceneEndpointStatePairs.RemovePair(endpoint)); } -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS /********************************************************** * Attributes Definition @@ -301,11 +301,11 @@ OnOffServer & OnOffServer::Instance() chip::scenes::SceneHandler * OnOffServer::GetSceneHandler() { -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS return &sOnOffSceneHandler; #else return nullptr; -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS } bool OnOffServer::HasFeature(chip::EndpointId endpoint, Feature feature) @@ -403,7 +403,7 @@ EmberAfStatus OnOffServer::setOnOffValue(chip::EndpointId endpoint, chip::Comman return status; } -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL // If initiatedByLevelChange is false, then we assume that the level change // ZCL stuff has not happened and we do it here if (!initiatedByLevelChange && LevelControlWithOnOffFeaturePresent(endpoint)) @@ -411,7 +411,7 @@ EmberAfStatus OnOffServer::setOnOffValue(chip::EndpointId endpoint, chip::Comman emberAfOnOffClusterLevelControlEffectCallback(endpoint, newValue); } #endif -#ifdef EMBER_AF_PLUGIN_MODE_SELECT +#ifdef MATTER_DM_PLUGIN_MODE_SELECT // If OnMode is not a null value, then change the current mode to it. if (emberAfContainsServer(endpoint, ModeSelect::Id) && emberAfContainsAttribute(endpoint, ModeSelect::Id, ModeSelect::Attributes::OnMode::Id)) @@ -424,14 +424,14 @@ EmberAfStatus OnOffServer::setOnOffValue(chip::EndpointId endpoint, chip::Comman } } #endif -#ifdef EMBER_AF_PLUGIN_MODE_BASE +#ifdef MATTER_DM_PLUGIN_MODE_BASE // If OnMode is not a null value, then change the current mode to it. UpdateModeBaseCurrentModeToOnMode(endpoint); #endif } else // Set Off { -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL // If initiatedByLevelChange is false, then we assume that the level change // ZCL stuff has not happened and we do it here if (!initiatedByLevelChange && LevelControlWithOnOffFeaturePresent(endpoint)) @@ -457,13 +457,13 @@ EmberAfStatus OnOffServer::setOnOffValue(chip::EndpointId endpoint, chip::Comman } } -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT // the scene has been changed (the value of on/off has changed) so // the current scene as described in the attribute table is invalid, // so mark it as invalid (just writes the valid/invalid attribute) ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT // The returned status is based solely on the On/Off cluster. Errors in the // Level Control and/or Scenes cluster are ignored. @@ -501,13 +501,13 @@ void OnOffServer::initOnOffServer(chip::EndpointId endpoint) status = setOnOffValue(endpoint, onOffValueForStartUp, true); } -#if defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#if defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS // Registers Scene handlers for the On/Off cluster on the server app::Clusters::ScenesManagement::ScenesServer::Instance().RegisterSceneHandler(endpoint, OnOffServer::Instance().GetSceneHandler()); -#endif // defined(EMBER_AF_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS +#endif // defined(MATTER_DM_PLUGIN_SCENES_MANAGEMENT) && CHIP_CONFIG_SCENES_USE_DEFAULT_HANDLERS -#ifdef EMBER_AF_PLUGIN_MODE_SELECT +#ifdef MATTER_DM_PLUGIN_MODE_SELECT // If OnMode is not a null value, then change the current mode to it. if (onOffValueForStartUp && emberAfContainsServer(endpoint, ModeSelect::Id) && emberAfContainsAttribute(endpoint, ModeSelect::Id, ModeSelect::Attributes::OnMode::Id)) @@ -606,9 +606,9 @@ bool OnOffServer::offWithEffectCommand(app::CommandHandler * commandObj, const a if (SupportsLightingApplications(endpoint)) { -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT FabricIndex fabric = commandObj->GetAccessingFabricIndex(); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT bool globalSceneControl = false; OnOff::Attributes::GlobalSceneControl::Get(endpoint, &globalSceneControl); @@ -617,7 +617,7 @@ bool OnOffServer::offWithEffectCommand(app::CommandHandler * commandObj, const a if (globalSceneControl) { -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT GroupId groupId = ZCL_SCENES_GLOBAL_SCENE_GROUP_ID; if (commandObj->GetExchangeContext()->IsGroupExchangeContext()) { @@ -625,7 +625,7 @@ bool OnOffServer::offWithEffectCommand(app::CommandHandler * commandObj, const a } ScenesManagement::ScenesServer::Instance().StoreCurrentScene(fabric, endpoint, groupId, ZCL_SCENES_GLOBAL_SCENE_SCENE_ID); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT OnOff::Attributes::GlobalSceneControl::Set(endpoint, false); } @@ -665,9 +665,9 @@ bool OnOffServer::OnWithRecallGlobalSceneCommand(app::CommandHandler * commandOb return true; } -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT FabricIndex fabric = commandObj->GetAccessingFabricIndex(); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT bool globalSceneControl = false; OnOff::Attributes::GlobalSceneControl::Get(endpoint, &globalSceneControl); @@ -678,7 +678,7 @@ bool OnOffServer::OnWithRecallGlobalSceneCommand(app::CommandHandler * commandOb return true; } -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT GroupId groupId = ZCL_SCENES_GLOBAL_SCENE_GROUP_ID; if (commandObj->GetExchangeContext()->IsGroupExchangeContext()) { @@ -686,7 +686,7 @@ bool OnOffServer::OnWithRecallGlobalSceneCommand(app::CommandHandler * commandOb } ScenesManagement::ScenesServer::Instance().RecallScene(fabric, endpoint, groupId, ZCL_SCENES_GLOBAL_SCENE_SCENE_ID); -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT OnOff::Attributes::GlobalSceneControl::Set(endpoint, true); setOnOffValue(endpoint, Commands::On::Id, false); @@ -860,7 +860,7 @@ bool OnOffServer::areStartUpOnOffServerAttributesNonVolatile(EndpointId endpoint */ EmberEventControl * OnOffServer::getEventControl(EndpointId endpoint, const Span & eventControlArray) { - uint16_t index = emberAfGetClusterServerEndpointIndex(endpoint, OnOff::Id, EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t index = emberAfGetClusterServerEndpointIndex(endpoint, OnOff::Id, MATTER_DM_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT); if (index >= eventControlArray.size()) { return nullptr; diff --git a/src/app/clusters/operational-state-server/operational-state-server.h b/src/app/clusters/operational-state-server/operational-state-server.h index e4ab6d981ca75a..5a461c272177ba 100644 --- a/src/app/clusters/operational-state-server/operational-state-server.h +++ b/src/app/clusters/operational-state-server/operational-state-server.h @@ -341,10 +341,32 @@ namespace RvcOperationalState { class Delegate : public OperationalState::Delegate { public: + /** + * Handle Command Callback in application: GoHome + * @param[out] err operational error after callback. + */ virtual void HandleGoHomeCommandCallback(OperationalState::GenericOperationalError & err) { err.Set(to_underlying(OperationalState::ErrorStateEnum::kUnknownEnumValue)); }; + + /** + * The start command is not supported by the RvcOperationalState cluster hence this method should never be called. + * This is a dummy implementation of the handler method so the consumer of this class does not need to define it. + */ + void HandleStartStateCallback(OperationalState::GenericOperationalError & err) override + { + err.Set(to_underlying(OperationalState::ErrorStateEnum::kUnknownEnumValue)); + }; + + /** + * The stop command is not supported by the RvcOperationalState cluster hence this method should never be called. + * This is a dummy implementation of the handler method so the consumer of this class does not need to define it. + */ + void HandleStopStateCallback(OperationalState::GenericOperationalError & err) override + { + err.Set(to_underlying(OperationalState::ErrorStateEnum::kUnknownEnumValue)); + }; }; class Instance : public OperationalState::Instance diff --git a/src/app/clusters/ota-provider/ota-provider.cpp b/src/app/clusters/ota-provider/ota-provider.cpp index 6b353073a829dc..46f55905157a95 100644 --- a/src/app/clusters/ota-provider/ota-provider.cpp +++ b/src/app/clusters/ota-provider/ota-provider.cpp @@ -37,16 +37,16 @@ using namespace chip::app::Clusters::OtaSoftwareUpdateProvider; using chip::app::Clusters::OTAProviderDelegate; using Protocols::InteractionModel::Status; -// EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT is only defined if the +// MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT is only defined if the // cluster is actually enabled in the ZAP config. To allow operation in setups // where that's not the case (and custom dispatch is used), define it here as // needed. -#ifndef EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT -#define EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT 0 -#endif // EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT +#ifndef MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT +#define MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT 0 +#endif // MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT static constexpr size_t kOtaProviderDelegateTableSize = - EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kOtaProviderDelegateTableSize <= kEmberInvalidEndpointIndex, "OtaProvider Delegate table size error"); namespace { @@ -60,7 +60,7 @@ OTAProviderDelegate * gDelegateTable[kOtaProviderDelegateTableSize] = { nullptr OTAProviderDelegate * GetDelegate(EndpointId endpoint) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, OtaSoftwareUpdateProvider::Id, - EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kOtaProviderDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -229,7 +229,7 @@ namespace OTAProvider { void SetDelegate(EndpointId endpoint, OTAProviderDelegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, OtaSoftwareUpdateProvider::Id, - EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT); if (ep < kOtaProviderDelegateTableSize) { gDelegateTable[ep] = delegate; diff --git a/src/app/clusters/power-source-server/power-source-server.cpp b/src/app/clusters/power-source-server/power-source-server.cpp index 037a182dd7a0d6..717c610830b8fb 100644 --- a/src/app/clusters/power-source-server/power-source-server.cpp +++ b/src/app/clusters/power-source-server/power-source-server.cpp @@ -72,9 +72,9 @@ PowerSourceServer gPowerSourceServer; PowerSourceAttrAccess gAttrAccess; #ifdef ZCL_USING_POWER_SOURCE_CLUSTER_SERVER -static constexpr uint16_t kNumStaticEndpoints = EMBER_AF_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT; +static constexpr uint16_t kNumStaticEndpoints = MATTER_DM_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT; #define POWER_SERVER_NUM_SUPPORTED_ENDPOINTS \ - (EMBER_AF_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) + (MATTER_DM_POWER_SOURCE_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) #else static constexpr uint16_t kNumStaticEndpoints = 0; #define POWER_SERVER_NUM_SUPPORTED_ENDPOINTS CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT diff --git a/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp b/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp index 4d9a88d3f8216c..76f2a3d01830ed 100644 --- a/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp +++ b/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp @@ -156,12 +156,12 @@ static void setEffectiveModes(EndpointId endpoint) // Maximum, Minimum or Local case OperationModeEnum::kMaximum: { -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL uint8_t maxLevel; #endif Attributes::EffectiveOperationMode::Set(endpoint, OperationModeEnum::kMaximum); Attributes::EffectiveControlMode::Set(endpoint, ControlModeEnum::kConstantSpeed); -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL LevelControl::Attributes::MaxLevel::Get(endpoint, &maxLevel); LevelControl::Attributes::CurrentLevel::Set(endpoint, maxLevel); #endif @@ -175,12 +175,12 @@ static void setEffectiveModes(EndpointId endpoint) break; case OperationModeEnum::kMinimum: { -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL uint8_t minLevel; #endif Attributes::EffectiveOperationMode::Set(endpoint, OperationModeEnum::kMinimum); Attributes::EffectiveControlMode::Set(endpoint, ControlModeEnum::kConstantSpeed); -#ifdef EMBER_AF_PLUGIN_LEVEL_CONTROL +#ifdef MATTER_DM_PLUGIN_LEVEL_CONTROL LevelControl::Attributes::MinLevel::Get(endpoint, &minLevel); if (minLevel == 0) { diff --git a/src/app/clusters/sample-mei-server/sample-mei-server.cpp b/src/app/clusters/sample-mei-server/sample-mei-server.cpp index f52aa573ece038..25bcb2aaf77b13 100644 --- a/src/app/clusters/sample-mei-server/sample-mei-server.cpp +++ b/src/app/clusters/sample-mei-server/sample-mei-server.cpp @@ -27,7 +27,7 @@ using namespace chip::app::Clusters::SampleMei::Attributes; void MatterSampleMeiPluginServerInitCallback() { - ChipLogProgress(Zcl, "Sample MEI Init. Ep %d, Total Ep %u", EMBER_AF_SAMPLE_MEI_CLUSTER_SERVER_ENDPOINT_COUNT, + ChipLogProgress(Zcl, "Sample MEI Init. Ep %d, Total Ep %u", MATTER_DM_SAMPLE_MEI_CLUSTER_SERVER_ENDPOINT_COUNT, static_cast(kNumSupportedEndpoints)); ReturnOnFailure(InteractionModelEngine::GetInstance()->RegisterCommandHandler(&SampleMeiServer::Instance())); VerifyOrReturn(registerAttributeAccessOverride(&SampleMeiServer::Instance()), CHIP_ERROR_INCORRECT_STATE); diff --git a/src/app/clusters/sample-mei-server/sample-mei-server.h b/src/app/clusters/sample-mei-server/sample-mei-server.h index 9f5307dba6d753..14446ba6f38f02 100644 --- a/src/app/clusters/sample-mei-server/sample-mei-server.h +++ b/src/app/clusters/sample-mei-server/sample-mei-server.h @@ -13,7 +13,7 @@ #ifdef ZCL_USING_SAMPLE_MEI_CLUSTER_SERVER #define SAMPLE_MEI_NUM_SUPPORTED_ENDPOINTS \ - (EMBER_AF_SAMPLE_MEI_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) + (MATTER_DM_SAMPLE_MEI_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) #else #define SAMPLE_MEI_NUM_SUPPORTED_ENDPOINTS CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT #endif /* ZCL_USING_SAMPLE_MEI_CLUSTER_SERVER */ diff --git a/src/app/clusters/scenes-server/scenes-server.cpp b/src/app/clusters/scenes-server/scenes-server.cpp index 94039297713bed..c595ee6486779f 100644 --- a/src/app/clusters/scenes-server/scenes-server.cpp +++ b/src/app/clusters/scenes-server/scenes-server.cpp @@ -269,7 +269,7 @@ CHIP_ERROR ScenesServer::FabricSceneInfo::FindFabricSceneInfoIndex(EndpointId en VerifyOrReturnError(kInvalidEndpointId != endpoint, CHIP_ERROR_INVALID_ARGUMENT); uint16_t index = - emberAfGetClusterServerEndpointIndex(endpoint, ScenesManagement::Id, EMBER_AF_SCENES_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, ScenesManagement::Id, MATTER_DM_SCENES_CLUSTER_SERVER_ENDPOINT_COUNT); if (index < ArraySize(mSceneInfoStructs)) { diff --git a/src/app/clusters/scenes-server/scenes-server.h b/src/app/clusters/scenes-server/scenes-server.h index e85e72ea07606b..86459fb8e82c67 100644 --- a/src/app/clusters/scenes-server/scenes-server.h +++ b/src/app/clusters/scenes-server/scenes-server.h @@ -35,7 +35,7 @@ class ScenesServer : public CommandHandlerInterface, public AttributeAccessInter { public: static constexpr size_t kScenesServerMaxEndpointCount = - EMBER_AF_SCENES_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_SCENES_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kScenesServerMaxEndpointCount <= kEmberInvalidEndpointIndex, "Scenes endpoint count error"); static constexpr uint8_t kScenesServerMaxFabricCount = CHIP_CONFIG_MAX_FABRICS; diff --git a/src/app/clusters/target-navigator-server/target-navigator-server.cpp b/src/app/clusters/target-navigator-server/target-navigator-server.cpp index e52ef407003eb1..71d396a671d67b 100644 --- a/src/app/clusters/target-navigator-server/target-navigator-server.cpp +++ b/src/app/clusters/target-navigator-server/target-navigator-server.cpp @@ -49,7 +49,7 @@ using chip::Protocols::InteractionModel::Status; using TargetUpdatedEvent = chip::app::Clusters::TargetNavigator::Events::TargetUpdated::Type; static constexpr size_t kTargetNavigatorDelegateTableSize = - EMBER_AF_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kTargetNavigatorDelegateTableSize <= kEmberInvalidEndpointIndex, "TargetNavigator Delegate table size error"); // ----------------------------------------------------------------------------- @@ -74,7 +74,7 @@ Delegate * GetDelegate(EndpointId endpoint) ChipLogProgress(Zcl, "TargetNavigator NOT returning ContentApp delegate for endpoint:%u", endpoint); uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, TargetNavigator::Id, - EMBER_AF_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kTargetNavigatorDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -97,7 +97,7 @@ namespace TargetNavigator { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, TargetNavigator::Id, - EMBER_AF_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kTargetNavigatorDelegateTableSize) { diff --git a/src/app/clusters/valve-configuration-and-control-server/valve-configuration-and-control-server.cpp b/src/app/clusters/valve-configuration-and-control-server/valve-configuration-and-control-server.cpp index 30481d8ddf5cbc..62d5e1b2c77da8 100644 --- a/src/app/clusters/valve-configuration-and-control-server/valve-configuration-and-control-server.cpp +++ b/src/app/clusters/valve-configuration-and-control-server/valve-configuration-and-control-server.cpp @@ -50,7 +50,7 @@ using chip::app::Clusters::ValveConfigurationAndControl::Delegate; using chip::Protocols::InteractionModel::Status; static constexpr size_t kValveConfigurationAndControlDelegateTableSize = - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kValveConfigurationAndControlDelegateTableSize <= kEmberInvalidEndpointIndex, "ValveConfigurationAndControl Delegate table size error"); @@ -69,7 +69,7 @@ Delegate * gDelegateTable[kValveConfigurationAndControlDelegateTableSize] = { nu bool GetRemainingDuration(EndpointId endpoint, DataModel::Nullable & duration) { uint16_t epIdx = emberAfGetClusterServerEndpointIndex(endpoint, ValveConfigurationAndControl::Id, - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); VerifyOrReturnValue(epIdx < kValveConfigurationAndControlDelegateTableSize, false); duration = gRemainingDuration[epIdx].remainingDuration; return true; @@ -78,7 +78,7 @@ bool GetRemainingDuration(EndpointId endpoint, DataModel::Nullable & d void SetRemainingDuration(EndpointId endpoint, DataModel::Nullable duration) { uint16_t epIdx = emberAfGetClusterServerEndpointIndex(endpoint, ValveConfigurationAndControl::Id, - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); if (epIdx < kValveConfigurationAndControlDelegateTableSize) { gRemainingDuration[epIdx].endpoint = endpoint; @@ -89,7 +89,7 @@ void SetRemainingDuration(EndpointId endpoint, DataModel::Nullable dur void SetRemainingDurationNull(EndpointId endpoint) { uint16_t epIdx = emberAfGetClusterServerEndpointIndex(endpoint, ValveConfigurationAndControl::Id, - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); if (epIdx < kValveConfigurationAndControlDelegateTableSize) { if (!gRemainingDuration[epIdx].remainingDuration.IsNull()) @@ -103,7 +103,7 @@ void SetRemainingDurationNull(EndpointId endpoint) RemainingDurationTable * GetRemainingDurationItem(EndpointId endpoint) { uint16_t epIdx = emberAfGetClusterServerEndpointIndex(endpoint, ValveConfigurationAndControl::Id, - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); if (epIdx < kValveConfigurationAndControlDelegateTableSize) { return &gRemainingDuration[epIdx]; @@ -114,7 +114,7 @@ RemainingDurationTable * GetRemainingDurationItem(EndpointId endpoint) Delegate * GetDelegate(EndpointId endpoint) { uint16_t epIdx = emberAfGetClusterServerEndpointIndex(endpoint, ValveConfigurationAndControl::Id, - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); return (epIdx >= kValveConfigurationAndControlDelegateTableSize ? nullptr : gDelegateTable[epIdx]); } @@ -261,7 +261,7 @@ namespace ValveConfigurationAndControl { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, ValveConfigurationAndControl::Id, - EMBER_AF_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); + MATTER_DM_VALVE_CONFIGURATION_AND_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kValveConfigurationAndControlDelegateTableSize) { diff --git a/src/app/clusters/wake-on-lan-server/wake-on-lan-server.cpp b/src/app/clusters/wake-on-lan-server/wake-on-lan-server.cpp index 15b514c9e3f247..ec989bbc588372 100644 --- a/src/app/clusters/wake-on-lan-server/wake-on-lan-server.cpp +++ b/src/app/clusters/wake-on-lan-server/wake-on-lan-server.cpp @@ -38,7 +38,7 @@ using namespace chip::app::Clusters; using namespace chip::app::Clusters::WakeOnLan; static constexpr size_t kWakeOnLanDelegateTableSize = - EMBER_AF_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kWakeOnLanDelegateTableSize <= kEmberInvalidEndpointIndex, "WakeOnLan Delegate table size error"); // ----------------------------------------------------------------------------- @@ -52,7 +52,8 @@ Delegate * gDelegateTable[kWakeOnLanDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, WakeOnLan::Id, EMBER_AF_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, WakeOnLan::Id, MATTER_DM_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kWakeOnLanDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -74,7 +75,8 @@ namespace WakeOnLan { void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { - uint16_t ep = emberAfGetClusterServerEndpointIndex(endpoint, WakeOnLan::Id, EMBER_AF_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT); + uint16_t ep = + emberAfGetClusterServerEndpointIndex(endpoint, WakeOnLan::Id, MATTER_DM_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT); if (ep < kWakeOnLanDelegateTableSize) { gDelegateTable[ep] = delegate; diff --git a/src/app/clusters/window-covering-server/window-covering-server.cpp b/src/app/clusters/window-covering-server/window-covering-server.cpp index b55f59074de843..79956d0c448894 100644 --- a/src/app/clusters/window-covering-server/window-covering-server.cpp +++ b/src/app/clusters/window-covering-server/window-covering-server.cpp @@ -30,9 +30,9 @@ #include #include -#ifdef EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT #include -#endif // EMBER_AF_PLUGIN_SCENES_MANAGEMENT +#endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT using namespace chip; using namespace chip::app::Clusters; @@ -47,7 +47,7 @@ using chip::Protocols::InteractionModel::Status; namespace { constexpr size_t kWindowCoveringDelegateTableSize = - EMBER_AF_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; + MATTER_DM_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; static_assert(kWindowCoveringDelegateTableSize <= kEmberInvalidEndpointIndex, "WindowCovering Delegate table size error"); Delegate * gDelegateTable[kWindowCoveringDelegateTableSize] = { nullptr }; @@ -55,7 +55,7 @@ Delegate * gDelegateTable[kWindowCoveringDelegateTableSize] = { nullptr }; Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, WindowCovering::Id, EMBER_AF_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, WindowCovering::Id, MATTER_DM_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT); return (ep >= kWindowCoveringDelegateTableSize ? nullptr : gDelegateTable[ep]); } @@ -596,7 +596,7 @@ Status GetMotionLockStatus(chip::EndpointId endpoint) void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate) { uint16_t ep = - emberAfGetClusterServerEndpointIndex(endpoint, WindowCovering::Id, EMBER_AF_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT); + emberAfGetClusterServerEndpointIndex(endpoint, WindowCovering::Id, MATTER_DM_WINDOW_COVERING_CLUSTER_SERVER_ENDPOINT_COUNT); // if endpoint is found if (ep < kWindowCoveringDelegateTableSize) diff --git a/src/app/icd/server/ICDManager.cpp b/src/app/icd/server/ICDManager.cpp index 954b3d753be7ce..05948feb3406a1 100644 --- a/src/app/icd/server/ICDManager.cpp +++ b/src/app/icd/server/ICDManager.cpp @@ -544,5 +544,19 @@ bool ICDManager::CheckInMessagesWouldBeSent() return false; } +void ICDManager::TriggerCheckInMessages() +{ + VerifyOrReturn(SupportsFeature(Feature::kCheckInProtocolSupport)); + + // Only trigger Check-In messages when we are in IdleMode. + // If we are already in ActiveMode, Check-In messages have already been sent. + VerifyOrReturn(mOperationalState == OperationalState::IdleMode); + + // If we don't have any Check-In messages to send, do nothing + VerifyOrReturn(CheckInMessagesWouldBeSent()); + + UpdateOperationState(OperationalState::ActiveMode); +} + } // namespace app } // namespace chip diff --git a/src/app/icd/server/ICDManager.h b/src/app/icd/server/ICDManager.h index 3f78cccc69cfd1..f115a41bdddcc8 100644 --- a/src/app/icd/server/ICDManager.h +++ b/src/app/icd/server/ICDManager.h @@ -108,6 +108,11 @@ class ICDManager : public ICDListener void OnICDManagementServerEvent(ICDManagementEvents event) override; void OnSubscriptionReport() override; + /** + * @brief Trigger the ICDManager to send Check-In message if necessary + */ + void TriggerCheckInMessages(); + protected: friend class TestICDManager; diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 3c33c45537d5ef..6228c10bb46698 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -436,6 +436,16 @@ void Server::OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event) } break; case DeviceEventType::kServerReady: +#if CHIP_CONFIG_ENABLE_ICD_SERVER + // Only Trigger Check-In messages if we are not in the middle of a commissioning. + // This check is only necessary for the first commissioiner since the kServerReady event + // is triggered once we join the network. + // We trigger Check-In messages before resuming subscriptions to avoid doing both. + if (!mFailSafeContext.IsFailSafeArmed()) + { + mICDManager.TriggerCheckInMessages(); + } +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS ResumeSubscriptions(); #endif diff --git a/src/app/server/java/CHIPAppServer-JNI.cpp b/src/app/server/java/CHIPAppServer-JNI.cpp index 2fd6aa8dbb516c..4040d4d0d22ec2 100644 --- a/src/app/server/java/CHIPAppServer-JNI.cpp +++ b/src/app/server/java/CHIPAppServer-JNI.cpp @@ -51,9 +51,9 @@ using namespace chip::DeviceLayer; static void * IOThreadAppMain(void * arg); namespace { -JavaVM * sJVM; -pthread_t sIOThread = PTHREAD_NULL; -jclass sChipAppServerExceptionCls = NULL; +JavaVM * sJVM = nullptr; +pthread_t sIOThread = PTHREAD_NULL; +JniGlobalReference sChipAppServerExceptionCls; ChipAppServerDelegate sChipAppServerDelegate; } // namespace @@ -77,7 +77,10 @@ jint AndroidAppServerJNI_OnLoad(JavaVM * jvm, void * reserved) ChipLogProgress(AppServer, "Loading Java class references."); // Get various class references need by the API. - err = JniReferences::GetInstance().GetClassRef(env, "chip/appserver/ChipAppServerException", sChipAppServerExceptionCls); + jclass appServerExceptionCls; + err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/appserver/ChipAppServerException", appServerExceptionCls); + SuccessOrExit(err); + err = sChipAppServerExceptionCls.Init(static_cast(appServerExceptionCls)); SuccessOrExit(err); ChipLogProgress(AppServer, "Java class references loaded."); diff --git a/src/app/server/java/ChipAppServerDelegate.cpp b/src/app/server/java/ChipAppServerDelegate.cpp index 50d76c63d59423..91edb2a6da5527 100644 --- a/src/app/server/java/ChipAppServerDelegate.cpp +++ b/src/app/server/java/ChipAppServerDelegate.cpp @@ -29,7 +29,9 @@ void ChipAppServerDelegate::OnCommissioningSessionEstablishmentStarted() ChipLogError(AppServer, "mOnCommissioningSessionEstablishmentStartedMethod is nullptr")); env->ExceptionClear(); - env->CallVoidMethod(mChipAppServerDelegateObject, mOnCommissioningSessionEstablishmentStartedMethod); + VerifyOrReturn(mChipAppServerDelegateObject.HasValidObjectRef(), + ChipLogError(AppServer, "mChipAppServerDelegateObject is not valid")); + env->CallVoidMethod(mChipAppServerDelegateObject.ObjectRef(), mOnCommissioningSessionEstablishmentStartedMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnCommissioningSessionEstablishmentStartedMethod"); @@ -46,7 +48,9 @@ void ChipAppServerDelegate::OnCommissioningSessionStarted() ChipLogError(AppServer, "mOnCommissioningSessionStartedMethod is nullptr")); env->ExceptionClear(); - env->CallVoidMethod(mChipAppServerDelegateObject, mOnCommissioningSessionStartedMethod); + VerifyOrReturn(mChipAppServerDelegateObject.HasValidObjectRef(), + ChipLogError(AppServer, "mChipAppServerDelegateObject is not valid")); + env->CallVoidMethod(mChipAppServerDelegateObject.ObjectRef(), mOnCommissioningSessionStartedMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnCommissioningSessionStartedMethod"); @@ -63,7 +67,9 @@ void ChipAppServerDelegate::OnCommissioningSessionEstablishmentError(CHIP_ERROR ChipLogError(AppServer, "mOnCommissioningSessionEstablishmentErrorMethod is nullptr")); env->ExceptionClear(); - env->CallVoidMethod(mChipAppServerDelegateObject, mOnCommissioningSessionEstablishmentErrorMethod, + VerifyOrReturn(mChipAppServerDelegateObject.HasValidObjectRef(), + ChipLogError(AppServer, "mChipAppServerDelegateObject is not valid")); + env->CallVoidMethod(mChipAppServerDelegateObject.ObjectRef(), mOnCommissioningSessionEstablishmentErrorMethod, static_cast(err.AsInteger())); if (env->ExceptionCheck()) { @@ -81,7 +87,9 @@ void ChipAppServerDelegate::OnCommissioningSessionStopped() ChipLogError(AppServer, "mOnCommissioningSessionStoppedMethod is nullptr")); env->ExceptionClear(); - env->CallVoidMethod(mChipAppServerDelegateObject, mOnCommissioningSessionStoppedMethod); + VerifyOrReturn(mChipAppServerDelegateObject.HasValidObjectRef(), + ChipLogError(AppServer, "mChipAppServerDelegateObject is not valid")); + env->CallVoidMethod(mChipAppServerDelegateObject.ObjectRef(), mOnCommissioningSessionStoppedMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnCommissioningSessionStoppedMethod"); @@ -98,7 +106,9 @@ void ChipAppServerDelegate::OnCommissioningWindowOpened() ChipLogError(AppServer, "mOnCommissioningWindowOpenedMethod is nullptr")); env->ExceptionClear(); - env->CallVoidMethod(mChipAppServerDelegateObject, mOnCommissioningWindowOpenedMethod); + VerifyOrReturn(mChipAppServerDelegateObject.HasValidObjectRef(), + ChipLogError(AppServer, "mChipAppServerDelegateObject is not valid")); + env->CallVoidMethod(mChipAppServerDelegateObject.ObjectRef(), mOnCommissioningWindowOpenedMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnCommissioningWindowOpenedMethod"); @@ -115,7 +125,9 @@ void ChipAppServerDelegate::OnCommissioningWindowClosed() ChipLogError(AppServer, "mOnCommissioningWindowClosedMethod is nullptr")); env->ExceptionClear(); - env->CallVoidMethod(mChipAppServerDelegateObject, mOnCommissioningWindowClosedMethod); + VerifyOrReturn(mChipAppServerDelegateObject.HasValidObjectRef(), + ChipLogError(AppServer, "mChipAppServerDelegateObject is not valid")); + env->CallVoidMethod(mChipAppServerDelegateObject.ObjectRef(), mOnCommissioningWindowClosedMethod); if (env->ExceptionCheck()) { ChipLogError(AppServer, "Java exception in OnCommissioningWindowClosedMethod"); @@ -128,11 +140,9 @@ CHIP_ERROR ChipAppServerDelegate::InitializeWithObjects(jobject appDelegateObjec { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); + ReturnLogErrorOnFailure(mChipAppServerDelegateObject.Init(appDelegateObject)); - mChipAppServerDelegateObject = env->NewGlobalRef(appDelegateObject); - VerifyOrReturnLogError(mChipAppServerDelegateObject != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - - jclass chipAppServerDelegateClass = env->GetObjectClass(mChipAppServerDelegateObject); + jclass chipAppServerDelegateClass = env->GetObjectClass(mChipAppServerDelegateObject.ObjectRef()); VerifyOrReturnLogError(chipAppServerDelegateClass != nullptr, CHIP_JNI_ERROR_JAVA_ERROR); mOnCommissioningSessionEstablishmentStartedMethod = diff --git a/src/app/server/java/ChipAppServerDelegate.h b/src/app/server/java/ChipAppServerDelegate.h index 42df60605de39a..ec56519a470331 100644 --- a/src/app/server/java/ChipAppServerDelegate.h +++ b/src/app/server/java/ChipAppServerDelegate.h @@ -20,6 +20,7 @@ #include #include #include +#include class ChipAppServerDelegate : public AppDelegate { @@ -34,7 +35,7 @@ class ChipAppServerDelegate : public AppDelegate CHIP_ERROR InitializeWithObjects(jobject appDelegateObject); private: - jobject mChipAppServerDelegateObject = nullptr; + chip::JniGlobalReference mChipAppServerDelegateObject; jmethodID mOnCommissioningSessionEstablishmentStartedMethod = nullptr; jmethodID mOnCommissioningSessionStartedMethod = nullptr; jmethodID mOnCommissioningSessionEstablishmentErrorMethod = nullptr; diff --git a/src/app/tests/suites/TestIcdManagementCluster.yaml b/src/app/tests/suites/TestIcdManagementCluster.yaml index f8a853c5fe09e7..4a83c077843822 100644 --- a/src/app/tests/suites/TestIcdManagementCluster.yaml +++ b/src/app/tests/suites/TestIcdManagementCluster.yaml @@ -52,6 +52,43 @@ tests: }, ] + - label: "Read ICDCounter" + command: "readAttribute" + attribute: "ICDCounter" + response: + constraints: + type: int32u + minValue: 0x0 + maxValue: 0xFFFFFFFF + saveAs: beforeRebootICDCounter + + - label: "Reboot target device" + cluster: "SystemCommands" + command: "Reboot" + + - label: "Connect to the device again" + cluster: "DelayCommands" + command: "WaitForCommissionee" + arguments: + values: + - name: "nodeId" + value: nodeId + + - label: "Wait for 1S" + cluster: "DelayCommands" + command: "WaitForMs" + arguments: + values: + - name: "ms" + value: 1000 + + # Verifies ICDCounter increment and Check-In message at reboot + - label: "Read ICDCounter after reboot" + command: "readAttribute" + attribute: "ICDCounter" + response: + value: beforeRebootICDCounter + 101 + - label: "Unregister Client Registered During Commissioning" command: "UnregisterClient" arguments: @@ -83,34 +120,6 @@ tests: response: value: 5000 - - label: "Read ICDCounter" - command: "readAttribute" - attribute: "ICDCounter" - response: - constraints: - type: int32u - minValue: 0x0 - maxValue: 0xFFFFFFFF - saveAs: beforeRebootICDCounter - - - label: "Reboot target device" - cluster: "SystemCommands" - command: "Reboot" - - - label: "Connect to the device again" - cluster: "DelayCommands" - command: "WaitForCommissionee" - arguments: - values: - - name: "nodeId" - value: nodeId - - - label: "Read ICDCounter after reboot" - command: "readAttribute" - attribute: "ICDCounter" - response: - value: beforeRebootICDCounter + 100 - - label: "Read UserActiveModeTriggerHint" command: "readAttribute" attribute: "UserActiveModeTriggerHint" diff --git a/src/app/util/af-types.h b/src/app/util/af-types.h index d154399a6973a6..e394a2098e4005 100644 --- a/src/app/util/af-types.h +++ b/src/app/util/af-types.h @@ -59,7 +59,7 @@ typedef void (*EmberAfGenericClusterFunction)(void); * @brief A distinguished manufacturer code that is used to indicate the * absence of a manufacturer-specific cluster, command, or attribute. */ -#define EMBER_AF_NULL_MANUFACTURER_CODE 0x0000 +#define MATTER_DM_NULL_MANUFACTURER_CODE 0x0000 /** * @brief Struct describing cluster @@ -234,12 +234,12 @@ struct EmberAfDefinedEndpoint /** * @brief Indicates the absence of a Scene table entry. */ -#define EMBER_AF_SCENE_TABLE_NULL_INDEX 0xFF +#define MATTER_DM_SCENE_TABLE_NULL_INDEX 0xFF /** * @brief Value used when setting or getting the endpoint in a Scene table * entry. It indicates that the entry is not in use. */ -#define EMBER_AF_SCENE_TABLE_UNUSED_ENDPOINT_ID 0x00 +#define MATTER_DM_SCENE_TABLE_UNUSED_ENDPOINT_ID 0x00 /** * @brief Maximum length of Scene names, not including the length byte. */ diff --git a/src/app/util/af.h b/src/app/util/af.h index c186699cbc68a7..d18d69956b9746 100644 --- a/src/app/util/af.h +++ b/src/app/util/af.h @@ -176,7 +176,7 @@ uint16_t emberAfIndexFromEndpointIncludingDisabledEndpoints(chip::EndpointId end * @param endpoint Endpoint number * @param cluster Id the of the Cluster server you are interrested on * @param fixedClusterServerEndpointCount The number of fixed endpoints containing this cluster server. Typically one of the - EMBER_AF_*_CLUSTER_SERVER_ENDPOINT_COUNT constants. + MATTER_DM_*_CLUSTER_SERVER_ENDPOINT_COUNT constants. */ uint16_t emberAfGetClusterServerEndpointIndex(chip::EndpointId endpoint, chip::ClusterId cluster, uint16_t fixedClusterServerEndpointCount); diff --git a/src/app/util/util.cpp b/src/app/util/util.cpp index fb166ff72453bd..2593609d77af93 100644 --- a/src/app/util/util.cpp +++ b/src/app/util/util.cpp @@ -28,9 +28,9 @@ // TODO: figure out a clear path for compile-time codegen #include -#ifdef EMBER_AF_PLUGIN_GROUPS_SERVER +#ifdef MATTER_DM_PLUGIN_GROUPS_SERVER #include -#endif // EMBER_AF_PLUGIN_GROUPS_SERVER +#endif // MATTER_DM_PLUGIN_GROUPS_SERVER using namespace chip; @@ -45,8 +45,8 @@ const EmberAfClusterName zclClusterNames[] = { { kInvalidClusterId, nullptr }, // terminator }; -#ifdef EMBER_AF_GENERATED_PLUGIN_TICK_FUNCTION_DECLARATIONS -EMBER_AF_GENERATED_PLUGIN_TICK_FUNCTION_DECLARATIONS +#ifdef MATTER_DM_GENERATED_PLUGIN_TICK_FUNCTION_DECLARATIONS +MATTER_DM_GENERATED_PLUGIN_TICK_FUNCTION_DECLARATIONS #endif //------------------------------------------------------------------------------ diff --git a/src/app/zap-templates/templates/app/gen_config.zapt b/src/app/zap-templates/templates/app/gen_config.zapt index 65a7705b459036..87dce18a6673b1 100644 --- a/src/app/zap-templates/templates/app/gen_config.zapt +++ b/src/app/zap-templates/templates/app/gen_config.zapt @@ -5,7 +5,7 @@ /**** Cluster endpoint counts ****/ {{#all_user_clusters}} -#define EMBER_AF_{{as_delimited_macro define}}_{{as_delimited_macro side}}_ENDPOINT_COUNT ({{user_endpoint_count_by_cluster id side}}) +#define MATTER_DM_{{as_delimited_macro define}}_{{as_delimited_macro side}}_ENDPOINT_COUNT ({{user_endpoint_count_by_cluster id side}}) {{/all_user_clusters}} /**** Cluster Plugins ****/ @@ -13,30 +13,30 @@ // Use this macro to check if the {{side}} side of the {{name}} cluster is included #define ZCL_USING_{{as_delimited_macro define}}_{{as_delimited_macro side}} -#define EMBER_AF_PLUGIN_{{as_delimited_macro name}}_{{as_delimited_macro side}} +#define MATTER_DM_PLUGIN_{{as_delimited_macro name}}_{{as_delimited_macro side}} {{#if (is_server side)}} -#define EMBER_AF_PLUGIN_{{as_delimited_macro name}} +#define MATTER_DM_PLUGIN_{{as_delimited_macro name}} {{/if}} {{#if (is_str_equal name "Color Control")}} {{#if (is_server side)}} // User options for {{side}} plugin {{name}} -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_XY -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_TEMP -#define EMBER_AF_PLUGIN_COLOR_CONTROL_SERVER_HSV +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP +#define MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV {{/if}} {{else if (is_str_equal name "IAS Zone")}} // User options for {{side}} plugin {{name}} {{#if (is_server side)}} -#define EMBER_AF_PLUGIN_IAS_ZONE_SERVER_ZONE_TYPE 541 +#define MATTER_DM_PLUGIN_IAS_ZONE_SERVER_ZONE_TYPE 541 {{else}} -#define EMBER_AF_PLUGIN_IAS_ZONE_CLIENT_MAX_DEVICES 10 +#define MATTER_DM_PLUGIN_IAS_ZONE_CLIENT_MAX_DEVICES 10 {{/if}} {{else if (is_str_equal name "Level Control")}} {{#if (is_server side)}} // User options for {{side}} plugin {{name}} -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254 -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0 -#define EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE 0 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0 +#define MATTER_DM_PLUGIN_LEVEL_CONTROL_RATE 0 {{/if}} {{else if (is_str_equal name "Scenes Management")}} {{#if (is_server side)}} diff --git a/src/controller/java/AndroidCallbacks.cpp b/src/controller/java/AndroidCallbacks.cpp index f4f62b6b0ec4c7..88bbf9844c9407 100644 --- a/src/controller/java/AndroidCallbacks.cpp +++ b/src/controller/java/AndroidCallbacks.cpp @@ -500,7 +500,6 @@ CHIP_ERROR InvokeCallback::CreateInvokeElement(JNIEnv * env, const app::Concrete { CHIP_ERROR err = CHIP_NO_ERROR; jclass invokeElementCls = nullptr; - jobject localRef = nullptr; err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/model/InvokeElement", invokeElementCls); ReturnErrorOnFailure(err); @@ -536,20 +535,18 @@ CHIP_ERROR InvokeCallback::CreateInvokeElement(JNIEnv * env, const app::Concrete err = TlvToJson(readerForJson, json); ReturnErrorOnFailure(err); UtfString jsonString(env, json.c_str()); - localRef = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), - jniByteArray.jniValue(), jsonString.jniValue()); + outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), + jniByteArray.jniValue(), jsonString.jniValue()); } else { - localRef = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), nullptr, - nullptr); + outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), nullptr, + nullptr); } - VerifyOrReturnError(localRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - outObj = env->NewGlobalRef(localRef); VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - return err; + return CHIP_NO_ERROR; } void ReportCallback::OnError(CHIP_ERROR aError) diff --git a/src/controller/java/AndroidCommissioningWindowOpener.cpp b/src/controller/java/AndroidCommissioningWindowOpener.cpp index 0429c72bf12ad5..581b81073769c8 100644 --- a/src/controller/java/AndroidCommissioningWindowOpener.cpp +++ b/src/controller/java/AndroidCommissioningWindowOpener.cpp @@ -36,9 +36,8 @@ AndroidCommissioningWindowOpener::AndroidCommissioningWindowOpener(DeviceControl CommissioningWindowOpener(controller), mOnOpenCommissioningWindowCallback(OnOpenCommissioningWindowResponse, this), mOnOpenBasicCommissioningWindowCallback(OnOpenBasicCommissioningWindowResponse, this) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - mJavaCallback = env->NewGlobalRef(jCallbackObject); - if (mJavaCallback == nullptr) + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + if (mJavaCallback.Init(jCallbackObject) != CHIP_NO_ERROR) { ChipLogError(Controller, "Failed to create global reference for mJavaCallback"); return; @@ -61,16 +60,6 @@ AndroidCommissioningWindowOpener::AndroidCommissioningWindowOpener(DeviceControl } } -AndroidCommissioningWindowOpener::~AndroidCommissioningWindowOpener() -{ - ChipLogError(Controller, "Delete AndroidCommissioningWindowOpener"); - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - if (mJavaCallback != nullptr) - { - env->DeleteGlobalRef(mJavaCallback); - } -} - CHIP_ERROR AndroidCommissioningWindowOpener::OpenBasicCommissioningWindow(DeviceController * controller, NodeId deviceId, Seconds16 timeout, jobject jcallback) { @@ -123,7 +112,7 @@ void AndroidCommissioningWindowOpener::OnOpenCommissioningWindowResponse(void * VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); - VerifyOrExit(self->mJavaCallback != nullptr, ChipLogError(Controller, "mJavaCallback is not allocated.")); + VerifyOrExit(self->mJavaCallback.HasValidObjectRef(), ChipLogError(Controller, "mJavaCallback is not allocated.")); if (status == CHIP_NO_ERROR) { @@ -137,7 +126,7 @@ void AndroidCommissioningWindowOpener::OnOpenCommissioningWindowResponse(void * { UtfString jManualPairingCode(env, manualPairingCode.c_str()); UtfString jQRCode(env, QRCode.c_str()); - env->CallVoidMethod(self->mJavaCallback, self->mOnSuccessMethod, static_cast(deviceId), + env->CallVoidMethod(self->mJavaCallback.ObjectRef(), self->mOnSuccessMethod, static_cast(deviceId), jManualPairingCode.jniValue(), jQRCode.jniValue()); } } @@ -145,7 +134,7 @@ void AndroidCommissioningWindowOpener::OnOpenCommissioningWindowResponse(void * { if (self->mOnErrorMethod != nullptr) { - env->CallVoidMethod(self->mJavaCallback, self->mOnErrorMethod, static_cast(status.GetValue()), + env->CallVoidMethod(self->mJavaCallback.ObjectRef(), self->mOnErrorMethod, static_cast(status.GetValue()), static_cast(deviceId)); } } @@ -156,7 +145,7 @@ void AndroidCommissioningWindowOpener::OnOpenCommissioningWindowResponse(void * void AndroidCommissioningWindowOpener::OnOpenBasicCommissioningWindowResponse(void * context, NodeId deviceId, CHIP_ERROR status) { auto * self = static_cast(context); - if (self->mJavaCallback != nullptr) + if (self->mJavaCallback.HasValidObjectRef()) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); @@ -167,7 +156,7 @@ void AndroidCommissioningWindowOpener::OnOpenBasicCommissioningWindowResponse(vo { UtfString jManualPairingCode(env, ""); UtfString jQRCode(env, ""); - env->CallVoidMethod(self->mJavaCallback, self->mOnSuccessMethod, static_cast(deviceId), + env->CallVoidMethod(self->mJavaCallback.ObjectRef(), self->mOnSuccessMethod, static_cast(deviceId), jManualPairingCode.jniValue(), jQRCode.jniValue()); } } @@ -175,7 +164,7 @@ void AndroidCommissioningWindowOpener::OnOpenBasicCommissioningWindowResponse(vo { if (self->mOnErrorMethod != nullptr) { - env->CallVoidMethod(self->mJavaCallback, self->mOnErrorMethod, static_cast(status.GetValue()), + env->CallVoidMethod(self->mJavaCallback.ObjectRef(), self->mOnErrorMethod, static_cast(status.GetValue()), static_cast(deviceId)); } } diff --git a/src/controller/java/AndroidCommissioningWindowOpener.h b/src/controller/java/AndroidCommissioningWindowOpener.h index 2d6a61f62d6743..cfed42e145d74f 100644 --- a/src/controller/java/AndroidCommissioningWindowOpener.h +++ b/src/controller/java/AndroidCommissioningWindowOpener.h @@ -19,6 +19,7 @@ #include #include +#include namespace chip { namespace Controller { @@ -44,7 +45,6 @@ class AndroidCommissioningWindowOpener : private CommissioningWindowOpener private: AndroidCommissioningWindowOpener(DeviceController * controller, jobject javaCallbackObject); - ~AndroidCommissioningWindowOpener(); static void OnOpenCommissioningWindowResponse(void * context, NodeId deviceId, CHIP_ERROR status, chip::SetupPayload payload); static void OnOpenBasicCommissioningWindowResponse(void * context, NodeId deviceId, CHIP_ERROR status); @@ -52,7 +52,7 @@ class AndroidCommissioningWindowOpener : private CommissioningWindowOpener chip::Callback::Callback mOnOpenCommissioningWindowCallback; chip::Callback::Callback mOnOpenBasicCommissioningWindowCallback; - jobject mJavaCallback; + chip::JniGlobalReference mJavaCallback; jmethodID mOnSuccessMethod = nullptr; jmethodID mOnErrorMethod = nullptr; }; diff --git a/src/controller/java/AndroidCurrentFabricRemover.cpp b/src/controller/java/AndroidCurrentFabricRemover.cpp index 1029177ae3db31..59798678f90bde 100644 --- a/src/controller/java/AndroidCurrentFabricRemover.cpp +++ b/src/controller/java/AndroidCurrentFabricRemover.cpp @@ -26,9 +26,13 @@ namespace Controller { AndroidCurrentFabricRemover::AndroidCurrentFabricRemover(DeviceController * controller, jobject jCallbackObject) : CurrentFabricRemover(controller), mOnRemoveCurrentFabricCallback(OnRemoveCurrentFabric, this) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - mJavaCallback = env->NewGlobalRef(jCallbackObject); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + if (mJavaCallback.Init(jCallbackObject) != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Fail to init mJavaObjectRef"); + return; + } jclass callbackClass = env->GetObjectClass(jCallbackObject); mOnSuccessMethod = env->GetMethodID(callbackClass, "onSuccess", "(J)V"); @@ -46,13 +50,6 @@ AndroidCurrentFabricRemover::AndroidCurrentFabricRemover(DeviceController * cont } } -AndroidCurrentFabricRemover::~AndroidCurrentFabricRemover() -{ - ChipLogError(Controller, "Delete AndroidCurrentFabricRemover"); - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - env->DeleteGlobalRef(mJavaCallback); -} - CHIP_ERROR AndroidCurrentFabricRemover::RemoveCurrentFabric(DeviceController * controller, NodeId remoteNodeId, jobject jcallback) { // Not using Platform::New because we want to keep our constructor private. @@ -66,6 +63,7 @@ CHIP_ERROR AndroidCurrentFabricRemover::RemoveCurrentFabric(DeviceController * c if (err != CHIP_NO_ERROR) { delete remover; + remover = nullptr; } // Else will clean up when the callback is called. return err; @@ -75,21 +73,21 @@ void AndroidCurrentFabricRemover::OnRemoveCurrentFabric(void * context, NodeId r { auto * self = static_cast(context); - if (self->mJavaCallback != nullptr) + if (self != nullptr && self->mJavaCallback.HasValidObjectRef()) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); if (err == CHIP_NO_ERROR) { if (self->mOnSuccessMethod != nullptr) { - env->CallVoidMethod(self->mJavaCallback, self->mOnSuccessMethod, static_cast(remoteNodeId)); + env->CallVoidMethod(self->mJavaCallback.ObjectRef(), self->mOnSuccessMethod, static_cast(remoteNodeId)); } } else { if (self->mOnErrorMethod != nullptr) { - env->CallVoidMethod(self->mJavaCallback, self->mOnErrorMethod, static_cast(err.GetValue()), + env->CallVoidMethod(self->mJavaCallback.ObjectRef(), self->mOnErrorMethod, static_cast(err.GetValue()), static_cast(remoteNodeId)); } } diff --git a/src/controller/java/AndroidCurrentFabricRemover.h b/src/controller/java/AndroidCurrentFabricRemover.h index a363411549a7f7..bbca17bbfcc57a 100644 --- a/src/controller/java/AndroidCurrentFabricRemover.h +++ b/src/controller/java/AndroidCurrentFabricRemover.h @@ -19,6 +19,7 @@ #include #include +#include namespace chip { namespace Controller { @@ -34,12 +35,11 @@ class AndroidCurrentFabricRemover : private CurrentFabricRemover private: AndroidCurrentFabricRemover(DeviceController * controller, jobject javaCallbackObject); - ~AndroidCurrentFabricRemover(); static void OnRemoveCurrentFabric(void * context, NodeId remoteNodeId, CHIP_ERROR status); chip::Callback::Callback mOnRemoveCurrentFabricCallback; - jobject mJavaCallback; + chip::JniGlobalReference mJavaCallback; jmethodID mOnSuccessMethod = nullptr; jmethodID mOnErrorMethod = nullptr; }; diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index b02e93ba48c8a7..74e1187ef2a03b 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -48,10 +48,6 @@ using namespace TLV; AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() { - if ((mJavaVM != nullptr) && (mJavaObjectRef != nullptr)) - { - JniReferences::GetInstance().GetEnvForCurrentThread()->DeleteGlobalRef(mJavaObjectRef); - } mController->Shutdown(); #ifndef JAVA_MATTER_CONTROLLER_TEST @@ -83,14 +79,17 @@ AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() void AndroidDeviceControllerWrapper::SetJavaObjectRef(JavaVM * vm, jobject obj) { - mJavaVM = vm; - mJavaObjectRef = JniReferences::GetInstance().GetEnvForCurrentThread()->NewGlobalRef(obj); + mJavaVM = vm; + if (mJavaObjectRef.Init(obj) != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Fail to init mJavaObjectRef"); + } } void AndroidDeviceControllerWrapper::CallJavaMethod(const char * methodName, jint argument) { - JniReferences::GetInstance().CallVoidInt(JniReferences::GetInstance().GetEnvForCurrentThread(), mJavaObjectRef, methodName, - argument); + JniReferences::GetInstance().CallVoidInt(JniReferences::GetInstance().GetEnvForCurrentThread(), mJavaObjectRef.ObjectRef(), + methodName, argument); } AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( @@ -235,7 +234,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( err = opCredsIssuer->Initialize(wrapper->mExampleStorage); #else // TODO: Init IPK Epoch Key in opcreds issuer, so that commissionees get the right IPK - err = opCredsIssuer->Initialize(*wrapper.get(), &wrapper->mAutoCommissioner, wrapper.get()->mJavaObjectRef); + err = opCredsIssuer->Initialize(*wrapper.get(), &wrapper->mAutoCommissioner, wrapper.get()->mJavaObjectRef.ObjectRef()); #endif if (err != CHIP_NO_ERROR) { @@ -534,21 +533,18 @@ CHIP_ERROR AndroidDeviceControllerWrapper::UpdateDeviceAttestationDelegateBridge chip::Optional expiryTimeoutSecs, bool shouldWaitAfterDeviceAttestation) { - CHIP_ERROR err = CHIP_NO_ERROR; - - DeviceAttestationDelegateBridge * delegateBridge = - new DeviceAttestationDelegateBridge(deviceAttestationDelegate, expiryTimeoutSecs, shouldWaitAfterDeviceAttestation); - VerifyOrExit(delegateBridge != nullptr, err = CHIP_ERROR_NO_MEMORY); - + chip::JniGlobalReference deviceAttestationDelegateRef; + ReturnErrorOnFailure(deviceAttestationDelegateRef.Init(deviceAttestationDelegate)); + DeviceAttestationDelegateBridge * delegateBridge = new DeviceAttestationDelegateBridge( + std::move(deviceAttestationDelegateRef), expiryTimeoutSecs, shouldWaitAfterDeviceAttestation); + VerifyOrReturnError(delegateBridge != nullptr, CHIP_ERROR_NO_MEMORY); if (mDeviceAttestationDelegateBridge != nullptr) { delete mDeviceAttestationDelegateBridge; } mDeviceAttestationDelegateBridge = delegateBridge; - -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR AndroidDeviceControllerWrapper::UpdateAttestationTrustStoreBridge(jobject attestationTrustStoreDelegate, @@ -556,8 +552,11 @@ CHIP_ERROR AndroidDeviceControllerWrapper::UpdateAttestationTrustStoreBridge(job { CHIP_ERROR err = CHIP_NO_ERROR; - DeviceAttestationVerifier * deviceAttestationVerifier = nullptr; - AttestationTrustStoreBridge * attestationTrustStoreBridge = new AttestationTrustStoreBridge(attestationTrustStoreDelegate); + DeviceAttestationVerifier * deviceAttestationVerifier = nullptr; + chip::JniGlobalReference attestationTrustStoreDelegateRef; + ReturnErrorOnFailure(attestationTrustStoreDelegateRef.Init(attestationTrustStoreDelegate)); + AttestationTrustStoreBridge * attestationTrustStoreBridge = + new AttestationTrustStoreBridge(std::move(attestationTrustStoreDelegateRef)); VerifyOrExit(attestationTrustStoreBridge != nullptr, err = CHIP_ERROR_NO_MEMORY); deviceAttestationVerifier = new Credentials::DefaultDACVerifier(attestationTrustStoreBridge); @@ -568,12 +567,14 @@ CHIP_ERROR AndroidDeviceControllerWrapper::UpdateAttestationTrustStoreBridge(job delete mAttestationTrustStoreBridge; } mAttestationTrustStoreBridge = attestationTrustStoreBridge; + attestationTrustStoreBridge = nullptr; if (mDeviceAttestationVerifier != nullptr) { delete mDeviceAttestationVerifier; } mDeviceAttestationVerifier = deviceAttestationVerifier; + deviceAttestationVerifier = nullptr; if (cdTrustKeys != nullptr) { @@ -606,6 +607,7 @@ CHIP_ERROR AndroidDeviceControllerWrapper::UpdateAttestationTrustStoreBridge(job if (attestationTrustStoreBridge != nullptr) { delete attestationTrustStoreBridge; + attestationTrustStoreBridge = nullptr; } } @@ -692,10 +694,10 @@ void AndroidDeviceControllerWrapper::OnCommissioningComplete(NodeId deviceId, CH JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jmethodID onCommissioningCompleteMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningComplete", "(JI)V", + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef.ObjectRef(), "onCommissioningComplete", "(JI)V", &onCommissioningCompleteMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); - env->CallVoidMethod(mJavaObjectRef, onCommissioningCompleteMethod, static_cast(deviceId), + env->CallVoidMethod(mJavaObjectRef.ObjectRef(), onCommissioningCompleteMethod, static_cast(deviceId), static_cast(error.AsInteger())); if (ssidStr != nullptr) @@ -726,12 +728,12 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); jmethodID onCommissioningStatusUpdateMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningStatusUpdate", + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef.ObjectRef(), "onCommissioningStatusUpdate", "(JLjava/lang/String;I)V", &onCommissioningStatusUpdateMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); UtfString jStageCompleted(env, StageToString(stageCompleted)); - env->CallVoidMethod(mJavaObjectRef, onCommissioningStatusUpdateMethod, static_cast(peerId.GetNodeId()), + env->CallVoidMethod(mJavaObjectRef.ObjectRef(), onCommissioningStatusUpdateMethod, static_cast(peerId.GetNodeId()), jStageCompleted.jniValue(), static_cast(error.AsInteger())); } @@ -741,7 +743,7 @@ void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(const chip::Control chip::DeviceLayer::StackUnlock unlock; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jmethodID onReadCommissioningInfoMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onReadCommissioningInfo", "(IIII)V", + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef.ObjectRef(), "onReadCommissioningInfo", "(IIII)V", &onReadCommissioningInfoMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); @@ -749,7 +751,7 @@ void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(const chip::Control mUserActiveModeTriggerHint = info.icd.userActiveModeTriggerHint; CopyCharSpanToMutableCharSpan(info.icd.userActiveModeTriggerInstruction, mUserActiveModeTriggerInstruction); - env->CallVoidMethod(mJavaObjectRef, onReadCommissioningInfoMethod, static_cast(info.basic.vendorId), + env->CallVoidMethod(mJavaObjectRef.ObjectRef(), onReadCommissioningInfoMethod, static_cast(info.basic.vendorId), static_cast(info.basic.productId), static_cast(info.network.wifi.endpoint), static_cast(info.network.thread.endpoint)); } @@ -767,7 +769,7 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Error invoking Java callback: no JNIEnv")); err = JniReferences::GetInstance().FindMethod( - env, mJavaObjectRef, "onScanNetworksSuccess", + env, mJavaObjectRef.ObjectRef(), "onScanNetworksSuccess", "(Ljava/lang/Integer;Ljava/util/Optional;Ljava/util/Optional;Ljava/util/Optional;)V", &javaMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error invoking Java callback: %s", ErrorStr(err))); @@ -923,7 +925,7 @@ void AndroidDeviceControllerWrapper::OnScanNetworksSuccess( chip::JniReferences::GetInstance().CreateOptional(ThreadScanResultsInsideOptional, ThreadScanResults); } - env->CallVoidMethod(mJavaObjectRef, javaMethod, NetworkingStatus, DebugText, WiFiScanResults, ThreadScanResults); + env->CallVoidMethod(mJavaObjectRef.ObjectRef(), javaMethod, NetworkingStatus, DebugText, WiFiScanResults, ThreadScanResults); } void AndroidDeviceControllerWrapper::OnScanNetworksFailure(CHIP_ERROR error) @@ -938,11 +940,11 @@ void AndroidDeviceControllerWrapper::OnICDRegistrationInfoRequired() chip::DeviceLayer::StackUnlock unlock; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jmethodID onICDRegistrationInfoRequiredMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onICDRegistrationInfoRequired", "()V", - &onICDRegistrationInfoRequiredMethod); + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef.ObjectRef(), "onICDRegistrationInfoRequired", + "()V", &onICDRegistrationInfoRequiredMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); - env->CallVoidMethod(mJavaObjectRef, onICDRegistrationInfoRequiredMethod); + env->CallVoidMethod(mJavaObjectRef.ObjectRef(), onICDRegistrationInfoRequiredMethod); } void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::NodeId icdNodeId, uint32_t icdCounter) @@ -985,7 +987,7 @@ void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::NodeId icdN jobject icdDeviceInfoObj = nullptr; jbyteArray jSymmetricKey = nullptr; CHIP_ERROR methodErr = - JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onICDRegistrationComplete", + JniReferences::GetInstance().FindMethod(env, mJavaObjectRef.ObjectRef(), "onICDRegistrationComplete", "(ILchip/devicecontroller/ICDDeviceInfo;)V", &onICDRegistrationCompleteMethod); VerifyOrReturn(methodErr == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, methodErr.Format())); @@ -1009,7 +1011,8 @@ void AndroidDeviceControllerWrapper::OnICDRegistrationComplete(chip::NodeId icdN static_cast(mAutoCommissioner.GetCommissioningParameters().GetICDMonitoredSubject().Value()), static_cast(Controller()->GetFabricId()), static_cast(Controller()->GetFabricIndex())); - env->CallVoidMethod(mJavaObjectRef, onICDRegistrationCompleteMethod, static_cast(err.AsInteger()), icdDeviceInfoObj); + env->CallVoidMethod(mJavaObjectRef.ObjectRef(), onICDRegistrationCompleteMethod, static_cast(err.AsInteger()), + icdDeviceInfoObj); } CHIP_ERROR AndroidDeviceControllerWrapper::SyncGetKeyValue(const char * key, void * value, uint16_t & size) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index d5b07cf7164a75..ac279370f62c4a 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -63,7 +63,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Controller::DeviceCommissioner * Controller() { return mController.get(); } void SetJavaObjectRef(JavaVM * vm, jobject obj); - jobject JavaObjectRef() { return mJavaObjectRef; } + jobject JavaObjectRef() { return mJavaObjectRef.ObjectRef(); } jlong ToJNIHandle(); #ifndef JAVA_MATTER_CONTROLLER_TEST @@ -224,8 +224,8 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::app::DefaultICDClientStorage mICDClientStorage; - JavaVM * mJavaVM = nullptr; - jobject mJavaObjectRef = nullptr; + JavaVM * mJavaVM = nullptr; + chip::JniGlobalReference mJavaObjectRef; #ifdef JAVA_MATTER_CONTROLLER_TEST ExampleOperationalCredentialsIssuerPtr mOpCredsIssuer; PersistentStorage mExampleStorage; diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 056c87c4d1b464..4c1d72b9c4873f 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -25,17 +25,6 @@ using namespace chip; -AttestationTrustStoreBridge::~AttestationTrustStoreBridge() -{ - if (mAttestationTrustStoreDelegate != nullptr) - { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); - env->DeleteGlobalRef(mAttestationTrustStoreDelegate); - mAttestationTrustStoreDelegate = nullptr; - } -} - CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const { @@ -73,19 +62,20 @@ CHIP_ERROR AttestationTrustStoreBridge::GetPaaCertFromJava(const chip::ByteSpan VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); JniLocalReferenceScope scope(env); + VerifyOrReturnError(mAttestationTrustStoreDelegate.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/AttestationTrustStoreDelegate", attestationTrustStoreDelegateCls); VerifyOrReturnError(attestationTrustStoreDelegateCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); - JniReferences::GetInstance().FindMethod(env, mAttestationTrustStoreDelegate, "getProductAttestationAuthorityCert", "([B)[B", - &getProductAttestationAuthorityCertMethod); + JniReferences::GetInstance().FindMethod(env, mAttestationTrustStoreDelegate.ObjectRef(), "getProductAttestationAuthorityCert", + "([B)[B", &getProductAttestationAuthorityCertMethod); VerifyOrReturnError(getProductAttestationAuthorityCertMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); JniReferences::GetInstance().N2J_ByteArray(env, skid.data(), static_cast(skid.size()), javaSkid); VerifyOrReturnError(javaSkid != nullptr, CHIP_ERROR_NO_MEMORY); - jbyteArray javaPaaCert = - (jbyteArray) env->CallObjectMethod(mAttestationTrustStoreDelegate, getProductAttestationAuthorityCertMethod, javaSkid); + jbyteArray javaPaaCert = (jbyteArray) env->CallObjectMethod(mAttestationTrustStoreDelegate.ObjectRef(), + getProductAttestationAuthorityCertMethod, javaSkid); VerifyOrReturnError(javaPaaCert != nullptr, CHIP_ERROR_CA_CERT_NOT_FOUND); JniByteArray paaCertBytes(env, javaPaaCert); diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index be84be2f530307..0b22a8f5ce6c18 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -21,16 +21,15 @@ class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustStore { public: - AttestationTrustStoreBridge(jobject attestationTrustStoreDelegate) : - mAttestationTrustStoreDelegate(attestationTrustStoreDelegate) + AttestationTrustStoreBridge(chip::JniGlobalReference && attestationTrustStoreDelegate) : + mAttestationTrustStoreDelegate(std::move(attestationTrustStoreDelegate)) {} - ~AttestationTrustStoreBridge(); CHIP_ERROR GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const override; protected: - jobject mAttestationTrustStoreDelegate = nullptr; + chip::JniGlobalReference mAttestationTrustStoreDelegate; CHIP_ERROR GetPaaCertFromJava(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const; }; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 29cab3b22424e3..26870b5752caab 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -101,13 +101,9 @@ static CHIP_ERROR ParseDataVersionFilterList(jobject dataVersionFilterList, static CHIP_ERROR IsWildcardChipPathId(jobject chipPathId, bool & isWildcard); namespace { - -JavaVM * sJVM; - +JavaVM * sJVM = nullptr; pthread_t sIOThread = PTHREAD_NULL; - -jclass sChipDeviceControllerExceptionCls = nullptr; - +chip::JniGlobalReference sChipDeviceControllerExceptionCls; } // namespace // NOTE: Remote device ID is in sync with the echo server device id @@ -136,9 +132,11 @@ jint JNI_OnLoad(JavaVM * jvm, void * reserved) ChipLogProgress(Controller, "Loading Java class references."); // Get various class references need by the API. - err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/ChipDeviceControllerException", - sChipDeviceControllerExceptionCls); - SuccessOrExit(err); + jclass controllerExceptionCls; + err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/ChipDeviceControllerException", + controllerExceptionCls); + SuccessOrExit(err = sChipDeviceControllerExceptionCls.Init(controllerExceptionCls)); + ChipLogProgress(Controller, "Java class references loaded."); #ifndef JAVA_MATTER_CONTROLLER_TEST @@ -514,11 +512,8 @@ JNI_METHOD(void, setDeviceAttestationDelegate) chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeoutSecs)); bool shouldWaitAfterDeviceAttestation = false; jclass deviceAttestationDelegateCls = nullptr; - jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); - - VerifyOrExit(deviceAttestationDelegateRef != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT); - JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate", - deviceAttestationDelegateCls); + JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate", + deviceAttestationDelegateCls); VerifyOrExit(deviceAttestationDelegateCls != nullptr, err = CHIP_JNI_ERROR_TYPE_NOT_FOUND); if (env->IsInstanceOf(deviceAttestationDelegate, deviceAttestationDelegateCls)) @@ -526,9 +521,8 @@ JNI_METHOD(void, setDeviceAttestationDelegate) shouldWaitAfterDeviceAttestation = true; } - err = wrapper->UpdateDeviceAttestationDelegateBridge(deviceAttestationDelegateRef, timeoutSecs, + err = wrapper->UpdateDeviceAttestationDelegateBridge(deviceAttestationDelegate, timeoutSecs, shouldWaitAfterDeviceAttestation); - SuccessOrExit(err); } exit: @@ -550,8 +544,7 @@ JNI_METHOD(void, setAttestationTrustStoreDelegate) if (attestationTrustStoreDelegate != nullptr) { - jobject attestationTrustStoreDelegateRef = env->NewGlobalRef(attestationTrustStoreDelegate); - err = wrapper->UpdateAttestationTrustStoreBridge(attestationTrustStoreDelegateRef, cdTrustKeys); + err = wrapper->UpdateAttestationTrustStoreBridge(attestationTrustStoreDelegate, cdTrustKeys); SuccessOrExit(err); } diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index 5c695da3b4f9bb..b57654d18a0415 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -68,7 +68,7 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( ChipLogProgress(Controller, "OnDeviceAttestationCompleted with result: %hu", static_cast(attestationResult)); mResult = attestationResult; - if (mDeviceAttestationDelegate != nullptr) + if (mDeviceAttestationDelegate.HasValidObjectRef()) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); @@ -79,10 +79,10 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( VerifyOrReturn(deviceAttestationDelegateCls != nullptr, ChipLogError(Controller, "Could not find device attestation delegate class.")); - if (env->IsInstanceOf(mDeviceAttestationDelegate, deviceAttestationDelegateCls)) + if (env->IsInstanceOf(mDeviceAttestationDelegate.ObjectRef(), deviceAttestationDelegateCls)) { jmethodID onDeviceAttestationCompletedMethod; - JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationCompleted", + JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate.ObjectRef(), "onDeviceAttestationCompleted", "(JLchip/devicecontroller/AttestationInfo;I)V", &onDeviceAttestationCompletedMethod); VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, @@ -98,19 +98,8 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); } - env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, reinterpret_cast(device), - javaAttestationInfo, static_cast(attestationResult)); + env->CallVoidMethod(mDeviceAttestationDelegate.ObjectRef(), onDeviceAttestationCompletedMethod, + reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); } } } - -DeviceAttestationDelegateBridge::~DeviceAttestationDelegateBridge() -{ - if (mDeviceAttestationDelegate != nullptr) - { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); - env->DeleteGlobalRef(mDeviceAttestationDelegate); - mDeviceAttestationDelegate = nullptr; - } -} diff --git a/src/controller/java/DeviceAttestationDelegateBridge.h b/src/controller/java/DeviceAttestationDelegateBridge.h index 214c5d78ec95ae..448a8ab2f49f11 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.h +++ b/src/controller/java/DeviceAttestationDelegateBridge.h @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -24,15 +25,13 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestationDelegate { public: - DeviceAttestationDelegateBridge(jobject deviceAttestationDelegate, chip::Optional expiryTimeoutSecs, - bool shouldWaitAfterDeviceAttestation) : + DeviceAttestationDelegateBridge(chip::JniGlobalReference && deviceAttestationDelegate, + chip::Optional expiryTimeoutSecs, bool shouldWaitAfterDeviceAttestation) : mResult(chip::Credentials::AttestationVerificationResult::kSuccess), - mDeviceAttestationDelegate(deviceAttestationDelegate), mExpiryTimeoutSecs(expiryTimeoutSecs), + mDeviceAttestationDelegate(std::move(deviceAttestationDelegate)), mExpiryTimeoutSecs(expiryTimeoutSecs), mShouldWaitAfterDeviceAttestation(shouldWaitAfterDeviceAttestation) {} - ~DeviceAttestationDelegateBridge(); - chip::Optional FailSafeExpiryTimeoutSecs() const override { return mExpiryTimeoutSecs; } void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, @@ -45,7 +44,7 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestat private: chip::Credentials::AttestationVerificationResult mResult; - jobject mDeviceAttestationDelegate = nullptr; + chip::JniGlobalReference mDeviceAttestationDelegate; chip::Optional mExpiryTimeoutSecs; const bool mShouldWaitAfterDeviceAttestation; }; diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index ae5942f5a4fdc3..24b9efcec73ff2 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -8549,6 +8549,8 @@ - EnergyEVSEMode - DeviceEnergyManagementMode - Messages + - ElectricalPowerMeasurement + - PowerTopology attributes: DoorLock: # Aliro is not ready yet. diff --git a/src/lib/support/JniReferences.cpp b/src/lib/support/JniReferences.cpp index 76c3f77e8bbecf..506ae0a82b7788 100644 --- a/src/lib/support/JniReferences.cpp +++ b/src/lib/support/JniReferences.cpp @@ -34,6 +34,7 @@ void JniReferences::SetJavaVm(JavaVM * jvm, const char * clsType) // thread, meaning it won't find our Chip classes. // https://developer.android.com/training/articles/perf-jni#faq_FindClass JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Support, "env can not be nullptr")); // Any chip.devicecontroller.* class will work here - just need something to call getClassLoader() on. jclass chipClass = env->FindClass(clsType); VerifyOrReturn(chipClass != nullptr, ChipLogError(Support, "clsType can not be found")); @@ -42,12 +43,26 @@ void JniReferences::SetJavaVm(JavaVM * jvm, const char * clsType) jclass classLoaderClass = env->FindClass("java/lang/ClassLoader"); jmethodID getClassLoaderMethod = env->GetMethodID(classClass, "getClassLoader", "()Ljava/lang/ClassLoader;"); - mClassLoader = env->NewGlobalRef(env->CallObjectMethod(chipClass, getClassLoaderMethod)); + CHIP_ERROR err = mClassLoader.Init(env->CallObjectMethod(chipClass, getClassLoaderMethod)); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mClassLoader")); mFindClassMethod = env->GetMethodID(classLoaderClass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;"); - chip::JniReferences::GetInstance().GetClassRef(env, "java/util/List", mListClass); - chip::JniReferences::GetInstance().GetClassRef(env, "java/util/ArrayList", mArrayListClass); - chip::JniReferences::GetInstance().GetClassRef(env, "java/util/HashMap", mHashMapClass); + jclass listClass = nullptr; + jclass arrayListClass = nullptr; + jclass hashMapClass = nullptr; + + err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/List", listClass); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to get local class ref for List")); + err = mListClass.Init(static_cast(listClass)); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mListClass")); + err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/ArrayList", arrayListClass); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to get local class ref for ArrayList")); + err = mArrayListClass.Init(static_cast(arrayListClass)); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mArrayListClass")); + err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/HashMap", hashMapClass); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to get local class ref for HashMap")); + mHashMapClass.Init(static_cast(hashMapClass)); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mHashMapClass")); } JNIEnv * JniReferences::GetEnvForCurrentThread() @@ -76,21 +91,12 @@ JNIEnv * JniReferences::GetEnvForCurrentThread() return env; } -CHIP_ERROR JniReferences::GetClassRef(JNIEnv * env, const char * clsType, jclass & outCls) -{ - jclass cls = nullptr; - CHIP_ERROR err = GetLocalClassRef(env, clsType, cls); - ReturnErrorOnFailure(err); - outCls = (jclass) env->NewGlobalRef((jobject) cls); - VerifyOrReturnError(outCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); - - return err; -} - CHIP_ERROR JniReferences::GetLocalClassRef(JNIEnv * env, const char * clsType, jclass & outCls) { jclass cls = nullptr; + VerifyOrReturnError(mClassLoader.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + // Try `j$/util/Optional` when enabling Java8. if (strcmp(clsType, "java/util/Optional") == 0) { @@ -107,7 +113,7 @@ CHIP_ERROR JniReferences::GetLocalClassRef(JNIEnv * env, const char * clsType, j if (cls == nullptr) { // Try the cached classloader if FindClass() didn't work. - cls = static_cast(env->CallObjectMethod(mClassLoader, mFindClassMethod, env->NewStringUTF(clsType))); + cls = static_cast(env->CallObjectMethod(mClassLoader.ObjectRef(), mFindClassMethod, env->NewStringUTF(clsType))); VerifyOrReturnError(cls != nullptr && env->ExceptionCheck() != JNI_TRUE, CHIP_JNI_ERROR_TYPE_NOT_FOUND); } @@ -117,17 +123,14 @@ CHIP_ERROR JniReferences::GetLocalClassRef(JNIEnv * env, const char * clsType, j CHIP_ERROR JniReferences::N2J_ByteArray(JNIEnv * env, const uint8_t * inArray, jsize inArrayLen, jbyteArray & outArray) { - CHIP_ERROR err = CHIP_NO_ERROR; - outArray = env->NewByteArray(inArrayLen); - VerifyOrReturnError(outArray != NULL, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(outArray != nullptr, CHIP_ERROR_NO_MEMORY); env->ExceptionClear(); env->SetByteArrayRegion(outArray, 0, inArrayLen, (jbyte *) inArray); - VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); + VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); -exit: - return err; + return CHIP_NO_ERROR; } static std::string StrReplaceAll(const std::string & source, const std::string & from, const std::string & to) @@ -241,21 +244,28 @@ void JniReferences::ThrowError(JNIEnv * env, jclass exceptionCls, CHIP_ERROR err { env->ExceptionClear(); jmethodID constructor = env->GetMethodID(exceptionCls, "", "(JLjava/lang/String;)V"); - VerifyOrReturn(constructor != NULL); + VerifyOrReturn(constructor != nullptr); jstring jerrStr = env->NewStringUTF(ErrorStr(errToThrow)); - jthrowable outEx = (jthrowable) env->NewObject(exceptionCls, constructor, static_cast(errToThrow.AsInteger()), jerrStr); + jthrowable outEx = + static_cast(env->NewObject(exceptionCls, constructor, static_cast(errToThrow.AsInteger()), jerrStr)); VerifyOrReturn(!env->ExceptionCheck()); env->Throw(outEx); } +void JniReferences::ThrowError(JNIEnv * env, JniGlobalReference & exceptionCls, CHIP_ERROR errToThrow) +{ + VerifyOrReturn(exceptionCls.HasValidObjectRef(), ChipLogError(Support, "exceptionCls is invalid, failed to throw error")); + ThrowError(env, static_cast(exceptionCls.ObjectRef()), errToThrow); +} + CHIP_ERROR JniReferences::CreateOptional(jobject objectToWrap, jobject & outOptional) { JNIEnv * env = GetEnvForCurrentThread(); - jclass optionalCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/Optional", optionalCls); - VerifyOrReturnError(optionalCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); + VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + jclass optionalCls = nullptr; + ReturnErrorOnFailure(chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/Optional", optionalCls)); jmethodID ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Ljava/util/Optional;"); env->ExceptionClear(); @@ -278,10 +288,9 @@ CHIP_ERROR JniReferences::CreateOptional(jobject objectToWrap, jobject & outOpti CHIP_ERROR JniReferences::GetOptionalValue(jobject optionalObj, jobject & optionalValue) { JNIEnv * env = GetEnvForCurrentThread(); - jclass optionalCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/Optional", optionalCls); - VerifyOrReturnError(optionalCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); - + VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + jclass optionalCls = nullptr; + ReturnErrorOnFailure(chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/Optional", optionalCls)); jmethodID isPresentMethod = env->GetMethodID(optionalCls, "isPresent", "()Z"); VerifyOrReturnError(isPresentMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); jboolean isPresent = optionalObj && env->CallBooleanMethod(optionalObj, isPresentMethod); @@ -301,8 +310,11 @@ CHIP_ERROR JniReferences::GetOptionalValue(jobject optionalObj, jobject & option jint JniReferences::IntegerToPrimitive(jobject boxedInteger) { JNIEnv * env = GetEnvForCurrentThread(); - jclass boxedTypeCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Integer", boxedTypeCls); + VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr")); + jclass boxedTypeCls = nullptr; + CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Integer", boxedTypeCls); + VerifyOrReturnValue(err == CHIP_NO_ERROR, 0, + ChipLogError(Support, "IntegerToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format())); jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "intValue", "()I"); return env->CallIntMethod(boxedInteger, valueMethod); @@ -311,9 +323,11 @@ jint JniReferences::IntegerToPrimitive(jobject boxedInteger) jlong JniReferences::LongToPrimitive(jobject boxedLong) { JNIEnv * env = GetEnvForCurrentThread(); - jclass boxedTypeCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Long", boxedTypeCls); - + VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr")); + jclass boxedTypeCls = nullptr; + CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Long", boxedTypeCls); + VerifyOrReturnValue(err == CHIP_NO_ERROR, 0, + ChipLogError(Support, "LongToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format())); jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "longValue", "()J"); return env->CallLongMethod(boxedLong, valueMethod); } @@ -321,8 +335,11 @@ jlong JniReferences::LongToPrimitive(jobject boxedLong) jboolean JniReferences::BooleanToPrimitive(jobject boxedBoolean) { JNIEnv * env = GetEnvForCurrentThread(); - jclass boxedTypeCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Boolean", boxedTypeCls); + VerifyOrReturnValue(env != nullptr, false, ChipLogError(Support, "env cannot be nullptr")); + jclass boxedTypeCls = nullptr; + CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Boolean", boxedTypeCls); + VerifyOrReturnValue(err == CHIP_NO_ERROR, false, + ChipLogError(Support, "BooleanToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format())); jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "booleanValue", "()Z"); return env->CallBooleanMethod(boxedBoolean, valueMethod); @@ -331,8 +348,11 @@ jboolean JniReferences::BooleanToPrimitive(jobject boxedBoolean) jfloat JniReferences::FloatToPrimitive(jobject boxedFloat) { JNIEnv * env = GetEnvForCurrentThread(); - jclass boxedTypeCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Float", boxedTypeCls); + VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr")); + jclass boxedTypeCls = nullptr; + CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Float", boxedTypeCls); + VerifyOrReturnValue(err == CHIP_NO_ERROR, 0, + ChipLogError(Support, "FloatToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format())); jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "floatValue", "()F"); return env->CallFloatMethod(boxedFloat, valueMethod); @@ -341,8 +361,11 @@ jfloat JniReferences::FloatToPrimitive(jobject boxedFloat) jdouble JniReferences::DoubleToPrimitive(jobject boxedDouble) { JNIEnv * env = GetEnvForCurrentThread(); - jclass boxedTypeCls; - chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Double", boxedTypeCls); + VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr")); + jclass boxedTypeCls = nullptr; + CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Double", boxedTypeCls); + VerifyOrReturnValue(err == CHIP_NO_ERROR, 0, + ChipLogError(Support, "DoubleToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format())); jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "doubleValue", "()D"); return env->CallDoubleMethod(boxedDouble, valueMethod); @@ -352,7 +375,7 @@ CHIP_ERROR JniReferences::CallSubscriptionEstablished(jobject javaCallback, long { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); jmethodID subscriptionEstablishedMethod; err = chip::JniReferences::GetInstance().FindMethod(env, javaCallback, "onSubscriptionEstablished", "(J)V", &subscriptionEstablishedMethod); @@ -366,99 +389,107 @@ CHIP_ERROR JniReferences::CallSubscriptionEstablished(jobject javaCallback, long CHIP_ERROR JniReferences::CreateArrayList(jobject & outList) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - - jmethodID arrayListCtor = env->GetMethodID(mArrayListClass, "", "()V"); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mArrayListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + jclass ref = static_cast(mArrayListClass.ObjectRef()); + jmethodID arrayListCtor = env->GetMethodID(ref, "", "()V"); VerifyOrReturnError(arrayListCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); - outList = env->NewObject(mArrayListClass, arrayListCtor); + outList = env->NewObject(ref, arrayListCtor); VerifyOrReturnError(outList != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::AddToList(jobject list, jobject objectToAdd) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - - jmethodID addMethod = env->GetMethodID(mListClass, "add", "(Ljava/lang/Object;)Z"); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mArrayListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + jclass ref = static_cast(mListClass.ObjectRef()); + jmethodID addMethod = env->GetMethodID(ref, "add", "(Ljava/lang/Object;)Z"); VerifyOrReturnError(addMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); env->CallBooleanMethod(list, addMethod, objectToAdd); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::CreateHashMap(jobject & outMap) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - - jmethodID hashMapCtor = env->GetMethodID(mHashMapClass, "", "()V"); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mHashMapClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + jclass ref = static_cast(mHashMapClass.ObjectRef()); + jmethodID hashMapCtor = env->GetMethodID(ref, "", "()V"); VerifyOrReturnError(hashMapCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); - outMap = env->NewObject(mHashMapClass, hashMapCtor); + outMap = env->NewObject(ref, hashMapCtor); VerifyOrReturnError(outMap != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::PutInMap(jobject map, jobject key, jobject value) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - - jmethodID putMethod = env->GetMethodID(mHashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mHashMapClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + jclass ref = static_cast(mHashMapClass.ObjectRef()); + jmethodID putMethod = env->GetMethodID(ref, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); VerifyOrReturnError(putMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); env->CallObjectMethod(map, putMethod, key, value); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::GetListSize(jobject list, jint & size) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + jclass ref = static_cast(mListClass.ObjectRef()); - jmethodID sizeMethod = env->GetMethodID(mListClass, "size", "()I"); + jmethodID sizeMethod = env->GetMethodID(ref, "size", "()I"); VerifyOrReturnError(sizeMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); size = env->CallIntMethod(list, sizeMethod); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::GetListItem(jobject list, jint index, jobject & outItem) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + jclass ref = static_cast(mListClass.ObjectRef()); - jmethodID getMethod = env->GetMethodID(mListClass, "get", "(I)Ljava/lang/Object;"); + jmethodID getMethod = env->GetMethodID(ref, "get", "(I)Ljava/lang/Object;"); VerifyOrReturnError(getMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); outItem = env->CallObjectMethod(list, getMethod, index); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::GetObjectField(jobject objectToRead, const char * name, const char * signature, jobject & outObject) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrReturnError(objectToRead != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(objectToRead != nullptr, CHIP_ERROR_INVALID_ARGUMENT); jclass objClass = env->GetObjectClass(objectToRead); jfieldID field = env->GetFieldID(objClass, name, signature); outObject = env->GetObjectField(objectToRead, field); - return err; + return CHIP_NO_ERROR; } CHIP_ERROR JniReferences::CharToStringUTF(const chip::CharSpan & charSpan, jobject & outStr) { - JNIEnv * env = GetEnvForCurrentThread(); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); jobject jbyteBuffer = env->NewDirectByteBuffer((void *) charSpan.data(), static_cast(charSpan.size())); jclass charSetClass = env->FindClass("java/nio/charset/Charset"); @@ -517,4 +548,26 @@ CHIP_ERROR JniReferences::CharToStringUTF(const chip::CharSpan & charSpan, jobje return CHIP_NO_ERROR; } +CHIP_ERROR JniGlobalReference::Init(jobject aObjectRef) +{ + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + VerifyOrReturnError(aObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + VerifyOrReturnError(mObjectRef == nullptr, CHIP_ERROR_INCORRECT_STATE); + mObjectRef = env->NewGlobalRef(aObjectRef); + VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); + VerifyOrReturnError(mObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + return CHIP_NO_ERROR; +} + +void JniGlobalReference::Reset() +{ + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + if (env != nullptr && mObjectRef != nullptr) + { + env->DeleteGlobalRef(mObjectRef); + mObjectRef = nullptr; + } +} + } // namespace chip diff --git a/src/lib/support/JniReferences.h b/src/lib/support/JniReferences.h index 15f69a3c13888d..96adcc3ba62aaa 100644 --- a/src/lib/support/JniReferences.h +++ b/src/lib/support/JniReferences.h @@ -24,7 +24,63 @@ #include #include +#define JNI_LOCAL_REF_COUNT 256 + namespace chip { +class JniLocalReferenceScope +{ +public: + explicit JniLocalReferenceScope(JNIEnv * env) : mEnv(env) + { + if (mEnv->PushLocalFrame(JNI_LOCAL_REF_COUNT) == 0) + { + mlocalFramePushed = true; + } + } + + ~JniLocalReferenceScope() + { + if (mlocalFramePushed) + { + mEnv->PopLocalFrame(nullptr); + mlocalFramePushed = false; + } + } + + // Delete copy constructor and copy assignment operator + JniLocalReferenceScope(const JniLocalReferenceScope &) = delete; + JniLocalReferenceScope & operator=(const JniLocalReferenceScope &) = delete; + +private: + JNIEnv * const mEnv; + bool mlocalFramePushed = false; +}; + +class JniGlobalReference +{ +public: + JniGlobalReference() {} + + CHIP_ERROR Init(jobject aObjectRef); + + JniGlobalReference(JniGlobalReference && aOther) + { + mObjectRef = aOther.mObjectRef; + aOther.mObjectRef = nullptr; + } + + ~JniGlobalReference() { Reset(); } + + void Reset(); + + jobject ObjectRef() const { return mObjectRef; } + + bool HasValidObjectRef() const { return mObjectRef != nullptr; } + +private: + jobject mObjectRef = nullptr; +}; + class JniReferences { public: @@ -44,7 +100,7 @@ class JniReferences * * we need clsType in context to get ClassLoader * - * This must be called before GetEnvForCurrentThread() or GetClassRef(). + * This must be called before GetEnvForCurrentThread(). */ void SetJavaVm(JavaVM * jvm, const char * clsType); @@ -56,18 +112,6 @@ class JniReferences */ JNIEnv * GetEnvForCurrentThread(); - /** - * @brief - * Creates a global jclass reference to the given class type. - * - * This must be called after SetJavaVm(). - * - * @param[in] env The JNIEnv for finding a Java class and creating a new Java reference. - * @param[in] clsType The fully-qualified Java class name to find, e.g. java/lang/IllegalStateException. - * @param[out] outCls A Java reference to the class matching clsType. - */ - CHIP_ERROR GetClassRef(JNIEnv * env, const char * clsType, jclass & outCls); - /** * @brief * Creates a local jclass reference to the given class type. @@ -94,6 +138,7 @@ class JniReferences void ThrowError(JNIEnv * env, jclass exceptionCls, CHIP_ERROR errToThrow); + void ThrowError(JNIEnv * env, JniGlobalReference & exceptionCls, CHIP_ERROR errToThrow); /** * Creates a java.util.Optional wrapping the specified jobject. If the wrapped jobject is null, an empty * Optional will be returned. @@ -156,17 +201,14 @@ class JniReferences template ::value, int> = 0> CHIP_ERROR CreateBoxedObject(std::string boxedTypeClsName, std::string constructorSignature, T value, jobject & outObj) { - JNIEnv * env = GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - jclass boxedTypeCls; - err = GetClassRef(env, boxedTypeClsName.c_str(), boxedTypeCls); - VerifyOrReturnError(err == CHIP_NO_ERROR, err); + JNIEnv * env = GetEnvForCurrentThread(); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE); + jclass boxedTypeCls = nullptr; + ReturnErrorOnFailure(GetLocalClassRef(env, boxedTypeClsName.c_str(), boxedTypeCls)); jmethodID boxedTypeConstructor = env->GetMethodID(boxedTypeCls, "", constructorSignature.c_str()); outObj = env->NewObject(boxedTypeCls, boxedTypeConstructor, value); - env->DeleteGlobalRef(boxedTypeCls); - - return err; + return CHIP_NO_ERROR; } /** @@ -190,12 +232,13 @@ class JniReferences private: JniReferences() {} - JavaVM * mJvm = nullptr; - jobject mClassLoader = nullptr; + JavaVM * mJvm = nullptr; + JniGlobalReference mClassLoader; jmethodID mFindClassMethod = nullptr; - jclass mHashMapClass = nullptr; - jclass mListClass = nullptr; - jclass mArrayListClass = nullptr; + JniGlobalReference mHashMapClass; + JniGlobalReference mListClass; + JniGlobalReference mArrayListClass; }; + } // namespace chip diff --git a/src/lib/support/JniTypeWrappers.h b/src/lib/support/JniTypeWrappers.h index f2f040e93d8e9e..0e64666b3e328e 100644 --- a/src/lib/support/JniTypeWrappers.h +++ b/src/lib/support/JniTypeWrappers.h @@ -24,7 +24,6 @@ #include #include -#define JNI_LOCAL_REF_COUNT 256 namespace chip { /// Exposes the underlying UTF string from a jni string class JniUtfString @@ -182,74 +181,4 @@ class JniGlobalRefWrapper private: jobject mGlobalRef = nullptr; }; - -class JniLocalReferenceScope -{ -public: - explicit JniLocalReferenceScope(JNIEnv * env) : mEnv(env) - { - if (mEnv->PushLocalFrame(JNI_LOCAL_REF_COUNT) == 0) - { - mlocalFramePushed = true; - } - } - - ~JniLocalReferenceScope() - { - if (mlocalFramePushed) - { - mEnv->PopLocalFrame(nullptr); - mlocalFramePushed = false; - } - } - - // Delete copy constructor and copy assignment operator - JniLocalReferenceScope(const JniLocalReferenceScope &) = delete; - JniLocalReferenceScope & operator=(const JniLocalReferenceScope &) = delete; - -private: - JNIEnv * const mEnv; - bool mlocalFramePushed = false; -}; - -class JniGlobalReference -{ -public: - JniGlobalReference() {} - - CHIP_ERROR Init(jobject aObjectRef) - { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - VerifyOrReturnError(aObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - VerifyOrReturnError(mObjectRef == nullptr, CHIP_ERROR_INCORRECT_STATE); - mObjectRef = env->NewGlobalRef(aObjectRef); - VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); - VerifyOrReturnError(mObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - return CHIP_NO_ERROR; - } - - JniGlobalReference(JniGlobalReference && aOther) - { - mObjectRef = aOther.mObjectRef; - aOther.mObjectRef = nullptr; - } - - ~JniGlobalReference() - { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env != nullptr && mObjectRef != nullptr) - { - env->DeleteGlobalRef(mObjectRef); - } - } - - jobject ObjectRef() { return mObjectRef; } - - bool HasValidObjectRef() { return mObjectRef != nullptr; } - -private: - jobject mObjectRef = nullptr; -}; - } // namespace chip diff --git a/src/platform/android/AndroidChipPlatform-JNI.cpp b/src/platform/android/AndroidChipPlatform-JNI.cpp index 05a781ca231de0..a5863a0c739e32 100644 --- a/src/platform/android/AndroidChipPlatform-JNI.cpp +++ b/src/platform/android/AndroidChipPlatform-JNI.cpp @@ -53,9 +53,8 @@ static bool JavaBytesToUUID(JNIEnv * env, jbyteArray value, chip::Ble::ChipBleUU #endif namespace { -JavaVM * sJVM; -jclass sAndroidChipPlatformCls = NULL; -jclass sAndroidChipPlatformExceptionCls = NULL; +JavaVM * sJVM = nullptr; +JniGlobalReference sAndroidChipPlatformExceptionCls; } // namespace CHIP_ERROR AndroidChipPlatformJNI_OnLoad(JavaVM * jvm, void * reserved) @@ -78,11 +77,14 @@ CHIP_ERROR AndroidChipPlatformJNI_OnLoad(JavaVM * jvm, void * reserved) ChipLogProgress(DeviceLayer, "Loading Java class references."); // Get various class references need by the API. - err = JniReferences::GetInstance().GetClassRef(env, "chip/platform/AndroidChipPlatform", sAndroidChipPlatformCls); + + jclass androidChipPlatformException; + err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/platform/AndroidChipPlatformException", + androidChipPlatformException); SuccessOrExit(err); - err = JniReferences::GetInstance().GetClassRef(env, "chip/platform/AndroidChipPlatformException", - sAndroidChipPlatformExceptionCls); + err = sAndroidChipPlatformExceptionCls.Init(static_cast(androidChipPlatformException)); SuccessOrExit(err); + ChipLogProgress(DeviceLayer, "Java class references loaded."); err = BleConnectCallbackJNI_OnLoad(jvm, reserved); diff --git a/src/platform/android/AndroidConfig.cpp b/src/platform/android/AndroidConfig.cpp index ec9221f08ba12e..afca2b43f3e96b 100644 --- a/src/platform/android/AndroidConfig.cpp +++ b/src/platform/android/AndroidConfig.cpp @@ -41,7 +41,7 @@ namespace chip { namespace DeviceLayer { namespace Internal { -static jobject gAndroidConfigObject = nullptr; +static JniGlobalReference gAndroidConfigObject; static jmethodID gReadConfigValueLongMethod = nullptr; static jmethodID gReadConfigValueStrMethod = nullptr; static jmethodID gReadConfigValueBinMethod = nullptr; @@ -94,9 +94,10 @@ const AndroidConfig::Key AndroidConfig::kConfigKey_CountryCode = { kConfi void AndroidConfig::InitializeWithObject(jobject managerObject) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - gAndroidConfigObject = env->NewGlobalRef(managerObject); - jclass androidConfigClass = env->GetObjectClass(gAndroidConfigObject); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(gAndroidConfigObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(DeviceLayer, "Failed to init gAndroidConfigObject")); + jclass androidConfigClass = env->GetObjectClass(managerObject); VerifyOrReturn(androidConfigClass != nullptr, ChipLogError(DeviceLayer, "Failed to get KVS Java class")); gReadConfigValueLongMethod = @@ -195,7 +196,7 @@ CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint32_t & val) CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint64_t & val) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gReadConfigValueLongMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -204,7 +205,8 @@ CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint64_t & val) UtfString space(env, key.Namespace); UtfString name(env, key.Name); - jlong javaValue = env->CallLongMethod(gAndroidConfigObject, gReadConfigValueLongMethod, space.jniValue(), name.jniValue()); + jlong javaValue = + env->CallLongMethod(gAndroidConfigObject.ObjectRef(), gReadConfigValueLongMethod, space.jniValue(), name.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::readConfigValueLong"); @@ -221,7 +223,7 @@ CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint64_t & val) CHIP_ERROR AndroidConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gReadConfigValueStrMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -230,7 +232,8 @@ CHIP_ERROR AndroidConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize UtfString space(env, key.Namespace); UtfString name(env, key.Name); - jobject javaValue = env->CallObjectMethod(gAndroidConfigObject, gReadConfigValueStrMethod, space.jniValue(), name.jniValue()); + jobject javaValue = + env->CallObjectMethod(gAndroidConfigObject.ObjectRef(), gReadConfigValueStrMethod, space.jniValue(), name.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::ReadConfigValueStr"); @@ -250,7 +253,7 @@ CHIP_ERROR AndroidConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize CHIP_ERROR AndroidConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gReadConfigValueBinMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -260,7 +263,7 @@ CHIP_ERROR AndroidConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufS UtfString name(env, key.Name); jbyteArray javaValue = static_cast( - env->CallObjectMethod(gAndroidConfigObject, gReadConfigValueBinMethod, space.jniValue(), name.jniValue())); + env->CallObjectMethod(gAndroidConfigObject.ObjectRef(), gReadConfigValueBinMethod, space.jniValue(), name.jniValue())); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::ReadConfigValueBin"); @@ -297,7 +300,7 @@ CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint32_t val) CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint64_t val) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gWriteConfigValueLongMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -307,7 +310,7 @@ CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint64_t val) UtfString name(env, key.Name); jlong jval = static_cast(val); - env->CallVoidMethod(gAndroidConfigObject, gWriteConfigValueLongMethod, space.jniValue(), name.jniValue(), jval); + env->CallVoidMethod(gAndroidConfigObject.ObjectRef(), gWriteConfigValueLongMethod, space.jniValue(), name.jniValue(), jval); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::readConfigValueLong"); @@ -322,7 +325,7 @@ CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint64_t val) CHIP_ERROR AndroidConfig::WriteConfigValueStr(Key key, const char * str) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gWriteConfigValueStrMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -332,7 +335,8 @@ CHIP_ERROR AndroidConfig::WriteConfigValueStr(Key key, const char * str) UtfString name(env, key.Name); UtfString val(env, str); - env->CallVoidMethod(gAndroidConfigObject, gWriteConfigValueStrMethod, space.jniValue(), name.jniValue(), val.jniValue()); + env->CallVoidMethod(gAndroidConfigObject.ObjectRef(), gWriteConfigValueStrMethod, space.jniValue(), name.jniValue(), + val.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::gWriteConfigValueStrMethod"); @@ -372,7 +376,7 @@ CHIP_ERROR AndroidConfig::WriteConfigValueStr(Key key, const char * str, size_t CHIP_ERROR AndroidConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gWriteConfigValueBinMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(chip::CanCastTo(dataLen), CHIP_ERROR_INVALID_ARGUMENT); @@ -383,7 +387,8 @@ CHIP_ERROR AndroidConfig::WriteConfigValueBin(Key key, const uint8_t * data, siz UtfString name(env, key.Name); ByteArray jval(env, reinterpret_cast(data), static_cast(dataLen)); - env->CallVoidMethod(gAndroidConfigObject, gWriteConfigValueBinMethod, space.jniValue(), name.jniValue(), jval.jniValue()); + env->CallVoidMethod(gAndroidConfigObject.ObjectRef(), gWriteConfigValueBinMethod, space.jniValue(), name.jniValue(), + jval.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::gWriteConfigValueBinMethod"); @@ -398,7 +403,7 @@ CHIP_ERROR AndroidConfig::WriteConfigValueBin(Key key, const uint8_t * data, siz CHIP_ERROR AndroidConfig::ClearConfigValue(Key key) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(gClearConfigValueMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -407,7 +412,7 @@ CHIP_ERROR AndroidConfig::ClearConfigValue(Key key) UtfString space(env, key.Namespace); UtfString name(env, key.Name); - env->CallVoidMethod(gAndroidConfigObject, gClearConfigValueMethod, space.jniValue(), name.jniValue()); + env->CallVoidMethod(gAndroidConfigObject.ObjectRef(), gClearConfigValueMethod, space.jniValue(), name.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::gClearConfigValueMethod"); @@ -422,7 +427,7 @@ CHIP_ERROR AndroidConfig::ClearConfigValue(Key key) bool AndroidConfig::ConfigValueExists(Key key) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(gAndroidConfigObject == nullptr, false); + ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), false); ReturnErrorCodeIf(gConfigValueExistsMethod == nullptr, false); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -431,7 +436,8 @@ bool AndroidConfig::ConfigValueExists(Key key) UtfString space(env, key.Namespace); UtfString name(env, key.Name); - jboolean jvalue = env->CallBooleanMethod(gAndroidConfigObject, gConfigValueExistsMethod, space.jniValue(), name.jniValue()); + jboolean jvalue = + env->CallBooleanMethod(gAndroidConfigObject.ObjectRef(), gConfigValueExistsMethod, space.jniValue(), name.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in AndroidConfig::gConfigValueExistsMethod"); diff --git a/src/platform/android/BLEManagerImpl.cpp b/src/platform/android/BLEManagerImpl.cpp index 712e0556f98ee7..05dfb5f560fbb5 100644 --- a/src/platform/android/BLEManagerImpl.cpp +++ b/src/platform/android/BLEManagerImpl.cpp @@ -54,8 +54,7 @@ void BLEManagerImpl::InitializeWithObject(jobject manager) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(DeviceLayer, "Failed to GetEnvForCurrentThread for BLEManager")); - mBLEManagerObject = env->NewGlobalRef(manager); - VerifyOrReturn(mBLEManagerObject != nullptr, ChipLogError(DeviceLayer, "Failed to NewGlobalRef BLEManager")); + VerifyOrReturn(mBLEManagerObject.Init(manager) == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "Failed to Init BLEManager")); jclass BLEManagerClass = env->GetObjectClass(manager); VerifyOrReturn(BLEManagerClass != nullptr, ChipLogError(DeviceLayer, "Failed to get BLEManager Java class")); @@ -141,13 +140,13 @@ CHIP_ERROR BLEManagerImpl::_Init() err = BleLayer::Init(this, this, this, &DeviceLayer::SystemLayer()); ReturnLogErrorOnFailure(err); - VerifyOrReturnLogError(mBLEManagerObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mBLEManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(mInitMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - jint ret = env->CallIntMethod(mBLEManagerObject, mInitMethod); + jint ret = env->CallIntMethod(mBLEManagerObject.ObjectRef(), mInitMethod); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in BLEManager::init"); @@ -231,7 +230,7 @@ bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipLogProgress(DeviceLayer, "Received SubscribeCharacteristic"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnSubscribeCharacteristicMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); @@ -243,8 +242,8 @@ bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const env->ExceptionClear(); tmpConnObj = reinterpret_cast(conId); - rc = (bool) env->CallBooleanMethod(mBLEManagerObject, mOnSubscribeCharacteristicMethod, static_cast(tmpConnObj), svcIdObj, - charIdObj); + rc = (bool) env->CallBooleanMethod(mBLEManagerObject.ObjectRef(), mOnSubscribeCharacteristicMethod, + static_cast(tmpConnObj), svcIdObj, charIdObj); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -270,7 +269,7 @@ bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, cons ChipLogProgress(DeviceLayer, "Received UnsubscribeCharacteristic"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnUnsubscribeCharacteristicMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); @@ -282,8 +281,8 @@ bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, cons env->ExceptionClear(); tmpConnObj = reinterpret_cast(conId); - rc = (bool) env->CallBooleanMethod(mBLEManagerObject, mOnUnsubscribeCharacteristicMethod, static_cast(tmpConnObj), - svcIdObj, charIdObj); + rc = (bool) env->CallBooleanMethod(mBLEManagerObject.ObjectRef(), mOnUnsubscribeCharacteristicMethod, + static_cast(tmpConnObj), svcIdObj, charIdObj); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -307,13 +306,13 @@ bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) ChipLogProgress(DeviceLayer, "Received CloseConnection"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnCloseConnectionMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); env->ExceptionClear(); tmpConnObj = reinterpret_cast(conId); - rc = (bool) env->CallBooleanMethod(mBLEManagerObject, mOnCloseConnectionMethod, static_cast(tmpConnObj)); + rc = (bool) env->CallBooleanMethod(mBLEManagerObject.ObjectRef(), mOnCloseConnectionMethod, static_cast(tmpConnObj)); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -335,14 +334,14 @@ uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const uint16_t mtu = 0; ChipLogProgress(DeviceLayer, "Received GetMTU"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnGetMTUMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); ; env->ExceptionClear(); tmpConnObj = reinterpret_cast(conId); - mtu = (int16_t) env->CallIntMethod(mBLEManagerObject, mOnGetMTUMethod, static_cast(tmpConnObj)); + mtu = (int16_t) env->CallIntMethod(mBLEManagerObject.ObjectRef(), mOnGetMTUMethod, static_cast(tmpConnObj)); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -375,7 +374,7 @@ bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::Ch bool rc = false; ChipLogProgress(DeviceLayer, "Received SendWriteRequest"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnSendWriteRequestMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); @@ -390,8 +389,8 @@ bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::Ch env->ExceptionClear(); tmpConnObj = reinterpret_cast(conId); - rc = (bool) env->CallBooleanMethod(mBLEManagerObject, mOnSendWriteRequestMethod, static_cast(tmpConnObj), svcIdObj, - charIdObj, characteristicDataObj); + rc = (bool) env->CallBooleanMethod(mBLEManagerObject.ObjectRef(), mOnSendWriteRequestMethod, static_cast(tmpConnObj), + svcIdObj, charIdObj, characteristicDataObj); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -431,13 +430,13 @@ void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) intptr_t tmpConnObj; ChipLogProgress(DeviceLayer, "Received NotifyChipConnectionClosed"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnNotifyChipConnectionClosedMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); env->ExceptionClear(); tmpConnObj = reinterpret_cast(conId); - env->CallVoidMethod(mBLEManagerObject, mOnNotifyChipConnectionClosedMethod, static_cast(tmpConnObj)); + env->CallVoidMethod(mBLEManagerObject.ObjectRef(), mOnNotifyChipConnectionClosedMethod, static_cast(tmpConnObj)); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: @@ -469,7 +468,7 @@ void BLEManagerImpl::NewConnection(BleLayer * bleLayer, void * appState, const S JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); ChipLogProgress(Controller, "Received New Connection"); - VerifyOrExit(mBLEManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mBLEManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mOnNewConnectionMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(env != NULL, err = CHIP_JNI_ERROR_NO_ENV); @@ -488,7 +487,7 @@ void BLEManagerImpl::NewConnection(BleLayer * bleLayer, void * appState, const S discriminator = connDiscriminator.GetLongValue(); } - env->CallVoidMethod(mBLEManagerObject, mOnNewConnectionMethod, static_cast(discriminator), + env->CallVoidMethod(mBLEManagerObject.ObjectRef(), mOnNewConnectionMethod, static_cast(discriminator), static_cast(connDiscriminator.IsShortDiscriminator()), reinterpret_cast(this), reinterpret_cast(appState)); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); @@ -515,13 +514,13 @@ CHIP_ERROR BLEManagerImpl::HasFlag(BLEManagerImpl::Flags flag, bool & has) chip::DeviceLayer::StackUnlock unlock; jlong f = static_cast(flag); - VerifyOrReturnLogError(mBLEManagerObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mBLEManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(mHasFlagMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - jboolean jret = env->CallBooleanMethod(mBLEManagerObject, mHasFlagMethod, f); + jboolean jret = env->CallBooleanMethod(mBLEManagerObject.ObjectRef(), mHasFlagMethod, f); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in BLEManager::hasFlag"); @@ -539,13 +538,13 @@ CHIP_ERROR BLEManagerImpl::SetFlag(BLEManagerImpl::Flags flag, bool isSet) jlong jFlag = static_cast(flag); jboolean jIsSet = static_cast(isSet); - VerifyOrReturnLogError(mBLEManagerObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mBLEManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(mSetFlagMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - env->CallLongMethod(mBLEManagerObject, mSetFlagMethod, jFlag, jIsSet); + env->CallLongMethod(mBLEManagerObject.ObjectRef(), mSetFlagMethod, jFlag, jIsSet); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in BLEManager::satFlag"); diff --git a/src/platform/android/BLEManagerImpl.h b/src/platform/android/BLEManagerImpl.h index 57fe6e9a0ca217..effa75db4ce3b4 100644 --- a/src/platform/android/BLEManagerImpl.h +++ b/src/platform/android/BLEManagerImpl.h @@ -23,9 +23,9 @@ #pragma once -#include - #include +#include +#include #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE @@ -124,7 +124,7 @@ class BLEManagerImpl final : public BLEManager, CHIP_ERROR HasFlag(Flags flag, bool & has); CHIP_ERROR SetFlag(Flags flag, bool isSet); - jobject mBLEManagerObject = nullptr; + chip::JniGlobalReference mBLEManagerObject; jmethodID mInitMethod = nullptr; jmethodID mSetFlagMethod = nullptr; diff --git a/src/platform/android/CHIPP256KeypairBridge.cpp b/src/platform/android/CHIPP256KeypairBridge.cpp index 74bd91961e39e2..a6be8799ab7b96 100644 --- a/src/platform/android/CHIPP256KeypairBridge.cpp +++ b/src/platform/android/CHIPP256KeypairBridge.cpp @@ -33,13 +33,7 @@ using namespace chip; using namespace chip::Crypto; -CHIPP256KeypairBridge::~CHIPP256KeypairBridge() -{ - VerifyOrReturn(mDelegate != nullptr); - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr); - env->DeleteGlobalRef(mDelegate); -} +CHIPP256KeypairBridge::~CHIPP256KeypairBridge() {} CHIP_ERROR CHIPP256KeypairBridge::SetDelegate(jobject delegate) { @@ -47,12 +41,11 @@ CHIP_ERROR CHIPP256KeypairBridge::SetDelegate(jobject delegate) JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrExit(env != nullptr, err = CHIP_JNI_ERROR_NO_ENV); - - mDelegate = env->NewGlobalRef(delegate); - - err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/KeypairDelegate", mKeypairDelegateClass); + ReturnErrorOnFailure(mDelegate.Init(delegate)); + jclass keypairDelegateClass; + err = JniReferences::GetInstance().GetLocalClassRef(env, "chip/devicecontroller/KeypairDelegate", keypairDelegateClass); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Failed to find class for KeypairDelegate.")); - + SuccessOrExit(err = mKeypairDelegateClass.Init(static_cast(keypairDelegateClass))); err = JniReferences::GetInstance().FindMethod(env, delegate, "createCertificateSigningRequest", "()[B", &mCreateCertificateSigningRequestMethod); VerifyOrExit(err == CHIP_NO_ERROR, @@ -126,8 +119,8 @@ CHIP_ERROR CHIPP256KeypairBridge::ECDSA_sign_msg(const uint8_t * msg, size_t msg err = JniReferences::GetInstance().N2J_ByteArray(env, msg, static_cast(msg_length), jniMsg); VerifyOrReturnError(err == CHIP_NO_ERROR, err); VerifyOrReturnError(jniMsg != nullptr, err); - - signedResult = env->CallObjectMethod(mDelegate, mEcdsaSignMessageMethod, jniMsg); + VerifyOrReturnError(mDelegate.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + signedResult = env->CallObjectMethod(mDelegate.ObjectRef(), mEcdsaSignMessageMethod, jniMsg); if (env->ExceptionCheck()) { @@ -166,8 +159,8 @@ CHIP_ERROR CHIPP256KeypairBridge::SetPubkey() env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); - - publicKey = env->CallObjectMethod(mDelegate, mGetPublicKeyMethod); + VerifyOrReturnError(mDelegate.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + publicKey = env->CallObjectMethod(mDelegate.ObjectRef(), mGetPublicKeyMethod); if (env->ExceptionCheck()) { ChipLogError(Controller, "Java exception in KeypairDelegate.getPublicKey()"); diff --git a/src/platform/android/CHIPP256KeypairBridge.h b/src/platform/android/CHIPP256KeypairBridge.h index bc8649ddbd1979..0e05d33c2250b2 100644 --- a/src/platform/android/CHIPP256KeypairBridge.h +++ b/src/platform/android/CHIPP256KeypairBridge.h @@ -16,11 +16,11 @@ */ #pragma once -#include - #include "crypto/CHIPCryptoPAL.h" #include "lib/core/CHIPError.h" +#include "lib/support/JniReferences.h" #include "lib/support/logging/CHIPLogging.h" +#include /** * Bridging implementation of P256Keypair to allow delegation of signing and @@ -42,7 +42,7 @@ class CHIPP256KeypairBridge : public chip::Crypto::P256Keypair */ CHIP_ERROR SetDelegate(jobject delegate); - bool HasKeypair() const { return mDelegate != nullptr; } + bool HasKeypair() const { return mDelegate.HasValidObjectRef(); } CHIP_ERROR Initialize(chip::Crypto::ECPKeyTarget key_target) override; @@ -61,8 +61,8 @@ class CHIPP256KeypairBridge : public chip::Crypto::P256Keypair const chip::Crypto::P256PublicKey & Pubkey() const override { return mPublicKey; }; private: - jobject mDelegate; - jclass mKeypairDelegateClass; + chip::JniGlobalReference mDelegate; + chip::JniGlobalReference mKeypairDelegateClass; jmethodID mGetPublicKeyMethod; jmethodID mCreateCertificateSigningRequestMethod; jmethodID mEcdsaSignMessageMethod; diff --git a/src/platform/android/ConfigurationManagerImpl.cpp b/src/platform/android/ConfigurationManagerImpl.cpp index 8eecf20180c546..defbb77f89b6f6 100644 --- a/src/platform/android/ConfigurationManagerImpl.cpp +++ b/src/platform/android/ConfigurationManagerImpl.cpp @@ -50,11 +50,8 @@ ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() void ConfigurationManagerImpl::InitializeWithObject(jobject managerObject) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - mConfigurationManagerObject = env->NewGlobalRef(managerObject); - jclass configurationManagerClass = env->GetObjectClass(mConfigurationManagerObject); - VerifyOrReturn(configurationManagerClass != nullptr, ChipLogError(DeviceLayer, "Failed to get KVS Java class")); - + VerifyOrReturn(mConfigurationManagerObject.Init(managerObject) == CHIP_NO_ERROR, + ChipLogError(DeviceLayer, "Failed to init mConfigurationManagerObject")); AndroidConfig::InitializeWithObject(managerObject); } diff --git a/src/platform/android/ConfigurationManagerImpl.h b/src/platform/android/ConfigurationManagerImpl.h index cb8a7a6efc142c..2884b412b1a810 100644 --- a/src/platform/android/ConfigurationManagerImpl.h +++ b/src/platform/android/ConfigurationManagerImpl.h @@ -28,6 +28,7 @@ #include #include +#include namespace chip { namespace DeviceLayer { @@ -74,7 +75,7 @@ class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImp static void DoFactoryReset(intptr_t arg); - jobject mConfigurationManagerObject = nullptr; + chip::JniGlobalReference mConfigurationManagerObject; }; /** diff --git a/src/platform/android/DiagnosticDataProviderImpl.cpp b/src/platform/android/DiagnosticDataProviderImpl.cpp index 9be5c59a2fbe16..ec6207523366ef 100644 --- a/src/platform/android/DiagnosticDataProviderImpl.cpp +++ b/src/platform/android/DiagnosticDataProviderImpl.cpp @@ -52,9 +52,8 @@ void DiagnosticDataProviderImpl::InitializeWithObject(jobject manager) VerifyOrReturn(env != nullptr, ChipLogError(DeviceLayer, "Failed to GetEnvForCurrentThread for DiagnosticDataProviderManagerImpl")); - mDiagnosticDataProviderManagerObject = env->NewGlobalRef(manager); - VerifyOrReturn(mDiagnosticDataProviderManagerObject != nullptr, - ChipLogError(DeviceLayer, "Failed to NewGlobalRef DiagnosticDataProviderManager")); + VerifyOrReturn(mDiagnosticDataProviderManagerObject.Init(manager) == CHIP_NO_ERROR, + ChipLogError(DeviceLayer, "Failed to Init DiagnosticDataProviderManager")); jclass DiagnosticDataProviderManagerClass = env->GetObjectClass(manager); VerifyOrReturn(DiagnosticDataProviderManagerClass != nullptr, @@ -80,12 +79,12 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) { chip::DeviceLayer::StackUnlock unlock; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturnLogError(mDiagnosticDataProviderManagerObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnLogError(mDiagnosticDataProviderManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(mGetRebootCountMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnLogError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); ChipLogProgress(DeviceLayer, "Received GetRebootCount"); - jint count = env->CallIntMethod(mDiagnosticDataProviderManagerObject, mGetRebootCountMethod); + jint count = env->CallIntMethod(mDiagnosticDataProviderManagerObject.ObjectRef(), mGetRebootCountMethod); VerifyOrReturnLogError(count < UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); rebootCount = static_cast(count); @@ -100,11 +99,12 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT, ChipLogError(DeviceLayer, "Could not get JNIEnv for current thread")); JniLocalReferenceScope scope(env); - VerifyOrExit(mDiagnosticDataProviderManagerObject != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(mDiagnosticDataProviderManagerObject.HasValidObjectRef(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mGetNifMethod != nullptr, err = CHIP_ERROR_INCORRECT_STATE); { ChipLogProgress(DeviceLayer, "Received GetNetworkInterfaces"); - jobjectArray nifList = (jobjectArray) env->CallObjectMethod(mDiagnosticDataProviderManagerObject, mGetNifMethod); + jobjectArray nifList = + (jobjectArray) env->CallObjectMethod(mDiagnosticDataProviderManagerObject.ObjectRef(), mGetNifMethod); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in DiagnosticDataProviderImpl::GetNetworkInterfaces"); diff --git a/src/platform/android/DiagnosticDataProviderImpl.h b/src/platform/android/DiagnosticDataProviderImpl.h index 7086b6c1a5a651..8f61876679e260 100644 --- a/src/platform/android/DiagnosticDataProviderImpl.h +++ b/src/platform/android/DiagnosticDataProviderImpl.h @@ -48,9 +48,9 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; - jobject mDiagnosticDataProviderManagerObject = nullptr; - jmethodID mGetRebootCountMethod = nullptr; - jmethodID mGetNifMethod = nullptr; + JniGlobalReference mDiagnosticDataProviderManagerObject; + jmethodID mGetRebootCountMethod = nullptr; + jmethodID mGetNifMethod = nullptr; }; /** diff --git a/src/platform/android/DnssdImpl.cpp b/src/platform/android/DnssdImpl.cpp index c468eb5e3b59d0..5f2e79b27b258f 100644 --- a/src/platform/android/DnssdImpl.cpp +++ b/src/platform/android/DnssdImpl.cpp @@ -39,9 +39,9 @@ namespace Dnssd { using namespace chip::Platform; namespace { -jobject sResolverObject = nullptr; -jobject sBrowserObject = nullptr; -jobject sMdnsCallbackObject = nullptr; +JniGlobalReference sResolverObject; +JniGlobalReference sBrowserObject; +JniGlobalReference sMdnsCallbackObject; jmethodID sResolveMethod = nullptr; jmethodID sBrowseMethod = nullptr; jmethodID sGetTextEntryKeysMethod = nullptr; @@ -70,12 +70,12 @@ void ChipDnssdShutdown() {} CHIP_ERROR ChipDnssdRemoveServices() { - VerifyOrReturnError(sResolverObject != nullptr && sRemoveServicesMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(sResolverObject.HasValidObjectRef() && sRemoveServicesMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); { DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(sResolverObject, sRemoveServicesMethod); + env->CallVoidMethod(sResolverObject.ObjectRef(), sRemoveServicesMethod); } if (env->ExceptionCheck()) @@ -92,7 +92,7 @@ CHIP_ERROR ChipDnssdRemoveServices() CHIP_ERROR ChipDnssdPublishService(const DnssdService * service, DnssdPublishCallback callback, void * context) { VerifyOrReturnError(service != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(sResolverObject != nullptr && sPublishMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(sResolverObject.HasValidObjectRef() && sPublishMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(CanCastTo(service->mTextEntrySize), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(CanCastTo(service->mSubTypeSize), CHIP_ERROR_INVALID_ARGUMENT); @@ -134,8 +134,8 @@ CHIP_ERROR ChipDnssdPublishService(const DnssdService * service, DnssdPublishCal { DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(sResolverObject, sPublishMethod, jniName.jniValue(), jniHostName.jniValue(), jniServiceType.jniValue(), - service->mPort, keys, datas, subTypes); + env->CallVoidMethod(sResolverObject.ObjectRef(), sPublishMethod, jniName.jniValue(), jniHostName.jniValue(), + jniServiceType.jniValue(), service->mPort, keys, datas, subTypes); } if (env->ExceptionCheck()) @@ -185,15 +185,15 @@ CHIP_ERROR ChipDnssdBrowse(const char * type, DnssdServiceProtocol protocol, Ine Inet::InterfaceId interface, DnssdBrowseCallback callback, void * context, intptr_t * browseIdentifier) { VerifyOrReturnError(type != nullptr && callback != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(sBrowserObject != nullptr && sBrowseMethod != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(sMdnsCallbackObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(sBrowserObject.HasValidObjectRef() && sBrowseMethod != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(sMdnsCallbackObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); std::string serviceType = GetFullTypeWithSubTypes(type, protocol); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); UtfString jniServiceType(env, serviceType.c_str()); - env->CallVoidMethod(sBrowserObject, sBrowseMethod, jniServiceType.jniValue(), reinterpret_cast(callback), - reinterpret_cast(context), sMdnsCallbackObject); + env->CallVoidMethod(sBrowserObject.ObjectRef(), sBrowseMethod, jniServiceType.jniValue(), reinterpret_cast(callback), + reinterpret_cast(context), sMdnsCallbackObject.ObjectRef()); if (env->ExceptionCheck()) { @@ -247,8 +247,8 @@ CHIP_ERROR extractProtocol(const char * serviceType, char (&outServiceName)[N], CHIP_ERROR ChipDnssdResolve(DnssdService * service, Inet::InterfaceId interface, DnssdResolveCallback callback, void * context) { VerifyOrReturnError(service != nullptr && callback != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(sResolverObject != nullptr && sResolveMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(sMdnsCallbackObject != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(sResolverObject.HasValidObjectRef() && sResolveMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(sMdnsCallbackObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); std::string serviceType = GetFullType(service); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -257,8 +257,8 @@ CHIP_ERROR ChipDnssdResolve(DnssdService * service, Inet::InterfaceId interface, { DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(sResolverObject, sResolveMethod, jniInstanceName.jniValue(), jniServiceType.jniValue(), - reinterpret_cast(callback), reinterpret_cast(context), sMdnsCallbackObject); + env->CallVoidMethod(sResolverObject.ObjectRef(), sResolveMethod, jniInstanceName.jniValue(), jniServiceType.jniValue(), + reinterpret_cast(callback), reinterpret_cast(context), sMdnsCallbackObject.ObjectRef()); } if (env->ExceptionCheck()) @@ -283,13 +283,16 @@ CHIP_ERROR ChipDnssdReconfirmRecord(const char * hostname, chip::Inet::IPAddress void InitializeWithObjects(jobject resolverObject, jobject browserObject, jobject mdnsCallbackObject) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - sResolverObject = env->NewGlobalRef(resolverObject); - sBrowserObject = env->NewGlobalRef(browserObject); - sMdnsCallbackObject = env->NewGlobalRef(mdnsCallbackObject); - jclass resolverClass = env->GetObjectClass(sResolverObject); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(sResolverObject.Init(resolverObject) == CHIP_NO_ERROR, + ChipLogError(Discovery, "Failed to init sResolverObject")); + VerifyOrReturn(sBrowserObject.Init(browserObject) == CHIP_NO_ERROR, ChipLogError(Discovery, "Failed to init sBrowserObject")); + VerifyOrReturn(sMdnsCallbackObject.Init(mdnsCallbackObject) == CHIP_NO_ERROR, + ChipLogError(Discovery, "Failed to init sMdnsCallbackObject")); + + jclass resolverClass = env->GetObjectClass(resolverObject); jclass browserClass = env->GetObjectClass(browserObject); - sMdnsCallbackClass = env->GetObjectClass(sMdnsCallbackObject); + sMdnsCallbackClass = env->GetObjectClass(mdnsCallbackObject); VerifyOrReturn(browserClass != nullptr, ChipLogError(Discovery, "Failed to get Browse Java class")); VerifyOrReturn(resolverClass != nullptr, ChipLogError(Discovery, "Failed to get Resolver Java class")); @@ -390,7 +393,8 @@ void HandleResolve(jstring instanceName, jstring serviceType, jstring hostName, // so we free these in the exit section if (textEntries != nullptr) { - jobjectArray keys = (jobjectArray) env->CallObjectMethod(sMdnsCallbackObject, sGetTextEntryKeysMethod, textEntries); + jobjectArray keys = + (jobjectArray) env->CallObjectMethod(sMdnsCallbackObject.ObjectRef(), sGetTextEntryKeysMethod, textEntries); auto size = env->GetArrayLength(keys); TextEntry * entries = new (std::nothrow) TextEntry[size]; VerifyOrExit(entries != nullptr, ChipLogError(Discovery, "entries alloc failure")); @@ -403,8 +407,8 @@ void HandleResolve(jstring instanceName, jstring serviceType, jstring hostName, JniUtfString key(env, jniKeyObject); entries[i].mKey = strdup(key.c_str()); - jbyteArray datas = - (jbyteArray) env->CallObjectMethod(sMdnsCallbackObject, sGetTextEntryDataMethod, textEntries, jniKeyObject); + jbyteArray datas = (jbyteArray) env->CallObjectMethod(sMdnsCallbackObject.ObjectRef(), sGetTextEntryDataMethod, + textEntries, jniKeyObject); if (datas != nullptr) { size_t dataSize = env->GetArrayLength(datas); diff --git a/src/platform/android/KeyValueStoreManagerImpl.cpp b/src/platform/android/KeyValueStoreManagerImpl.cpp index 3b15d888810e56..658532f6524137 100644 --- a/src/platform/android/KeyValueStoreManagerImpl.cpp +++ b/src/platform/android/KeyValueStoreManagerImpl.cpp @@ -47,10 +47,8 @@ void KeyValueStoreManagerImpl::InitializeWithObject(jobject manager) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(DeviceLayer, "Failed to GetEnvForCurrentThread for KeyValueStoreManagerImpl")); - - mKeyValueStoreManagerObject = env->NewGlobalRef(manager); - VerifyOrReturn(mKeyValueStoreManagerObject != nullptr, - ChipLogError(DeviceLayer, "Failed to NewGlobalRef KeyValueStoreManager")); + VerifyOrReturn(mKeyValueStoreManagerObject.Init(manager) == CHIP_NO_ERROR, + ChipLogError(DeviceLayer, "Failed to Init KeyValueStoreManager")); jclass KeyValueStoreManagerClass = env->GetObjectClass(manager); VerifyOrReturn(KeyValueStoreManagerClass != nullptr, @@ -82,7 +80,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t size_t offset_bytes) { CHIP_ERROR err = CHIP_NO_ERROR; - ReturnErrorCodeIf(mKeyValueStoreManagerObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(mGetMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -90,7 +88,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t chip::UtfString javaKey(env, key); - jobject javaValue = env->CallObjectMethod(mKeyValueStoreManagerObject, mGetMethod, javaKey.jniValue()); + jobject javaValue = env->CallObjectMethod(mKeyValueStoreManagerObject.ObjectRef(), mGetMethod, javaKey.jniValue()); if (env->ExceptionCheck()) { ChipLogError(DeviceLayer, "Java exception in KeyValueStoreManager::Get"); @@ -142,7 +140,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) { - ReturnErrorCodeIf(mKeyValueStoreManagerObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(mSetMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(value_size > kMaxKvsValueBytes, CHIP_ERROR_INVALID_ARGUMENT); @@ -157,7 +155,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, UtfString utfKey(env, key); UtfString utfBase64Value(env, buffer.get()); - env->CallVoidMethod(mKeyValueStoreManagerObject, mSetMethod, utfKey.jniValue(), utfBase64Value.jniValue()); + env->CallVoidMethod(mKeyValueStoreManagerObject.ObjectRef(), mSetMethod, utfKey.jniValue(), utfBase64Value.jniValue()); if (env->ExceptionCheck()) { @@ -172,7 +170,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { - ReturnErrorCodeIf(mKeyValueStoreManagerObject == nullptr, CHIP_ERROR_INCORRECT_STATE); + ReturnErrorCodeIf(!mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); ReturnErrorCodeIf(mDeleteMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); @@ -180,7 +178,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) UtfString javaKey(env, key); - env->CallVoidMethod(mKeyValueStoreManagerObject, mDeleteMethod, javaKey.jniValue()); + env->CallVoidMethod(mKeyValueStoreManagerObject.ObjectRef(), mDeleteMethod, javaKey.jniValue()); if (env->ExceptionCheck()) { diff --git a/src/platform/android/KeyValueStoreManagerImpl.h b/src/platform/android/KeyValueStoreManagerImpl.h index 1355da9901b3ed..9b40756a01f6db 100644 --- a/src/platform/android/KeyValueStoreManagerImpl.h +++ b/src/platform/android/KeyValueStoreManagerImpl.h @@ -24,6 +24,7 @@ #pragma once #include +#include namespace chip { namespace DeviceLayer { @@ -46,10 +47,10 @@ class KeyValueStoreManagerImpl : public KeyValueStoreManager static KeyValueStoreManagerImpl sInstance; - jobject mKeyValueStoreManagerObject = nullptr; - jmethodID mGetMethod = nullptr; - jmethodID mSetMethod = nullptr; - jmethodID mDeleteMethod = nullptr; + chip::JniGlobalReference mKeyValueStoreManagerObject; + jmethodID mGetMethod = nullptr; + jmethodID mSetMethod = nullptr; + jmethodID mDeleteMethod = nullptr; }; /** diff --git a/src/platform/stm32/CHIPDevicePlatformConfig.h b/src/platform/stm32/CHIPDevicePlatformConfig.h index 4f43c3538cd043..aee9ec36a2b73a 100644 --- a/src/platform/stm32/CHIPDevicePlatformConfig.h +++ b/src/platform/stm32/CHIPDevicePlatformConfig.h @@ -106,9 +106,9 @@ // ========== Platform-specific Cluster Overrides ========= #define CHIP_CLUSTER_NETWORK_COMMISSIONING_MAX_NETWORKS 1 -// EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT is only defined if the +// MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT is only defined if the // cluster is actually enabled in the ZAP config. To allow operation in setups -#define EMBER_AF_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT 1 +#define MATTER_DM_OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT 1 /** * CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC From cbb4006ffa10b9f3b0e2e10d4ce39c46cdd2178b Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 12:42:08 -0800 Subject: [PATCH 18/75] MDNS class update progress --- .../mdns_discovery/mdns_discovery.py | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 14deecde901f85..dc66ea88772917 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -22,7 +22,7 @@ from enum import Enum from typing import Dict, List, Optional -from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf +from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf, DNSRecordType from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes @@ -193,13 +193,19 @@ async def get_operational_service(self, service_name: str = None, # Get service info service_info = AsyncServiceInfo(service_type, service_name) - is_discovered = await service_info.async_request(self._zc, 3000) + is_discovered = await service_info.async_request( + self._zc, + 3000, + record_type=DNSRecordType.A, + load_from_cache=False) # Adds service to discovered services if is_discovered: mdns_service_info = self._to_mdns_service_info_class(service_info) self._discovered_services = {} - self._discovered_services[service_type] = [mdns_service_info] + self._discovered_services[service_type] = [] + if mdns_service_info is not None: + self._discovered_services[service_type].append(mdns_service_info) if log_output: self._log_output() @@ -290,9 +296,9 @@ async def _discover(self, self._event.clear() if all_services: - self._service_types = list(await AsyncZeroconfServiceTypes.async_find()) + self._service_types = list(set(await AsyncZeroconfServiceTypes.async_find())) - print(f"Browsing for MDNS service(s) of type: {self._service_types}") + print(f"\n\tBrowsing for MDNS service(s) of type: {self._service_types}\n") aiobrowser = AsyncServiceBrowser(zeroconf=self._zc, type_=self._service_types, @@ -302,7 +308,9 @@ async def _discover(self, try: await asyncio.wait_for(self._event.wait(), timeout=discovery_timeout_sec) except asyncio.TimeoutError: - print(f"MDNS service discovery timed out after {discovery_timeout_sec} seconds.") + for service_type in self._service_types: + self._discovered_services[service_type] = [] + print(f"\n\tMDNS service discovery for {self._service_types} timed out after {discovery_timeout_sec} seconds.\n") finally: await aiobrowser.async_cancel() @@ -362,8 +370,9 @@ async def _query_service_info(self, zeroconf: Zeroconf, service_type: str, servi mdns_service_info = self._to_mdns_service_info_class(service_info) if service_type not in self._discovered_services: - self._discovered_services[service_type] = [mdns_service_info] - else: + self._discovered_services[service_type] = [] + + if mdns_service_info is not None: self._discovered_services[service_type].append(mdns_service_info) def _to_mdns_service_info_class(self, service_info: AsyncServiceInfo) -> MdnsServiceInfo: @@ -413,8 +422,10 @@ async def _get_service(self, service_type: MdnsServiceType, mdns_service_info = None self._service_types = [service_type.value] await self._discover(discovery_timeout_sec, log_output) + if service_type.value in self._discovered_services: - mdns_service_info = self._discovered_services[service_type.value][0] + if len(self._discovered_services[service_type.value]) > 0: + mdns_service_info = self._discovered_services[service_type.value][0] return mdns_service_info @@ -425,6 +436,6 @@ def _log_output(self) -> str: The method is intended to be used for debugging or informational purposes, providing a clear and comprehensive view of all services discovered during the mDNS service discovery process. """ - converted_services = {key: [asdict(item) for item in value] for key, value in self._discovered_services.items()} - json_str = json.dumps(converted_services, indent=4) + log_services = {key: [asdict(item) for item in value] for key, value in self._discovered_services.items()} + json_str = json.dumps(log_services, indent=4) print(json_str) From f5ebcf73ba530ae81bd40cc64e41f07ad638c28a Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 15:58:05 -0800 Subject: [PATCH 19/75] Adds MdnsAsyncServiceInfo class --- .../mdns_discovery/mdns_async_service_info.py | 304 ++++++++++++++++++ 1 file changed, 304 insertions(+) create mode 100644 src/python_testing/mdns_discovery/mdns_async_service_info.py diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py new file mode 100644 index 00000000000000..56ea991b46f177 --- /dev/null +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -0,0 +1,304 @@ +# +# Copyright (c) 2024 Project CHIP Authors +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +import asyncio +import enum +from ipaddress import IPv4Address, IPv6Address +from random import randint +from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union +from zeroconf import BadTypeInNameException, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis +from zeroconf.const import ( + _DNS_HOST_TTL, + _DNS_OTHER_TTL, + _LISTENER_TIME, + _MDNS_PORT, + _DUPLICATE_QUESTION_INTERVAL, + _FLAGS_QR_QUERY, + _CLASS_IN, + _TYPE_A, + _TYPE_AAAA, + _TYPE_SRV, + _TYPE_TXT + ) +from zeroconf._dns import ( + DNSQuestion, + DNSAddress, + DNSPointer, + DNSQuestionType, + DNSRecord, + DNSService, + DNSText +) +from zeroconf._protocol.outgoing import DNSOutgoing +from zeroconf._utils.name import service_type_name +from zeroconf._utils.net import _encode_address +from zeroconf._cache import DNSCache +from zeroconf._history import QuestionHistory + + +int_ = int +float_ = float +str_ = str + + +QU_QUESTION = DNSQuestionType.QU +QM_QUESTION = DNSQuestionType.QM +_AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) + +@enum.unique +class DNSRecordType(enum.Enum): + """An MDNS record type. + + "A" - A MDNS record type + "AAAA" - AAAA MDNS record type + "SRV" - SRV MDNS record type + "TXT" - TXT MDNS record type + """ + + A = 0 + AAAA = 1 + SRV = 2 + TXT = 3 + + +class MdnsAsyncServiceInfo(ServiceInfo): + def __init__( + self, + type_: str, + name: str, + port: Optional[int] = None, + weight: int = 0, + priority: int = 0, + properties: Union[bytes, Dict] = b'', + server: Optional[str] = None, + host_ttl: int = _DNS_HOST_TTL, + other_ttl: int = _DNS_OTHER_TTL, + *, + addresses: Optional[List[bytes]] = None, + parsed_addresses: Optional[List[str]] = None, + interface_index: Optional[int] = None, + ) -> None: + # Accept both none, or one, but not both. + if addresses is not None and parsed_addresses is not None: + raise TypeError("addresses and parsed_addresses cannot be provided together") + if not type_.endswith(service_type_name(name, strict=False)): + raise BadTypeInNameException + self.interface_index = interface_index + self.text = b'' + self.type = type_ + self._name = name + self.key = name.lower() + self._ipv4_addresses: List[IPv4Address] = [] + self._ipv6_addresses: List[IPv6Address] = [] + if addresses is not None: + self.addresses = addresses + elif parsed_addresses is not None: + self.addresses = [_encode_address(a) for a in parsed_addresses] + self.port = port + self.weight = weight + self.priority = priority + self.server = server if server else None + self.server_key = server.lower() if server else None + self._properties: Optional[Dict[bytes, Optional[bytes]]] = None + self._decoded_properties: Optional[Dict[str, Optional[str]]] = None + if isinstance(properties, bytes): + self._set_text(properties) + else: + self._set_properties(properties) + self.host_ttl = host_ttl + self.other_ttl = other_ttl + self._new_records_futures: Optional[Set[asyncio.Future]] = None + self._dns_address_cache: Optional[List[DNSAddress]] = None + self._dns_pointer_cache: Optional[DNSPointer] = None + self._dns_service_cache: Optional[DNSService] = None + self._dns_text_cache: Optional[DNSText] = None + self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None + + async def async_request( + self, + zc: 'Zeroconf', + timeout: float, + question_type: Optional[DNSQuestionType] = None, + addr: Optional[str] = None, + port: int = _MDNS_PORT, + record_type: DNSRecordType = None, + load_from_cache: bool = True + ) -> bool: + """Returns true if the service could be discovered on the + network, and updates this object with details discovered. + + This method will be run in the event loop. + + Passing addr and port is optional, and will default to the + mDNS multicast address and port. This is useful for directing + requests to a specific host that may be able to respond across + subnets. + """ + if not zc.started: + await zc.async_wait_for_start() + + now = current_time_millis() + + if load_from_cache: + if self._load_from_cache(zc, now): + return True + + if TYPE_CHECKING: + assert zc.loop is not None + + first_request = True + delay = self._get_initial_delay() + next_ = now + last = now + timeout + try: + zc.async_add_listener(self, None) + while not self._is_complete: + if last <= now: + return False + if next_ <= now: + this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION + out = self._generate_request_query(zc, now, this_question_type, record_type) + first_request = False + if out.questions: + # All questions may have been suppressed + # by the question history, so nothing to send, + # but keep waiting for answers in case another + # client on the network is asking the same + # question or they have not arrived yet. + zc.async_send(out, addr, port) + next_ = now + delay + next_ += self._get_random_delay() + if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: + # If we just asked a QM question, we need to + # wait at least the duplicate question interval + # before asking another QM question otherwise + # its likely to be suppressed by the question + # history of the remote responder. + delay = _DUPLICATE_QUESTION_INTERVAL + + await self.async_wait(min(next_, last) - now, zc.loop) + now = current_time_millis() + finally: + zc.async_remove_listener(self) + + return True + + def _generate_request_query( + self, zc: 'Zeroconf', now: float_, question_type: DNSQuestionType, record_type: DNSRecordType + ) -> DNSOutgoing: + """Generate the request query.""" + out = DNSOutgoing(_FLAGS_QR_QUERY) + name = self._name + server = self.server or name + cache = zc.cache + history = zc.question_history + qu_question = question_type is QU_QUESTION + if record_type is None or record_type is DNSRecordType.SRV: + print("Requesting MDNS SRV record...") + self._add_question_with_known_answers( + out, qu_question, history, cache, now, name, _TYPE_SRV, _CLASS_IN, True + ) + if record_type is None or record_type is DNSRecordType.TXT: + print("Requesting MDNS TXT record...") + self._add_question_with_known_answers( + out, qu_question, history, cache, now, name, _TYPE_TXT, _CLASS_IN, True + ) + if record_type is None or record_type is DNSRecordType.A: + print("Requesting MDNS A record...") + self._add_question_with_known_answers( + out, qu_question, history, cache, now, server, _TYPE_A, _CLASS_IN, False + ) + if record_type is None or record_type is DNSRecordType.AAAA: + print("Requesting MDNS AAAA record...") + self._add_question_with_known_answers( + out, qu_question, history, cache, now, server, _TYPE_AAAA, _CLASS_IN, False + ) + return out + + def _add_question_with_known_answers( + self, + out: DNSOutgoing, + qu_question: bool, + question_history: QuestionHistory, + cache: DNSCache, + now: float_, + name: str_, + type_: int_, + class_: int_, + skip_if_known_answers: bool, + ) -> None: + """Add a question with known answers if its not suppressed.""" + known_answers = { + answer for answer in cache.get_all_by_details(name, type_, class_) if not answer.is_stale(now) + } + if skip_if_known_answers and known_answers: + return + question = DNSQuestion(name, type_, class_) + if qu_question: + question.unicast = True + elif question_history.suppresses(question, now, known_answers): + return + else: + question_history.add_question_at_time(question, now, known_answers) + out.add_question(question) + for answer in known_answers: + out.add_answer_at_time(answer, now) + + def _get_initial_delay(self) -> float_: + return _LISTENER_TIME + + def _get_random_delay(self) -> int_: + return randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) + + def _set_properties(self, properties: Dict[Union[str, bytes], Optional[Union[str, bytes]]]) -> None: + """Sets properties and text of this info from a dictionary""" + list_: List[bytes] = [] + properties_contain_str = False + result = b'' + for key, value in properties.items(): + if isinstance(key, str): + key = key.encode('utf-8') + properties_contain_str = True + + record = key + if value is not None: + if not isinstance(value, bytes): + value = str(value).encode('utf-8') + properties_contain_str = True + record += b'=' + value + list_.append(record) + for item in list_: + result = b''.join((result, bytes((len(item),)), item)) + if not properties_contain_str: + # If there are no str keys or values, we can use the properties + # as-is, without decoding them, otherwise calling + # self.properties will lazy decode them, which is expensive. + if TYPE_CHECKING: + self._properties = cast("Dict[bytes, Optional[bytes]]", properties) + else: + self._properties = properties + self.text = result + + def _set_text(self, text: bytes) -> None: + """Sets properties and text given a text field""" + if text == self.text: + return + self.text = text + # Clear the properties cache + self._properties = None + self._decoded_properties = None From 5dc0419c02540b154cc7e58d9893b850a4cdb61b Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 15:58:36 -0800 Subject: [PATCH 20/75] Adds get_service_by_record_type to mdns class --- .../mdns_discovery/mdns_discovery.py | 116 ++++++++++-------- .../mdns_discovery/mdns_service_type_enum.py | 26 ---- 2 files changed, 66 insertions(+), 76 deletions(-) delete mode 100644 src/python_testing/mdns_discovery/mdns_service_type_enum.py diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index dc66ea88772917..133c4db7bd6bb6 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -20,11 +20,13 @@ import json from dataclasses import asdict, dataclass from enum import Enum +from time import sleep from typing import Dict, List, Optional -from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf, DNSRecordType +from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes +from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo @dataclass class MdnsServiceInfo: @@ -84,6 +86,7 @@ def __init__(self): self.updated_event = asyncio.Event() def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: + sleep(0.5) self.updated_event.set() def remove_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: @@ -151,10 +154,8 @@ async def get_commissionable_service(self, log_output: bool = False, """ return await self._get_service(MdnsServiceType.COMMISSIONABLE, log_output, discovery_timeout_sec) - async def get_operational_service(self, service_name: str = None, - service_type: str = None, - discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC, - log_output: bool = False + async def get_operational_service(self, log_output: bool = False, + discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC ) -> Optional[MdnsServiceInfo]: """ Asynchronously discovers an operational mDNS service within the network. @@ -162,55 +163,11 @@ async def get_operational_service(self, service_name: str = None, Args: log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. - service_name (str): The unique name of the mDNS service. Defaults to None. - service_type (str): The service type of the service. Defaults to None. Returns: Optional[MdnsServiceInfo]: An instance of MdnsServiceInfo or None if timeout reached. """ - # Validation to ensure both or none of the parameters are provided - if (service_name is None) != (service_type is None): - raise ValueError("Both service_name and service_type must be provided together or not at all.") - - mdns_service_info = None - - if service_name is None and service_type is None: - mdns_service_info = await self._get_service(MdnsServiceType.OPERATIONAL, log_output, discovery_timeout_sec) - else: - print(f"Looking for MDNS service type '{service_type}', service name '{service_name}'") - - # Adds service listener - service_listener = MdnsServiceListener() - self._zc.add_service_listener(MdnsServiceType.OPERATIONAL.value, service_listener) - - # Wait for the add/update service event or timeout - try: - await asyncio.wait_for(service_listener.updated_event.wait(), discovery_timeout_sec) - except asyncio.TimeoutError: - print(f"Service lookup for {service_name} timeout ({discovery_timeout_sec}) reached without an update.") - finally: - self._zc.remove_service_listener(service_listener) - - # Get service info - service_info = AsyncServiceInfo(service_type, service_name) - is_discovered = await service_info.async_request( - self._zc, - 3000, - record_type=DNSRecordType.A, - load_from_cache=False) - - # Adds service to discovered services - if is_discovered: - mdns_service_info = self._to_mdns_service_info_class(service_info) - self._discovered_services = {} - self._discovered_services[service_type] = [] - if mdns_service_info is not None: - self._discovered_services[service_type].append(mdns_service_info) - - if log_output: - self._log_output() - - return mdns_service_info + return await self._get_service(MdnsServiceType.OPERATIONAL, log_output, discovery_timeout_sec) async def get_border_router_service(self, log_output: bool = False, discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC @@ -268,6 +225,65 @@ async def get_service_types(self, log_output: bool = False) -> List[str]: return discovered_services + async def get_service_by_record_type(self, service_name: str, + service_type: str, + record_type: DNSRecordType, + load_from_cache: bool = True, + discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC, + log_output: bool = False + ) -> Optional[MdnsServiceInfo]: + """ + Asynchronously discovers an mDNS service within the network by service name, service type, + and record type. + + Args: + log_output (bool): Logs the discovered services to the console. Defaults to False. + discovery_timeout_sec (float): Defaults to 15 seconds. + service_name (str): The unique name of the mDNS service. Defaults to None. + service_type (str): The service type of the service. Defaults to None. + record_type (DNSRecordType): The type of record to look for (SRV, TXT, AAAA, A). + + Returns: + Optional[MdnsServiceInfo]: An instance of MdnsServiceInfo or None if timeout reached. + """ + mdns_service_info = None + + print( + f"Looking for MDNS service type '{service_type}', service name '{service_name}', record type '{record_type.name}'") + + # Adds service listener + service_listener = MdnsServiceListener() + self._zc.add_service_listener(MdnsServiceType.OPERATIONAL.value, service_listener) + + # Wait for the add/update service event or timeout + try: + await asyncio.wait_for(service_listener.updated_event.wait(), discovery_timeout_sec) + except asyncio.TimeoutError: + print(f"Service lookup for {service_name} timeout ({discovery_timeout_sec}) reached without an update.") + finally: + self._zc.remove_service_listener(service_listener) + + # Get service info + service_info = MdnsAsyncServiceInfo(service_type, service_name) + is_discovered = await service_info.async_request( + self._zc, + 3000, + record_type=record_type, + load_from_cache=load_from_cache) + + # Adds service to discovered services + if is_discovered: + mdns_service_info = self._to_mdns_service_info_class(service_info) + self._discovered_services = {} + self._discovered_services[service_type] = [] + if mdns_service_info is not None: + self._discovered_services[service_type].append(mdns_service_info) + + if log_output: + self._log_output() + + return mdns_service_info + # Private methods async def _discover(self, discovery_timeout_sec: float, diff --git a/src/python_testing/mdns_discovery/mdns_service_type_enum.py b/src/python_testing/mdns_discovery/mdns_service_type_enum.py deleted file mode 100644 index efd77ca3beef5c..00000000000000 --- a/src/python_testing/mdns_discovery/mdns_service_type_enum.py +++ /dev/null @@ -1,26 +0,0 @@ -# -# Copyright (c) 2024 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -from enum import Enum - - -class MdnsServiceType(Enum): - COMMISSIONER = "_matterd._udp.local." - COMMISSIONABLE = "_matterc._udp.local." - OPERATIONAL = "_matter._tcp.local." - BORDER_ROUTER = "_meshcop._udp.local." From 606a9201a49b5cfea4cc5e124fd594660faa9b53 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 16:00:16 -0800 Subject: [PATCH 21/75] TC progress --- src/python_testing/TC_SC_4_3.py | 133 +++++++++++++++++--------------- 1 file changed, 70 insertions(+), 63 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index abc1b570657c37..e7c833a1e119d7 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -20,7 +20,7 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main -from mdns_discovery.mdns_discovery import MdnsDiscovery, MdnsServiceType +from mdns_discovery.mdns_discovery import MdnsDiscovery, MdnsServiceType, DNSRecordType from mobly import asserts ''' @@ -172,72 +172,75 @@ async def test_TC_SC_4_3(self): # PENDING STEPS 6-8 mdns = MdnsDiscovery() - operational = await mdns.get_operational_service( + await mdns.get_service_by_record_type( service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", service_type=MdnsServiceType.OPERATIONAL.value, - log_output=True + record_type=DNSRecordType.SRV, + log_output=True, + load_from_cache=False ) + - # *** STEP 9 *** - self.print_step("9", "TH verifies ICD, SII, SAI, SAT, and T TXT record keys/vales of the returned record.") + # # *** STEP 9 *** + # self.print_step("9", "TH verifies ICD, SII, SAI, SAT, and T TXT record keys/vales of the returned record.") - # ICD TXT KEY - if supports_lit: - logging.info("supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") + # # ICD TXT KEY + # if supports_lit: + # logging.info("supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") - # Verify the ICD key IS present - asserts.assert_in('ICD', operational.txt_record, "ICD key is NOT present in the TXT record.") + # # Verify the ICD key IS present + # asserts.assert_in('ICD', operational.txt_record, "ICD key is NOT present in the TXT record.") - # Verify it has the value of 0 or 1 (ASCII) - icd_value = int(operational.txt_record['ICD']) - asserts.assert_true(icd_value == 0 or icd_value == 1, "ICD value is different than 0 or 1 (ASCII).") - else: - logging.info("supports_lit is false, verify that the ICD key is NOT present in the TXT record.") - asserts.assert_not_in('ICD', operational.txt_record, "ICD key is present in the TXT record.") + # # Verify it has the value of 0 or 1 (ASCII) + # icd_value = int(operational.txt_record['ICD']) + # asserts.assert_true(icd_value == 0 or icd_value == 1, "ICD value is different than 0 or 1 (ASCII).") + # else: + # logging.info("supports_lit is false, verify that the ICD key is NOT present in the TXT record.") + # asserts.assert_not_in('ICD', operational.txt_record, "ICD key is present in the TXT record.") - # SII TXT KEY - if supports_icd and not supports_lit: - sit_mode = True + # # SII TXT KEY + # if supports_icd and not supports_lit: + # sit_mode = True - if supports_icd and supports_lit: - if icd_value == 0: - sit_mode = True - else: - sit_mode = False + # if supports_icd and supports_lit: + # if icd_value == 0: + # sit_mode = True + # else: + # sit_mode = False - if not supports_icd: - sit_mode = False + # if not supports_icd: + # sit_mode = False - if sit_mode: - logging.info("sit_mode is True, verify the SII key IS present.") - asserts.assert_in('SII', operational.txt_record, "SII key is NOT present in the TXT record.") + # if sit_mode: + # logging.info("sit_mode is True, verify the SII key IS present.") + # asserts.assert_in('SII', operational.txt_record, "SII key is NOT present in the TXT record.") - logging.info("Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") - sii_value = operational.txt_record['SII'] - result, message = self.verify_decimal_value(sii_value, self.ONE_HOUR_IN_MS) - asserts.assert_true(result, message) + # logging.info("Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + # sii_value = operational.txt_record['SII'] + # result, message = self.verify_decimal_value(sii_value, self.ONE_HOUR_IN_MS) + # asserts.assert_true(result, message) - # SAI TXT KEY - if supports_icd: - logging.info("supports_icd is True, verify the SAI key IS present.") - asserts.assert_in('SAI', operational.txt_record, "SAI key is NOT present in the TXT record.") - - logging.info("Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") - sai_value = operational.txt_record['SAI'] - result, message = self.verify_decimal_value(sai_value, self.ONE_HOUR_IN_MS) - asserts.assert_true(result, message) - - # SAT TXT KEY - if 'SAT' in operational.txt_record: - logging.info( - "SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") - sat_value = operational.txt_record['SAT'] - result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) - asserts.assert_true(result, message) - - if supports_icd: - logging.info("supports_icd is True, verify the SAT value is equal to active_mode_threshold.") - asserts.assert_equal(int(sat_value), active_mode_threshold_ms) + # # SAI TXT KEY + # if supports_icd: + # logging.info("supports_icd is True, verify the SAI key IS present.") + # asserts.assert_in('SAI', operational.txt_record, "SAI key is NOT present in the TXT record.") + + # logging.info("Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + # sai_value = operational.txt_record['SAI'] + # result, message = self.verify_decimal_value(sai_value, self.ONE_HOUR_IN_MS) + # asserts.assert_true(result, message) + + # # SAT TXT KEY + # if 'SAT' in operational.txt_record: + # logging.info( + # "SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") + # sat_value = operational.txt_record['SAT'] + # result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) + # asserts.assert_true(result, message) + + # if supports_icd: + # logging.info("supports_icd is True, verify the SAT value is equal to active_mode_threshold.") + # asserts.assert_equal(int(sat_value), active_mode_threshold_ms) # # T TXT KEY # if 'T' in operational.txt_record: @@ -246,19 +249,23 @@ async def test_TC_SC_4_3(self): # result, message = self.verify_t_value(t_value) # asserts.assert_true(result, message) - # AAAA - logging.info("Verify the AAAA record contains at least one IPv6 address") - result, message = self.contains_ipv6_address(operational.addresses) - asserts.assert_true(result, message) + # # AAAA + # logging.info("Verify the AAAA record contains at least one IPv6 address") + # result, message = self.contains_ipv6_address(operational.addresses) + # asserts.assert_true(result, message) - # *** STEP 10 *** - self.print_step("10", "Verify DUT returns a PTR record with DNS-SD instance name set instance_name.") - service_types = await mdns.get_service_types(log_output=True) - op_sub_type = self.get_operational_subtype() - asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") + # # *** STEP 10 *** + # self.print_step("10", "Verify DUT returns a PTR record with DNS-SD instance name set instance_name.") + # service_types = await mdns.get_service_types(log_output=True) + # op_sub_type = self.get_operational_subtype() + # asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") print("\n"*10) + + # input() if __name__ == "__main__": default_matter_test_main() + + \ No newline at end of file From 9d9848f7b2116c358ad66711071959df3cf1c4df Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 16:12:03 -0800 Subject: [PATCH 22/75] Fix restyle --- src/python_testing/TC_SC_4_3.py | 7 ++--- .../mdns_discovery/mdns_async_service_info.py | 31 +++++-------------- .../mdns_discovery/mdns_discovery.py | 14 ++++----- 3 files changed, 16 insertions(+), 36 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index e7c833a1e119d7..df6ffb350a2ecd 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -20,7 +20,7 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main -from mdns_discovery.mdns_discovery import MdnsDiscovery, MdnsServiceType, DNSRecordType +from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType from mobly import asserts ''' @@ -179,7 +179,6 @@ async def test_TC_SC_4_3(self): log_output=True, load_from_cache=False ) - # # *** STEP 9 *** # self.print_step("9", "TH verifies ICD, SII, SAI, SAT, and T TXT record keys/vales of the returned record.") @@ -261,11 +260,9 @@ async def test_TC_SC_4_3(self): # asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") print("\n"*10) - + # input() if __name__ == "__main__": default_matter_test_main() - - \ No newline at end of file diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 56ea991b46f177..2ea1e813b43841 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -21,34 +21,16 @@ from ipaddress import IPv4Address, IPv6Address from random import randint from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union + from zeroconf import BadTypeInNameException, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis -from zeroconf.const import ( - _DNS_HOST_TTL, - _DNS_OTHER_TTL, - _LISTENER_TIME, - _MDNS_PORT, - _DUPLICATE_QUESTION_INTERVAL, - _FLAGS_QR_QUERY, - _CLASS_IN, - _TYPE_A, - _TYPE_AAAA, - _TYPE_SRV, - _TYPE_TXT - ) -from zeroconf._dns import ( - DNSQuestion, - DNSAddress, - DNSPointer, - DNSQuestionType, - DNSRecord, - DNSService, - DNSText -) +from zeroconf._cache import DNSCache +from zeroconf._dns import DNSQuestion, DNSAddress, DNSPointer, DNSQuestionType, DNSRecord, DNSService, DNSText +from zeroconf._history import QuestionHistory from zeroconf._protocol.outgoing import DNSOutgoing from zeroconf._utils.name import service_type_name from zeroconf._utils.net import _encode_address -from zeroconf._cache import DNSCache -from zeroconf._history import QuestionHistory +from zeroconf.const import (_DNS_HOST_TTL, _DNS_OTHER_TTL, _LISTENER_TIME, + _MDNS_PORT, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _CLASS_IN, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) int_ = int @@ -60,6 +42,7 @@ QM_QUESTION = DNSQuestionType.QM _AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) + @enum.unique class DNSRecordType(enum.Enum): """An MDNS record type. diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 133c4db7bd6bb6..ff5d4ded41ef60 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -23,10 +23,10 @@ from time import sleep from typing import Dict, List, Optional +from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes -from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo @dataclass class MdnsServiceInfo: @@ -226,12 +226,12 @@ async def get_service_types(self, log_output: bool = False) -> List[str]: return discovered_services async def get_service_by_record_type(self, service_name: str, - service_type: str, - record_type: DNSRecordType, - load_from_cache: bool = True, - discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC, - log_output: bool = False - ) -> Optional[MdnsServiceInfo]: + service_type: str, + record_type: DNSRecordType, + load_from_cache: bool = True, + discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC, + log_output: bool = False + ) -> Optional[MdnsServiceInfo]: """ Asynchronously discovers an mDNS service within the network by service name, service type, and record type. From d1c9e784d7c470737df258e0c23038c959cc3a99 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 16:14:43 -0800 Subject: [PATCH 23/75] Fix restyle --- .../mdns_discovery/mdns_async_service_info.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 2ea1e813b43841..40ea9c9a3e47ed 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -24,14 +24,13 @@ from zeroconf import BadTypeInNameException, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis from zeroconf._cache import DNSCache -from zeroconf._dns import DNSQuestion, DNSAddress, DNSPointer, DNSQuestionType, DNSRecord, DNSService, DNSText +from zeroconf._dns import DNSAddress, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, DNSService, DNSText from zeroconf._history import QuestionHistory from zeroconf._protocol.outgoing import DNSOutgoing from zeroconf._utils.name import service_type_name from zeroconf._utils.net import _encode_address -from zeroconf.const import (_DNS_HOST_TTL, _DNS_OTHER_TTL, _LISTENER_TIME, - _MDNS_PORT, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _CLASS_IN, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) - +from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, + _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) int_ = int float_ = float From db57750e5a179edd915fcdceee78dbe64aaba120 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 20:08:37 -0800 Subject: [PATCH 24/75] Fix lint --- src/python_testing/TC_SC_4_3.py | 6 +++--- .../mdns_discovery/mdns_async_service_info.py | 8 ++------ 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index df6ffb350a2ecd..fb0c553c6aacec 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -21,7 +21,7 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType -from mobly import asserts +# from mobly import asserts ''' Category @@ -136,8 +136,8 @@ async def test_TC_SC_4_3(self): supports_lit = None active_mode_threshold_ms = None instance_name = None - icd_value = None - sit_mode = None + # icd_value = None + # sit_mode = None # *** STEP 1 *** self.print_step("1", "DUT is commissioned on the same fabric as TH.") diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 40ea9c9a3e47ed..02d862d7eff7bb 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -20,14 +20,10 @@ import enum from ipaddress import IPv4Address, IPv6Address from random import randint -from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union +from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast -from zeroconf import BadTypeInNameException, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis -from zeroconf._cache import DNSCache -from zeroconf._dns import DNSAddress, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, DNSService, DNSText +from zeroconf import DNSOutgoing, BadTypeInNameException, DNSQuestionType, ServiceInfo, Zeroconf, DNSAddress, DNSPointer, DNSQuestion, DNSRecord, DNSService, DNSText, DNSCache, current_time_millis, service_type_name from zeroconf._history import QuestionHistory -from zeroconf._protocol.outgoing import DNSOutgoing -from zeroconf._utils.name import service_type_name from zeroconf._utils.net import _encode_address from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) From d2e5d8ca4fe60e3117a302cd1b85c53d2581bce1 Mon Sep 17 00:00:00 2001 From: raul-marquez-csa Date: Mon, 12 Feb 2024 20:11:03 -0800 Subject: [PATCH 25/75] Fix restyle --- src/python_testing/TC_SC_4_3.py | 1 + src/python_testing/mdns_discovery/mdns_async_service_info.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index fb0c553c6aacec..fd11f0d2eb0e37 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -21,6 +21,7 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType + # from mobly import asserts ''' diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 02d862d7eff7bb..16224a8c5f044b 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -22,7 +22,8 @@ from random import randint from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast -from zeroconf import DNSOutgoing, BadTypeInNameException, DNSQuestionType, ServiceInfo, Zeroconf, DNSAddress, DNSPointer, DNSQuestion, DNSRecord, DNSService, DNSText, DNSCache, current_time_millis, service_type_name +from zeroconf import (BadTypeInNameException, DNSAddress, DNSCache, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, + DNSRecord, DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) from zeroconf._history import QuestionHistory from zeroconf._utils.net import _encode_address from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, From dac6a4264bab7c6e88ea43a73684d7ab8ac2f031 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 9 Jul 2024 12:26:34 -0700 Subject: [PATCH 26/75] tests.yaml from master --- .github/workflows/tests.yaml | 200 +++++++++++++++++++---------------- 1 file changed, 109 insertions(+), 91 deletions(-) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 5079d891de181a..a8bdfdcdc2c1ec 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -16,6 +16,8 @@ name: Tests on: push: + branches-ignore: + - 'dependabot/**' pull_request: merge_group: workflow_dispatch: @@ -47,7 +49,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:35 + image: ghcr.io/project-chip/chip-build:54 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -89,6 +91,8 @@ jobs: --no-print \ --log-level info \ src/app/zap-templates/zcl/data-model/chip/global-attributes.xml \ + src/app/zap-templates/zcl/data-model/chip/global-structs.xml \ + src/app/zap-templates/zcl/data-model/chip/semantic-tag-namespace-enums.xml \ src/app/zap-templates/zcl/data-model/chip/access-control-definitions.xml \ src/app/zap-templates/zcl/data-model/chip/access-control-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/account-login-cluster.xml \ @@ -178,6 +182,7 @@ jobs: src/app/zap-templates/zcl/data-model/chip/test-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/thermostat-user-interface-configuration-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml \ + src/app/zap-templates/zcl/data-model/chip/thread-border-router-management-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml \ @@ -187,6 +192,7 @@ jobs: src/app/zap-templates/zcl/data-model/chip/wake-on-lan-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml \ + src/app/zap-templates/zcl/data-model/chip/wifi-network-management-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/window-covering.xml \ src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/matter-devices.xml \ @@ -247,7 +253,7 @@ jobs: --chip-tool ./out/linux-x64-chip-tool${CHIP_TOOL_VARIANT}-${BUILD_VARIANT}/chip-tool \ run \ --iterations 1 \ - --expected-failures 1 \ + --expected-failures 3 \ --keep-going \ --test-timeout-seconds 120 \ --all-clusters-app ./out/linux-x64-all-clusters-${BUILD_VARIANT}/chip-all-clusters-app \ @@ -328,7 +334,7 @@ jobs: LSAN_OPTIONS: detect_leaks=1 suppressions=scripts/tests/chiptest/lsan-mac-suppressions.txt if: github.actor != 'restyled-io[bot]' - runs-on: macos-latest + runs-on: macos-13 steps: - name: Checkout @@ -398,7 +404,7 @@ jobs: --chip-tool ./out/darwin-x64-chip-tool${CHIP_TOOL_VARIANT}-${BUILD_VARIANT}/chip-tool \ run \ --iterations 1 \ - --expected-failures 1 \ + --expected-failures 3 \ --keep-going \ --test-timeout-seconds 120 \ --all-clusters-app ./out/darwin-x64-all-clusters-${BUILD_VARIANT}/chip-all-clusters-app \ @@ -437,7 +443,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:32 + image: ghcr.io/project-chip/chip-build:54 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" @@ -471,97 +477,109 @@ jobs: build \ --copy-artifacts-to objdir-clone \ " + - name: Generate an argument environment file + run: | + echo -n "" >/tmp/test_env.yaml + echo "ALL_CLUSTERS_APP: out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app" >> /tmp/test_env.yaml + echo "CHIP_LOCK_APP: out/linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-lock-app" >> /tmp/test_env.yaml + echo "ENERGY_MANAGEMENT_APP: out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app" >> /tmp/test_env.yaml + echo "LIT_ICD_APP: out/linux-x64-lit-icd-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app" >> /tmp/test_env.yaml + echo "CHIP_MICROWAVE_OVEN_APP: out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app" >> /tmp/test_env.yaml + echo "CHIP_RVC_APP: out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app" >> /tmp/test_env.yaml + echo "TRACE_APP: out/trace_data/app-{SCRIPT_BASE_NAME}" >> /tmp/test_env.yaml + echo "TRACE_TEST_JSON: out/trace_data/test-{SCRIPT_BASE_NAME}" >> /tmp/test_env.yaml + echo "TRACE_TEST_PERFETTO: out/trace_data/test-{SCRIPT_BASE_NAME}" >> /tmp/test_env.yaml + - name: Run Tests run: | mkdir -p out/trace_data - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script-args "--log-level INFO -t 3600 --disable-test ClusterObjectTests.TestTimedRequestTimeout --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RR_1_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DeviceBasicComposition.py" --script-args "--storage-path admin_storage.json --manual-code 10054912339 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_3_6.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lit-icd-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_4_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DA_1_7.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_TestEventTrigger.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_ACE_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_ACE_1_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_ACE_1_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --int-arg PIXIT.ACE.APPENDPOINT:1 PIXIT.ACE.APPDEVTYPEID:0x0100 --string-arg PIXIT.ACE.APPCLUSTER:OnOff PIXIT.ACE.APPATTRIBUTE:OnOff --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_ACE_1_5.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_AccessChecker.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_CGEN_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DA_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DA_1_5.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DA_1_7.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DGGEN_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-lock-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DRLK_2_12.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-lock-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DRLK_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-lock-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DRLK_2_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DeviceBasicComposition.py" --script-args "--storage-path admin_storage.json --manual-code 10054912339 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-lock-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_DeviceConformance.py" --script-args "--storage-path admin_storage.json --manual-code 10054912339 --bool-arg ignore_in_progress:True allow_provisional:True --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto --tests test_TC_IDM_10_2"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEM_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEM_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEM_2_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEM_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEM_2_5.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEVSE_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEVSE_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EEVSE_2_5.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EPM_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_EPM_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --hex-arg enableKey:000102030405060708090a0b0c0d0e0f --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_FAN_3_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_FAN_3_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_FAN_3_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_FAN_3_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_FAN_3_5.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-lit-icd-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_ICDM_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_IDM_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_IDM_1_4.py" --script-args "--hex-arg PIXIT.DGGEN.TEST_EVENT_TRIGGER_KEY:000102030405060708090a0b0c0d0e0f --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_PWRTL_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RR_1_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_SC_3_6.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_10.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_11.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_12.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_13.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_5.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_6.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_7.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_8.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_2_9.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_TIMESYNC_3_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_TestEventTrigger.py" --script-args "--storage-path admin_storage.json --bool-arg allow_sdk_dac:true --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TestBatchInvoke.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --quiet --app-args "--trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script-args "--log-level INFO -t 3600 --disable-test ClusterObjectTests.TestTimedRequestTimeout --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ACE_1_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ACE_1_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ACE_1_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ACE_1_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_AccessChecker.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_CGEN_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DA_1_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DA_1_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DA_1_7.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DGGEN_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DRLK_2_12.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DRLK_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DRLK_2_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DeviceBasicComposition.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_DeviceConformance.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEM_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEM_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEM_2_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEM_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEM_2_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEVSE_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEVSE_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EEVSE_2_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EPM_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_EPM_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_FAN_3_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_FAN_3_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_FAN_3_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_FAN_3_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_FAN_3_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ICDM_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ICDM_3_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ICDManagementCluster.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_IDM_1_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_IDM_1_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_PWRTL_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RR_1_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_SC_3_6.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_10.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_11.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_12.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_13.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_6.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_7.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_8.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_9.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_3_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TestEventTrigger.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TestBatchInvoke.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TestGroupTableReports.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPCREDS_3_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPCREDS_3_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPSTATE_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPSTATE_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPSTATE_2_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPSTATE_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OPSTATE_2_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OVENOPSTATE_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OVENOPSTATE_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OVENOPSTATE_2_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OVENOPSTATE_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_OVENOPSTATE_2_5.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_MWOCTRL_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_MWOCTRL_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_MWOCTRL_2_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_MWOM_1_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCRUNM_1_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCRUNM_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCRUNM_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCCLEANM_1_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCCLEANM_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCCLEANM_2_2.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCOPSTATE_2_1.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCOPSTATE_2_3.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RVCOPSTATE_2_4.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --script "src/python_testing/TestConformanceSupport.py" --script-args "--trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TestGroupTableReports.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --script "src/python_testing/TestMatterTestingSupport.py" --script-args "--trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --script "src/python_testing/TestSpecParsingSupport.py" --script-args "--trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' scripts/run_in_python_env.sh out/venv './scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OPSTATE_1_1.py" --script-args "--endpoint 1 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OPSTATE_2_1.py" --script-args "--endpoint 1 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OPSTATE_2_2.py" --script-args "--endpoint 1 --int-arg PIXIT.WAITTIME.COUNTDOWN:5 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OPSTATE_2_3.py" --script-args "--endpoint 1 --int-arg PIXIT.WAITTIME.COUNTDOWN:5 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OPSTATE_2_4.py" --script-args "--endpoint 1 --int-arg PIXIT.OPSTATE.ErrorEventGen:1 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OPSTATE_2_5.py" --script-args "--endpoint 1 --int-arg PIXIT.WAITTIME.REBOOT:5 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OVENOPSTATE_1_1.py" --script-args "--endpoint 1 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OVENOPSTATE_2_1.py" --script-args "--endpoint 1 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OVENOPSTATE_2_2.py" --script-args "--endpoint 1 --int-arg PIXIT.WAITTIME.COUNTDOWN:5 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OVENOPSTATE_2_3.py" --script-args "--endpoint 1 --int-arg PIXIT.WAITTIME.COUNTDOWN:5 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OVENOPSTATE_2_4.py" --script-args "--endpoint 1 --int-arg PIXIT.OVENOPSTATE.ErrorEventGen:1 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace-to json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_OVENOPSTATE_2_5.py" --script-args "--endpoint 1 --int-arg PIXIT.WAITTIME.REBOOT:5 --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS src/app/tests/suites/certification/ci-pics-values --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_MWOCTRL_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_MWOCTRL_2_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_MWOCTRL_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_MWOM_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCRUNM_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCRUNM_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto --int-arg PIXIT.RVCRUNM.MODE_CHANGE_OK:0 PIXIT.RVCRUNM.MODE_CHANGE_FAIL:2"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCRUNM_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto --int-arg PIXIT.RVCRUNM.MODE_A:1 PIXIT.RVCRUNM.MODE_B:2"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCCLEANM_1_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCCLEANM_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto --int-arg PIXIT.RVCCLEANM.MODE_CHANGE_FAIL:1 PIXIT.RVCCLEANM.MODE_CHANGE_OK:2"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCCLEANM_2_2.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCOPSTATE_2_1.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCOPSTATE_2_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_file json:out/trace_data/app-{SCRIPT_BASE_NAME}.json" --script "src/python_testing/TC_RVCOPSTATE_2_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --PICS examples/rvc-app/rvc-common/pics/rvc-app-pics-values --endpoint 1 --trace-to json:out/trace_data/test-{SCRIPT_BASE_NAME}.json --trace-to perfetto:out/trace_data/test-{SCRIPT_BASE_NAME}.perfetto"' + scripts/run_in_python_env.sh out/venv './src/python_testing/test_testing/test_TC_ICDM_2_1.py' + scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestIdChecks.py' + - name: Uploading core files uses: actions/upload-artifact@v4 if: ${{ failure() && !env.ACT }} @@ -590,7 +608,7 @@ jobs: TSAN_OPTIONS: "halt_on_error=1" if: github.actor != 'restyled-io[bot]' && false - runs-on: macos-latest + runs-on: macos-13 steps: - name: Checkout @@ -622,7 +640,7 @@ jobs: " - name: Run Tests run: | - scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/darwin-x64-all-clusters-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 3840 --interface-id -1" --script-args "-t 3600 --disable-test ClusterObjectTests.TestTimedRequestTimeout"' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --app out/darwin-x64-all-clusters-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --quiet --app-args "--discriminator 3840 --interface-id -1" --script-args "-t 3600 --disable-test ClusterObjectTests.TestTimedRequestTimeout"' - name: Uploading core files uses: actions/upload-artifact@v4 if: ${{ failure() && !env.ACT }} From caf613140b4d079ac73e1102137d7292964e0ae8 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 9 Jul 2024 13:18:44 -0700 Subject: [PATCH 27/75] tests.yaml from master --- .github/workflows/tests.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index a8bdfdcdc2c1ec..158339e90a4231 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -529,6 +529,7 @@ jobs: scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_ICDManagementCluster.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_IDM_1_2.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_IDM_1_4.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_IDM_4_2.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_PWRTL_2_1.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RR_1_1.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_SC_3_6.py' @@ -579,6 +580,7 @@ jobs: scripts/run_in_python_env.sh out/venv './scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py' scripts/run_in_python_env.sh out/venv './src/python_testing/test_testing/test_TC_ICDM_2_1.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestIdChecks.py' + scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/test_testing/test_IDM_10_4.py' - name: Uploading core files uses: actions/upload-artifact@v4 From e37cf0c9104c1569af7b3c4756c32029b1bbcac7 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 9 Jul 2024 21:06:28 -0700 Subject: [PATCH 28/75] Updates steps output and test runner configs --- src/python_testing/TC_SC_4_3.py | 99 +++++++++++++++++++++++++++++---- 1 file changed, 87 insertions(+), 12 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index fd11f0d2eb0e37..02792ed8636e46 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -15,11 +15,18 @@ # limitations under the License. # +# test-runner-runs: run1 +# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto + import ipaddress import logging import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main +from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main, TestStep from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType # from mobly import asserts @@ -39,6 +46,27 @@ class TC_SC_4_3(MatterBaseTest): + def steps_TC_SC_4_3(self): + return [TestStep(1, "DUT is commissioned on the same fabric as TH."), + TestStep(2, "TH reads ServerList attribute from the Descriptor cluster on EP0. ", + "If the ICD Management cluster ID (70,0x46) is present in the list, set supports_icd to true, otherwise set supports_icd to false."), + TestStep(3, "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.", ""), + TestStep(4, "If supports_icd is true, TH reads FeatureMap from the ICD Management cluster on EP0. If the LITS feature is set, set supports_lit to true. Otherwise set supports_lit to false.", ""), + TestStep(5, "TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the assigned 64-bit Node identifier, each expressed as a fixed-length sixteen-character hexadecimal string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen.", ""), + TestStep(6, "TH performs a query for the SRV record against the qname instance_qname.", + "Verify SRV record is returned"), + TestStep(7, "TH performs a query for the TXT record against the qname instance_qname.", + "Verify TXT record is returned"), + TestStep(8, "TH performs a query for the AAAA record against the target listed in the SRV record", + "Verify AAAA record is returned"), + TestStep(9, "TH verifies the following from the returned records:", + "Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a 12-character uppercase hexadecimal string. • If (MCORE.COM.THR) target, the hostname must be a 16-character hex string using capital letters. ICD TXT key: • If supports_lit is false, verify that the ICD key is NOT present in the TXT record • If supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII) SII TXT key: • If supports_icd is true and supports_lit is false, set sit_mode to true • If supports_icd is true and supports_lit is true, set sit_mode to true if ICD=0 otherwise set sit_mode to false • If supports_icd is false, set sit_mode to false • If sit_mode is true, verify that the SII key IS present in the TXT record • if the SII key is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) SAI TXT key: • if supports_icd is true, verify that the SAI key is present in the TXT record • If the SAI key is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms)"), + TestStep(10, "TH performs a DNS-SD browse for _I._sub._matter._tcp.local, where is the 64-bit compressed Fabric identifier, expressed as a fixed-length, sixteencharacter hexadecimal string, encoded as ASCII (UTF-8) text using capital letters.", + "Verify DUT returns a PTR record with DNS-SD instance name set to instance_name"), + TestStep(11, "TH performs a DNS-SD browse for _matter._tcp.local", + "Verify DUT returns a PTR record with DNS-SD instance name set to instance_name"), + ] + ONE_HOUR_IN_MS = 3600000 MAX_SAT_VALUE = 65535 MAX_T_VALUE = 6 @@ -141,10 +169,13 @@ async def test_TC_SC_4_3(self): # sit_mode = None # *** STEP 1 *** - self.print_step("1", "DUT is commissioned on the same fabric as TH.") + # DUT is commissioned on the same fabric as TH. + self.step(1) # *** STEP 2 *** - self.print_step("2", "TH reads ServerList attribute from the Descriptor cluster on EP0. If the ICD Management cluster ID (70,0x46) is present in the list, set supports_icd to true, otherwise set supports_icd to false.") + # TH reads from the DUT the ServerList attribute from the Descriptor cluster on EP0. If the ICD Management + # cluster ID (70,0x46) is present in the list, set supports_icd to true, otherwise set supports_icd to false. + self.step(2) ep0_servers = await self.get_descriptor_server_list() # Check if ep0_servers contains the ICD Management cluster ID (0x0046) @@ -152,14 +183,17 @@ async def test_TC_SC_4_3(self): logging.info(f"\n\n\tsupports_icd: {supports_icd}\n\n") # *** STEP 3 *** - self.print_step( - "3", "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.") + # If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves + # as active_mode_threshold. + self.step(3) if supports_icd: active_mode_threshold_ms = await self.get_idle_mode_threshhold_ms() logging.info(f"\n\n\tactive_mode_threshold_ms: {active_mode_threshold_ms}\n\n") # *** STEP 4 *** - self.print_step("4", "If supports_icd is true, TH reads FeatureMap from the ICD Management cluster on EP0. If the LITS feature is set, set supports_lit to true. Otherwise set supports_lit to false.") + # If supports_icd is true, TH reads FeatureMap from the ICD Management cluster on EP0. If the LITS feature + # is set, set supports_lit to true. Otherwise set supports_lit to false. + self.step(4) if supports_icd: feature_map = await self.get_icd_feature_map() LITS = Clusters.IcdManagement.Bitmaps.Feature.kLongIdleTimeSupport @@ -167,22 +201,55 @@ async def test_TC_SC_4_3(self): logging.info(f"\n\n\tkLongIdleTimeSupport set: {supports_lit}\n\n") # *** STEP 5 *** - self.print_step("5", "TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the assigned 64-bit Node identifier, each expressed as a fixed-length sixteen-character hexadecimal string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen.") + # TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the + # assigned 64-bit Node identifier, each expressed as a fixed-length sixteen-character hexadecimal + # string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen. + self.step(5) instance_name = self.get_dut_instance_name() - # PENDING STEPS 6-8 + + # *** STEP 6 *** + # TH performs a query for the SRV record against the qname instance_qname. + # Verify SRV record is returned + self.step(6) + + # *** STEP 7 *** + # TH performs a query for the TXT record against the qname instance_qname. + # Verify TXT record is returned + self.step(7) + + # *** STEP 8 *** + # TH performs a query for the AAAA record against the target listed in the SRV record. + # Verify AAAA record is returned + self.step(8) + + + + print("\n"*10) mdns = MdnsDiscovery() await mdns.get_service_by_record_type( service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", service_type=MdnsServiceType.OPERATIONAL.value, - record_type=DNSRecordType.SRV, + record_type=DNSRecordType.TXT, log_output=True, load_from_cache=False ) + print("\n"*10) + + # # *** STEP 9 *** - # self.print_step("9", "TH verifies ICD, SII, SAI, SAT, and T TXT record keys/vales of the returned record.") + # TH verifies the following from the returned records: Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a + # 12-character uppercase hexadecimal string. • If (MCORE.COM.THR) target, the hostname must be a 16-character hex string using capital + # letters. ICD TXT key: • If supports_lit is false, verify that the ICD key is NOT present in the TXT record • If supports_lit is true, + # verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII) SII TXT key: • If supports_icd is true and + # supports_lit is false, set sit_mode to true • If supports_icd is true and supports_lit is true, set sit_mode to true if ICD=0 + # otherwise set sit_mode to false • If supports_icd is false, set sit_mode to false • If sit_mode is true, verify that the SII key IS + # present in the TXT record • if the SII key is present, verify it is a decimal value with no leading zeros and is less than or equal + # to 3600000 (1h in ms) SAI TXT key: • if supports_icd is true, verify that the SAI key is present in the TXT record • If the SAI key + # is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) + self.step(9) # # ICD TXT KEY # if supports_lit: @@ -255,12 +322,20 @@ async def test_TC_SC_4_3(self): # asserts.assert_true(result, message) # # *** STEP 10 *** - # self.print_step("10", "Verify DUT returns a PTR record with DNS-SD instance name set instance_name.") + # TH performs a DNS-SD browse for _I._sub._matter._tcp.local, where is the 64-bit compressed Fabric identifier, expressed as a fixed-length, sixteencharacter hexadecimal string, encoded as + # ASCII (UTF-8) text using capital letters. Verify DUT returns a PTR record with DNS-SD instance name set to instance_name + self.step(10) # service_types = await mdns.get_service_types(log_output=True) # op_sub_type = self.get_operational_subtype() # asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") - print("\n"*10) + # # *** STEP 11 *** + # TH performs a DNS-SD browse for _matter._tcp.local + # Verify DUT returns a PTR record with DNS-SD instance name set to instance_name + self.step(11) + + + # input() From fe29ddef926a926834d15866b47087ffeb26f773 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 9 Jul 2024 21:09:50 -0700 Subject: [PATCH 29/75] Adds tc to tests.yaml --- .github/workflows/tests.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index ce9da1b635563f..866a30f17c4419 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -534,6 +534,7 @@ jobs: scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_PWRTL_2_1.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_RR_1_1.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_SC_3_6.py' + scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_SC_4_3.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_1.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_10.py' scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/python_testing/TC_TIMESYNC_2_11.py' From 04526685ee8ebcf0f1dc8d0842317db01a14e5ab Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 16 Jul 2024 09:31:40 -0700 Subject: [PATCH 30/75] Update --- src/python_testing/TC_SC_4_3.py | 66 +++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 16 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 02792ed8636e46..86723cecc71336 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -24,12 +24,13 @@ import ipaddress import logging +import dns.resolver import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main, TestStep from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType -# from mobly import asserts +from mobly import asserts ''' Category @@ -206,36 +207,69 @@ async def test_TC_SC_4_3(self): # string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen. self.step(5) instance_name = self.get_dut_instance_name() - - + instance_qname = f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}" # *** STEP 6 *** # TH performs a query for the SRV record against the qname instance_qname. # Verify SRV record is returned self.step(6) + print("\n"*10) + mdns = MdnsDiscovery() + operational_record = await mdns.get_service_by_record_type( + service_name=instance_qname, + service_type=MdnsServiceType.OPERATIONAL.value, + record_type=DNSRecordType.SRV, + log_output=True, + load_from_cache=False + ) + + # Verify SRV record is returned + srv_record_returned = operational_record is not None and operational_record.service_name == instance_qname + asserts.assert_true(srv_record_returned, "SRV record was not returned") # *** STEP 7 *** # TH performs a query for the TXT record against the qname instance_qname. # Verify TXT record is returned self.step(7) - - # *** STEP 8 *** - # TH performs a query for the AAAA record against the target listed in the SRV record. - # Verify AAAA record is returned - self.step(8) - - - - print("\n"*10) - mdns = MdnsDiscovery() - await mdns.get_service_by_record_type( - service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", + operational_record = await mdns.get_service_by_record_type( + service_name=instance_qname, service_type=MdnsServiceType.OPERATIONAL.value, record_type=DNSRecordType.TXT, log_output=True, load_from_cache=False ) - print("\n"*10) + + # Verify TXT record is returned and it contains values + txt_record_returned = operational_record.txt_record is not None and bool(operational_record.txt_record) + asserts.assert_true(txt_record_returned, "TXT record not returned or contains no values") + + # *** STEP 8 *** + # TH performs a query for the AAAA record against the target listed in the SRV record. + # Verify AAAA record is returned + self.step(8) + + # domain = operational_record.server + # try: + # answers = dns.resolver.resolve(domain, 'AAAA') + # for answer in answers: + # print(f"AAAA record for {domain}: {answer}") + # except dns.resolver.NoAnswer: + # print(f"No AAAA record found for {domain}") + # except dns.resolver.NXDOMAIN: + # print(f"Domain {domain} does not exist") + # except Exception as e: + # print(f"An error occurred: {e}") + + # print("\n"*10) + # mdns = MdnsDiscovery() + # await mdns.get_service_by_record_type( + # service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", + # service_type=MdnsServiceType.OPERATIONAL.value, + # record_type=DNSRecordType.TXT, + # log_output=True, + # load_from_cache=False + # ) + # print("\n"*10) From a3b894d1e44b4857c3f8ba64f804c9a8c8bd03a2 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 02:18:18 -0700 Subject: [PATCH 31/75] Updates to make a fresh question each time --- .../mdns_discovery/mdns_async_service_info.py | 40 ++++++------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 16224a8c5f044b..4d47cb940ba359 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -189,54 +189,38 @@ def _generate_request_query( qu_question = question_type is QU_QUESTION if record_type is None or record_type is DNSRecordType.SRV: print("Requesting MDNS SRV record...") - self._add_question_with_known_answers( - out, qu_question, history, cache, now, name, _TYPE_SRV, _CLASS_IN, True + self._add_question( + out, qu_question, server, _TYPE_SRV, _CLASS_IN ) if record_type is None or record_type is DNSRecordType.TXT: print("Requesting MDNS TXT record...") - self._add_question_with_known_answers( - out, qu_question, history, cache, now, name, _TYPE_TXT, _CLASS_IN, True + self._add_question( + out, qu_question, server, _TYPE_TXT, _CLASS_IN ) if record_type is None or record_type is DNSRecordType.A: print("Requesting MDNS A record...") - self._add_question_with_known_answers( - out, qu_question, history, cache, now, server, _TYPE_A, _CLASS_IN, False + self._add_question( + out, qu_question, server, _TYPE_A, _CLASS_IN ) if record_type is None or record_type is DNSRecordType.AAAA: print("Requesting MDNS AAAA record...") - self._add_question_with_known_answers( - out, qu_question, history, cache, now, server, _TYPE_AAAA, _CLASS_IN, False + self._add_question( + out, qu_question, server, _TYPE_AAAA, _CLASS_IN ) return out - def _add_question_with_known_answers( + def _add_question( self, out: DNSOutgoing, qu_question: bool, - question_history: QuestionHistory, - cache: DNSCache, - now: float_, name: str_, type_: int_, - class_: int_, - skip_if_known_answers: bool, + class_: int_ ) -> None: - """Add a question with known answers if its not suppressed.""" - known_answers = { - answer for answer in cache.get_all_by_details(name, type_, class_) if not answer.is_stale(now) - } - if skip_if_known_answers and known_answers: - return + """Add a question.""" question = DNSQuestion(name, type_, class_) - if qu_question: - question.unicast = True - elif question_history.suppresses(question, now, known_answers): - return - else: - question_history.add_question_at_time(question, now, known_answers) + question.unicast = qu_question out.add_question(question) - for answer in known_answers: - out.add_answer_at_time(answer, now) def _get_initial_delay(self) -> float_: return _LISTENER_TIME From eba4a1eebba2d677aeba2c7e8faa82101b78e255 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 02:18:57 -0700 Subject: [PATCH 32/75] Update progress --- src/python_testing/TC_SC_4_3.py | 181 ++++++++++++++------------------ 1 file changed, 76 insertions(+), 105 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 86723cecc71336..59428b23ac7a52 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -24,7 +24,6 @@ import ipaddress import logging -import dns.resolver import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main, TestStep @@ -213,7 +212,6 @@ async def test_TC_SC_4_3(self): # TH performs a query for the SRV record against the qname instance_qname. # Verify SRV record is returned self.step(6) - print("\n"*10) mdns = MdnsDiscovery() operational_record = await mdns.get_service_by_record_type( service_name=instance_qname, @@ -221,8 +219,8 @@ async def test_TC_SC_4_3(self): record_type=DNSRecordType.SRV, log_output=True, load_from_cache=False - ) - + ) + # Verify SRV record is returned srv_record_returned = operational_record is not None and operational_record.service_name == instance_qname asserts.assert_true(srv_record_returned, "SRV record was not returned") @@ -247,31 +245,8 @@ async def test_TC_SC_4_3(self): # TH performs a query for the AAAA record against the target listed in the SRV record. # Verify AAAA record is returned self.step(8) - - # domain = operational_record.server - # try: - # answers = dns.resolver.resolve(domain, 'AAAA') - # for answer in answers: - # print(f"AAAA record for {domain}: {answer}") - # except dns.resolver.NoAnswer: - # print(f"No AAAA record found for {domain}") - # except dns.resolver.NXDOMAIN: - # print(f"Domain {domain} does not exist") - # except Exception as e: - # print(f"An error occurred: {e}") - - # print("\n"*10) - # mdns = MdnsDiscovery() - # await mdns.get_service_by_record_type( - # service_name=f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}", - # service_type=MdnsServiceType.OPERATIONAL.value, - # record_type=DNSRecordType.TXT, - # log_output=True, - # load_from_cache=False - # ) - # print("\n"*10) - + # PENDING # # *** STEP 9 *** # TH verifies the following from the returned records: Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a @@ -285,94 +260,90 @@ async def test_TC_SC_4_3(self): # is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) self.step(9) - # # ICD TXT KEY - # if supports_lit: - # logging.info("supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") - - # # Verify the ICD key IS present - # asserts.assert_in('ICD', operational.txt_record, "ICD key is NOT present in the TXT record.") - - # # Verify it has the value of 0 or 1 (ASCII) - # icd_value = int(operational.txt_record['ICD']) - # asserts.assert_true(icd_value == 0 or icd_value == 1, "ICD value is different than 0 or 1 (ASCII).") - # else: - # logging.info("supports_lit is false, verify that the ICD key is NOT present in the TXT record.") - # asserts.assert_not_in('ICD', operational.txt_record, "ICD key is present in the TXT record.") - - # # SII TXT KEY - # if supports_icd and not supports_lit: - # sit_mode = True - - # if supports_icd and supports_lit: - # if icd_value == 0: - # sit_mode = True - # else: - # sit_mode = False - - # if not supports_icd: - # sit_mode = False - - # if sit_mode: - # logging.info("sit_mode is True, verify the SII key IS present.") - # asserts.assert_in('SII', operational.txt_record, "SII key is NOT present in the TXT record.") - - # logging.info("Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") - # sii_value = operational.txt_record['SII'] - # result, message = self.verify_decimal_value(sii_value, self.ONE_HOUR_IN_MS) - # asserts.assert_true(result, message) - - # # SAI TXT KEY - # if supports_icd: - # logging.info("supports_icd is True, verify the SAI key IS present.") - # asserts.assert_in('SAI', operational.txt_record, "SAI key is NOT present in the TXT record.") - - # logging.info("Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") - # sai_value = operational.txt_record['SAI'] - # result, message = self.verify_decimal_value(sai_value, self.ONE_HOUR_IN_MS) - # asserts.assert_true(result, message) - - # # SAT TXT KEY - # if 'SAT' in operational.txt_record: - # logging.info( - # "SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") - # sat_value = operational.txt_record['SAT'] - # result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) - # asserts.assert_true(result, message) - - # if supports_icd: - # logging.info("supports_icd is True, verify the SAT value is equal to active_mode_threshold.") - # asserts.assert_equal(int(sat_value), active_mode_threshold_ms) - - # # T TXT KEY - # if 'T' in operational.txt_record: - # logging.info(f"T key is present in TXT record, verify if that it is a decimal value with no leading zeros and is less than or equal to 6. Convert the value to a bitmap and verify bit 0 is clear.") - # t_value = operational.txt_record['T'] - # result, message = self.verify_t_value(t_value) - # asserts.assert_true(result, message) - - # # AAAA - # logging.info("Verify the AAAA record contains at least one IPv6 address") - # result, message = self.contains_ipv6_address(operational.addresses) - # asserts.assert_true(result, message) + # ICD TXT KEY + if supports_lit: + logging.info("supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") + + # Verify the ICD key IS present + asserts.assert_in('ICD', operational_record.txt_record, "ICD key is NOT present in the TXT record.") + + # Verify it has the value of 0 or 1 (ASCII) + icd_value = int(operational_record.txt_record['ICD']) + asserts.assert_true(icd_value == 0 or icd_value == 1, "ICD value is different than 0 or 1 (ASCII).") + else: + logging.info("supports_lit is false, verify that the ICD key is NOT present in the TXT record.") + asserts.assert_not_in('ICD', operational_record.txt_record, "ICD key is present in the TXT record.") + + # SII TXT KEY + if supports_icd and not supports_lit: + sit_mode = True + + if supports_icd and supports_lit: + if icd_value == 0: + sit_mode = True + else: + sit_mode = False + + if not supports_icd: + sit_mode = False + + if sit_mode: + logging.info("sit_mode is True, verify the SII key IS present.") + asserts.assert_in('SII', operational_record.txt_record, "SII key is NOT present in the TXT record.") + + logging.info("Verify SII value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + sii_value = operational_record.txt_record['SII'] + result, message = self.verify_decimal_value(sii_value, self.ONE_HOUR_IN_MS) + asserts.assert_true(result, message) + + # SAI TXT KEY + if supports_icd: + logging.info("supports_icd is True, verify the SAI key IS present.") + asserts.assert_in('SAI', operational_record.txt_record, "SAI key is NOT present in the TXT record.") + + logging.info("Verify SAI value is a decimal with no leading zeros and is less than or equal to 3600000 (1h in ms).") + sai_value = operational_record.txt_record['SAI'] + result, message = self.verify_decimal_value(sai_value, self.ONE_HOUR_IN_MS) + asserts.assert_true(result, message) + + # SAT TXT KEY + if 'SAT' in operational_record.txt_record: + logging.info( + "SAT key is present in TXT record, verify that it is a decimal value with no leading zeros and is less than or equal to 65535.") + sat_value = operational_record.txt_record['SAT'] + result, message = self.verify_decimal_value(sat_value, self.MAX_SAT_VALUE) + asserts.assert_true(result, message) + + if supports_icd: + logging.info("supports_icd is True, verify the SAT value is equal to active_mode_threshold.") + asserts.assert_equal(int(sat_value), active_mode_threshold_ms) + + # T TXT KEY + if 'T' in operational_record.txt_record: + logging.info(f"T key is present in TXT record, verify if that it is a decimal value with no leading zeros and is less than or equal to 6. Convert the value to a bitmap and verify bit 0 is clear.") + t_value = operational_record.txt_record['T'] + result, message = self.verify_t_value(t_value) + asserts.assert_true(result, message) + + # AAAA + logging.info("Verify the AAAA record contains at least one IPv6 address") + result, message = self.contains_ipv6_address(operational_record.addresses) + asserts.assert_true(result, message) # # *** STEP 10 *** # TH performs a DNS-SD browse for _I._sub._matter._tcp.local, where is the 64-bit compressed Fabric identifier, expressed as a fixed-length, sixteencharacter hexadecimal string, encoded as # ASCII (UTF-8) text using capital letters. Verify DUT returns a PTR record with DNS-SD instance name set to instance_name self.step(10) - # service_types = await mdns.get_service_types(log_output=True) - # op_sub_type = self.get_operational_subtype() - # asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") + service_types = await mdns.get_service_types(log_output=True) + op_sub_type = self.get_operational_subtype() + asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") # # *** STEP 11 *** # TH performs a DNS-SD browse for _matter._tcp.local # Verify DUT returns a PTR record with DNS-SD instance name set to instance_name self.step(11) - - - - # input() - + # PENDING if __name__ == "__main__": default_matter_test_main() From bbf97f6c47a83e96149bb3e9a9ba513d88abca31 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 02:31:40 -0700 Subject: [PATCH 33/75] Fix restyle --- src/python_testing/TC_SC_4_3.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 59428b23ac7a52..6d6986faf82c86 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -26,9 +26,8 @@ import logging import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main, TestStep +from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType - from mobly import asserts ''' @@ -50,7 +49,8 @@ def steps_TC_SC_4_3(self): return [TestStep(1, "DUT is commissioned on the same fabric as TH."), TestStep(2, "TH reads ServerList attribute from the Descriptor cluster on EP0. ", "If the ICD Management cluster ID (70,0x46) is present in the list, set supports_icd to true, otherwise set supports_icd to false."), - TestStep(3, "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.", ""), + TestStep(3, + "If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves as active_mode_threshold.", ""), TestStep(4, "If supports_icd is true, TH reads FeatureMap from the ICD Management cluster on EP0. If the LITS feature is set, set supports_lit to true. Otherwise set supports_lit to false.", ""), TestStep(5, "TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the assigned 64-bit Node identifier, each expressed as a fixed-length sixteen-character hexadecimal string, encoded as ASCII (UTF-8) text using capital letters, separated by a hyphen.", ""), TestStep(6, "TH performs a query for the SRV record against the qname instance_qname.", @@ -219,7 +219,7 @@ async def test_TC_SC_4_3(self): record_type=DNSRecordType.SRV, log_output=True, load_from_cache=False - ) + ) # Verify SRV record is returned srv_record_returned = operational_record is not None and operational_record.service_name == instance_qname @@ -345,5 +345,6 @@ async def test_TC_SC_4_3(self): # PENDING + if __name__ == "__main__": default_matter_test_main() From b76576b4e00a08eefaa25103d448277ef9d109df Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 10:06:15 -0700 Subject: [PATCH 34/75] Fix Lint --- src/python_testing/TC_SC_4_3.py | 10 ++++++++++ .../mdns_discovery/mdns_async_service_info.py | 5 +---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 6d6986faf82c86..3a4f7dc6fed62b 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -247,6 +247,16 @@ async def test_TC_SC_4_3(self): self.step(8) # PENDING + + operational_record_a = await mdns.get_service_by_record_type( + service_name=operational_record.server, + service_type=MdnsServiceType.OPERATIONAL.value, + record_type=DNSRecordType.TXT, + log_output=True, + load_from_cache=False + ) + + # # *** STEP 9 *** # TH verifies the following from the returned records: Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 4d47cb940ba359..d26c0f46c1c3f3 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -22,9 +22,8 @@ from random import randint from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast -from zeroconf import (BadTypeInNameException, DNSAddress, DNSCache, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, +from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) -from zeroconf._history import QuestionHistory from zeroconf._utils.net import _encode_address from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) @@ -184,8 +183,6 @@ def _generate_request_query( out = DNSOutgoing(_FLAGS_QR_QUERY) name = self._name server = self.server or name - cache = zc.cache - history = zc.question_history qu_question = question_type is QU_QUESTION if record_type is None or record_type is DNSRecordType.SRV: print("Requesting MDNS SRV record...") From 4a53936430a297733c07dd27ec84596ad723d242 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 10:08:26 -0700 Subject: [PATCH 35/75] Fix restyle --- src/python_testing/TC_SC_4_3.py | 10 ---------- .../mdns_discovery/mdns_async_service_info.py | 4 ++-- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 3a4f7dc6fed62b..6d6986faf82c86 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -247,16 +247,6 @@ async def test_TC_SC_4_3(self): self.step(8) # PENDING - - operational_record_a = await mdns.get_service_by_record_type( - service_name=operational_record.server, - service_type=MdnsServiceType.OPERATIONAL.value, - record_type=DNSRecordType.TXT, - log_output=True, - load_from_cache=False - ) - - # # *** STEP 9 *** # TH verifies the following from the returned records: Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index d26c0f46c1c3f3..b680dcadbcc1f4 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -22,8 +22,8 @@ from random import randint from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast -from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, - DNSRecord, DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) +from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, + DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) from zeroconf._utils.net import _encode_address from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) From 7c1f6b6f983dd326754db2a7fbe7a1ea1fa870d8 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 10:30:04 -0700 Subject: [PATCH 36/75] Fix lint --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 6d6986faf82c86..ed5bab045d273e 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -320,7 +320,7 @@ async def test_TC_SC_4_3(self): # T TXT KEY if 'T' in operational_record.txt_record: - logging.info(f"T key is present in TXT record, verify if that it is a decimal value with no leading zeros and is less than or equal to 6. Convert the value to a bitmap and verify bit 0 is clear.") + logging.info("T key is present in TXT record, verify if that it is a decimal value with no leading zeros and is less than or equal to 6. Convert the value to a bitmap and verify bit 0 is clear.") t_value = operational_record.txt_record['T'] result, message = self.verify_t_value(t_value) asserts.assert_true(result, message) From 4003dfcc9dad042bf7fef5ebc0cc991d8956dc43 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 12:14:58 -0700 Subject: [PATCH 37/75] Adds CI task tags --- src/python_testing/TC_SC_4_3.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index ed5bab045d273e..21e90e2761d5d6 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -15,12 +15,14 @@ # limitations under the License. # +# === BEGIN CI TEST ARGUMENTS === # test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} +# test-runner-run/run1/app: ${LIT_ICD_APP} # test-runner-run/run1/factoryreset: True # test-runner-run/run1/quiet: True # test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json # test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto +# === END CI TEST ARGUMENTS === import ipaddress import logging From 7a178c931c620aabd1e643fea8834989ca516a65 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 13:03:48 -0700 Subject: [PATCH 38/75] Completes step 11 --- src/python_testing/TC_SC_4_3.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 21e90e2761d5d6..1de48cf7e48142 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -222,6 +222,9 @@ async def test_TC_SC_4_3(self): log_output=True, load_from_cache=False ) + + # Will be used in Step 11 + server = operational_record.server # Verify SRV record is returned srv_record_returned = operational_record is not None and operational_record.service_name == instance_qname @@ -344,8 +347,15 @@ async def test_TC_SC_4_3(self): # TH performs a DNS-SD browse for _matter._tcp.local # Verify DUT returns a PTR record with DNS-SD instance name set to instance_name self.step(11) + op_service_info = await mdns._get_service( + service_type=MdnsServiceType.OPERATIONAL, + log_output=True, + discovery_timeout_sec=15 + ) - # PENDING + # Verify DUT returns a PTR record with DNS-SD instance name set instance_name + asserts.assert_equal(op_service_info.server, server, f"No PTR record with DNS-SD instance name '{MdnsServiceType.OPERATIONAL.value}'") + asserts.assert_equal(instance_name, op_service_info.instance_name, "Instance name mismatch") if __name__ == "__main__": From c0c691c291fec75d0d59d50f561ba7fe85212f88 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 17 Jul 2024 13:06:43 -0700 Subject: [PATCH 39/75] Fix restyled --- src/python_testing/TC_SC_4_3.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 1de48cf7e48142..0bf4d51a2e26b9 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -222,7 +222,7 @@ async def test_TC_SC_4_3(self): log_output=True, load_from_cache=False ) - + # Will be used in Step 11 server = operational_record.server @@ -354,7 +354,8 @@ async def test_TC_SC_4_3(self): ) # Verify DUT returns a PTR record with DNS-SD instance name set instance_name - asserts.assert_equal(op_service_info.server, server, f"No PTR record with DNS-SD instance name '{MdnsServiceType.OPERATIONAL.value}'") + asserts.assert_equal(op_service_info.server, server, + f"No PTR record with DNS-SD instance name '{MdnsServiceType.OPERATIONAL.value}'") asserts.assert_equal(instance_name, op_service_info.instance_name, "Instance name mismatch") From 1bf091e5a39ed0907ebc7a8e89ef45f3ebadf149 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Fri, 19 Jul 2024 09:38:42 -0700 Subject: [PATCH 40/75] Steps 8,11 --- src/python_testing/TC_SC_4_3.py | 24 ++++-- .../mdns_discovery/mdns_async_service_info.py | 47 ++++++----- .../mdns_discovery/mdns_discovery.py | 80 ++++++++++++------- 3 files changed, 95 insertions(+), 56 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 0bf4d51a2e26b9..be25a17f22cd43 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -30,6 +30,7 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType +from zeroconf.const import _TYPES, _TYPE_AAAA from mobly import asserts ''' @@ -161,8 +162,6 @@ def contains_ipv6_address(addresses): @async_test_body async def test_TC_SC_4_3(self): - print("\n"*10) - supports_icd = None supports_lit = None active_mode_threshold_ms = None @@ -219,11 +218,10 @@ async def test_TC_SC_4_3(self): service_name=instance_qname, service_type=MdnsServiceType.OPERATIONAL.value, record_type=DNSRecordType.SRV, - log_output=True, - load_from_cache=False + log_output=True ) - # Will be used in Step 11 + # Will be used in Step 8 and 11 server = operational_record.server # Verify SRV record is returned @@ -238,8 +236,7 @@ async def test_TC_SC_4_3(self): service_name=instance_qname, service_type=MdnsServiceType.OPERATIONAL.value, record_type=DNSRecordType.TXT, - log_output=True, - load_from_cache=False + log_output=True ) # Verify TXT record is returned and it contains values @@ -251,7 +248,18 @@ async def test_TC_SC_4_3(self): # Verify AAAA record is returned self.step(8) - # PENDING + quada_record = await mdns.get_service_by_record_type( + service_name=server, + record_type=DNSRecordType.AAAA, + log_output=True + ) + + answer_record_type = quada_record.get_type(quada_record.type) + quada = _TYPES[_TYPE_AAAA] + + # Verify AAAA record is returned + asserts.assert_equal(server, quada_record.name, f"Server name mismatch: {server} vs {quada_record.name}") + asserts.assert_equal(quada, answer_record_type, f"Record type should be {quada} but got {answer_record_type}") # # *** STEP 9 *** # TH verifies the following from the returned records: Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index b680dcadbcc1f4..53983126d01032 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -23,7 +23,7 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, - DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) + DNSService, DNSText, RecordUpdateListener, ServiceInfo, Zeroconf, current_time_millis, service_type_name) from zeroconf._utils.net import _encode_address from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) @@ -57,8 +57,9 @@ class DNSRecordType(enum.Enum): class MdnsAsyncServiceInfo(ServiceInfo): def __init__( self, - type_: str, + zc: 'Zeroconf', name: str, + type_: str = None, port: Optional[int] = None, weight: int = 0, priority: int = 0, @@ -74,12 +75,15 @@ def __init__( # Accept both none, or one, but not both. if addresses is not None and parsed_addresses is not None: raise TypeError("addresses and parsed_addresses cannot be provided together") - if not type_.endswith(service_type_name(name, strict=False)): + + if type_ and not type_.endswith(service_type_name(name, strict=False)): raise BadTypeInNameException + self.interface_index = interface_index self.text = b'' - self.type = type_ + self._zc = zc self._name = name + self.type = type_ self.key = name.lower() self._ipv4_addresses: List[IPv4Address] = [] self._ipv6_addresses: List[IPv6Address] = [] @@ -109,13 +113,11 @@ def __init__( async def async_request( self, - zc: 'Zeroconf', timeout: float, question_type: Optional[DNSQuestionType] = None, addr: Optional[str] = None, port: int = _MDNS_PORT, - record_type: DNSRecordType = None, - load_from_cache: bool = True + record_type: DNSRecordType = None ) -> bool: """Returns true if the service could be discovered on the network, and updates this object with details discovered. @@ -127,30 +129,26 @@ async def async_request( requests to a specific host that may be able to respond across subnets. """ - if not zc.started: - await zc.async_wait_for_start() + if not self._zc.started: + await self._zc.async_wait_for_start() now = current_time_millis() - if load_from_cache: - if self._load_from_cache(zc, now): - return True - if TYPE_CHECKING: - assert zc.loop is not None + assert self._zc.loop is not None first_request = True delay = self._get_initial_delay() next_ = now last = now + timeout try: - zc.async_add_listener(self, None) + self.async_add_listener(self, None) while not self._is_complete: if last <= now: return False if next_ <= now: this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION - out = self._generate_request_query(zc, now, this_question_type, record_type) + out: DNSOutgoing = self._generate_request_query(self._zc, now, this_question_type, record_type) first_request = False if out.questions: # All questions may have been suppressed @@ -158,7 +156,7 @@ async def async_request( # but keep waiting for answers in case another # client on the network is asking the same # question or they have not arrived yet. - zc.async_send(out, addr, port) + self._zc.async_send(out, addr, port) next_ = now + delay next_ += self._get_random_delay() if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: @@ -169,13 +167,24 @@ async def async_request( # history of the remote responder. delay = _DUPLICATE_QUESTION_INTERVAL - await self.async_wait(min(next_, last) - now, zc.loop) + await self.async_wait(min(next_, last) - now, self._zc.loop) now = current_time_millis() finally: - zc.async_remove_listener(self) + self._zc.async_remove_listener(self) return True + def async_add_listener( + self, listener: RecordUpdateListener, question: Optional[Union[DNSQuestion, List[DNSQuestion]]] + ) -> None: + """Adds a listener for a given question. The listener will have + its update_record method called when information is available to + answer the question(s). + + This function is not threadsafe and must be called in the eventloop. + """ + self._zc.record_manager.async_add_listener(listener, question) + def _generate_request_query( self, zc: 'Zeroconf', now: float_, question_type: DNSQuestionType, record_type: DNSRecordType ) -> DNSOutgoing: diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index ff5d4ded41ef60..b003c46140a63d 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -15,27 +15,26 @@ # limitations under the License. # - +import logging import asyncio import json from dataclasses import asdict, dataclass from enum import Enum from time import sleep -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Union, cast from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes - +from zeroconf._engine import AsyncListener +from zeroconf._protocol.incoming import DNSIncoming +from zeroconf._dns import DNSRecord @dataclass class MdnsServiceInfo: # The unique name of the mDNS service. service_name: str - # The service type of the service, typically indicating the service protocol and domain. - service_type: str - # The instance name of the service. instance_name: str @@ -66,6 +65,9 @@ class MdnsServiceInfo: # The time-to-live value for other records associated with the service. other_ttl: int + # The service type of the service, typically indicating the service protocol and domain. + service_type: Optional[str] = None + class MdnsServiceType(Enum): """ @@ -226,12 +228,11 @@ async def get_service_types(self, log_output: bool = False) -> List[str]: return discovered_services async def get_service_by_record_type(self, service_name: str, - service_type: str, record_type: DNSRecordType, - load_from_cache: bool = True, + service_type: str = None, discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC, log_output: bool = False - ) -> Optional[MdnsServiceInfo]: + ) -> Union[Optional[MdnsServiceInfo], Optional[DNSRecord]]: """ Asynchronously discovers an mDNS service within the network by service name, service type, and record type. @@ -244,12 +245,17 @@ async def get_service_by_record_type(self, service_name: str, record_type (DNSRecordType): The type of record to look for (SRV, TXT, AAAA, A). Returns: - Optional[MdnsServiceInfo]: An instance of MdnsServiceInfo or None if timeout reached. + Union[Optional[MdnsServiceInfo], Optional[DNSRecord]]: An instance of MdnsServiceInfo, + a DNSRecord object, or None. """ mdns_service_info = None - print( - f"Looking for MDNS service type '{service_type}', service name '{service_name}', record type '{record_type.name}'") + if service_type: + print( + f"\nLooking for MDNS service type '{service_type}', service name '{service_name}', record type '{record_type.name}'\n") + else: + print( + f"\nLooking for MDNS service with service name '{service_name}', record type '{record_type.name}'\n") # Adds service listener service_listener = MdnsServiceListener() @@ -263,26 +269,36 @@ async def get_service_by_record_type(self, service_name: str, finally: self._zc.remove_service_listener(service_listener) - # Get service info - service_info = MdnsAsyncServiceInfo(service_type, service_name) + # Prepare and perform query + service_info = MdnsAsyncServiceInfo(self._zc, name=service_name, type_=service_type) is_discovered = await service_info.async_request( - self._zc, 3000, - record_type=record_type, - load_from_cache=load_from_cache) + record_type=record_type) + + if not service_type: + # Service type not supplied so we can + # query against the target/server + for protocols in self._zc.engine.protocols: + listener = cast(AsyncListener, protocols) + if listener.data: + dns_incoming = DNSIncoming(listener.data) + if dns_incoming.data: + answers = dns_incoming.answers() + print(f"\nIncoming DNSRecord: {answers}\n") + return answers.pop(0) if answers else None + else: + # Adds service to discovered services + if is_discovered: + mdns_service_info = self._to_mdns_service_info_class(service_info) + self._discovered_services = {} + self._discovered_services[service_type] = [] + if mdns_service_info is not None: + self._discovered_services[service_type].append(mdns_service_info) - # Adds service to discovered services - if is_discovered: - mdns_service_info = self._to_mdns_service_info_class(service_info) - self._discovered_services = {} - self._discovered_services[service_type] = [] - if mdns_service_info is not None: - self._discovered_services[service_type].append(mdns_service_info) + if log_output: + self._log_output() - if log_output: - self._log_output() - - return mdns_service_info + return mdns_service_info # Private methods async def _discover(self, @@ -404,7 +420,7 @@ def _to_mdns_service_info_class(self, service_info: AsyncServiceInfo) -> MdnsSer mdns_service_info = MdnsServiceInfo( service_name=service_info.name, service_type=service_info.type, - instance_name=service_info.get_name(), + instance_name=self._get_instance_name(service_info), server=service_info.server, port=service_info.port, addresses=service_info.parsed_addresses(), @@ -418,6 +434,12 @@ def _to_mdns_service_info_class(self, service_info: AsyncServiceInfo) -> MdnsSer return mdns_service_info + def _get_instance_name(self, service_info: AsyncServiceInfo) -> str: + if service_info.type: + return service_info.name[: len(service_info.name) - len(service_info.type) - 1] + else: + return service_info.name + async def _get_service(self, service_type: MdnsServiceType, log_output: bool, discovery_timeout_sec: float From d5af8a58500320d7e48802f985c2e70155e498ff Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Fri, 19 Jul 2024 09:43:50 -0700 Subject: [PATCH 41/75] Fix restyled --- src/python_testing/TC_SC_4_3.py | 2 +- .../mdns_discovery/mdns_async_service_info.py | 4 ++-- src/python_testing/mdns_discovery/mdns_discovery.py | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index be25a17f22cd43..0fad77e16d3b46 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -30,8 +30,8 @@ import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType -from zeroconf.const import _TYPES, _TYPE_AAAA from mobly import asserts +from zeroconf.const import _TYPE_AAAA, _TYPES ''' Category diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 53983126d01032..d836b358cd6460 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -75,10 +75,10 @@ def __init__( # Accept both none, or one, but not both. if addresses is not None and parsed_addresses is not None: raise TypeError("addresses and parsed_addresses cannot be provided together") - + if type_ and not type_.endswith(service_type_name(name, strict=False)): raise BadTypeInNameException - + self.interface_index = interface_index self.text = b'' self._zc = zc diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index b003c46140a63d..1c51aefcae0203 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -15,7 +15,6 @@ # limitations under the License. # -import logging import asyncio import json from dataclasses import asdict, dataclass @@ -25,10 +24,11 @@ from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo from zeroconf import IPVersion, ServiceListener, ServiceStateChange, Zeroconf -from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes +from zeroconf._dns import DNSRecord from zeroconf._engine import AsyncListener from zeroconf._protocol.incoming import DNSIncoming -from zeroconf._dns import DNSRecord +from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconfServiceTypes + @dataclass class MdnsServiceInfo: @@ -274,7 +274,7 @@ async def get_service_by_record_type(self, service_name: str, is_discovered = await service_info.async_request( 3000, record_type=record_type) - + if not service_type: # Service type not supplied so we can # query against the target/server From 88dc100066222b58759a1ba8359fe416f9967082 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Fri, 19 Jul 2024 10:01:24 -0700 Subject: [PATCH 42/75] Adds timeout to get_service_types --- src/python_testing/mdns_discovery/mdns_discovery.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 1c51aefcae0203..d06933b233981a 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -204,7 +204,7 @@ async def get_all_services(self, log_output: bool = False, return self._discovered_services - async def get_service_types(self, log_output: bool = False) -> List[str]: + async def get_service_types(self, log_output: bool = False, discovery_timeout_sec: float = DISCOVERY_TIMEOUT_SEC,) -> List[str]: """ Asynchronously discovers all available mDNS services within the network and returns a list of the service types discovered. This method utilizes the AsyncZeroconfServiceTypes.async_find() @@ -219,8 +219,11 @@ async def get_service_types(self, log_output: bool = False) -> List[str]: element in the list is a string representing a unique type of service found during the discovery process. """ - - discovered_services = list(await AsyncZeroconfServiceTypes.async_find()) + try: + discovered_services = list(await asyncio.wait_for(AsyncZeroconfServiceTypes.async_find(), timeout=discovery_timeout_sec)) + except asyncio.TimeoutError: + print(f"MDNS service types discovery timed out after {discovery_timeout_sec} seconds.") + discovered_services = [] if log_output: print(f"MDNS discovered service types: {discovered_services}") From d9aaa1cab4a51e1a32e24253088e4f6808af7265 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Fri, 19 Jul 2024 10:46:23 -0700 Subject: [PATCH 43/75] Updates get_service_types description --- src/python_testing/mdns_discovery/mdns_discovery.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index d06933b233981a..8c96bf5fea0140 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -213,6 +213,7 @@ async def get_service_types(self, log_output: bool = False, discovery_timeout_se Args: log_output (bool): If set to True, the discovered service types are logged to the console. This can be useful for debugging or informational purposes. Defaults to False. + discovery_timeout_sec (float): The maximum time (in seconds) to wait for the discovery process. Defaults to 10.0 seconds. Returns: List[str]: A list containing the service types (str) of the discovered mDNS services. Each From 5a4b29d08a89c1c3ac2176e53f56e9d3089a326e Mon Sep 17 00:00:00 2001 From: Raul Marquez <130402456+raul-marquez-csa@users.noreply.github.com> Date: Tue, 23 Jul 2024 23:07:13 -0700 Subject: [PATCH 44/75] Update src/python_testing/TC_SC_4_3.py Co-authored-by: C Freeman --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 0fad77e16d3b46..712a19a07944e9 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -145,7 +145,7 @@ def verify_t_value(self, t_value): else: return False, f"Bit 0 is not clear. T value ({t_value})" except ValueError: - return False, f"T value ({t_value}) is not a valid decimal number." + return False, f"T value ({t_value}) is not a valid integer" @staticmethod def contains_ipv6_address(addresses): From fd5aa3d529f11e7844a8e631340fe0fd63ec8bf4 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 23 Jul 2024 23:13:32 -0700 Subject: [PATCH 45/75] Adds clarifying comment --- src/python_testing/TC_SC_4_3.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 712a19a07944e9..b89e28b09af34b 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -222,6 +222,7 @@ async def test_TC_SC_4_3(self): ) # Will be used in Step 8 and 11 + # This is the hostname server = operational_record.server # Verify SRV record is returned From 70cd9a2cd6cc8c43714748d87efc3f24f02e4797 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 00:10:17 -0700 Subject: [PATCH 46/75] Adds MCORE.COM PICS checks --- src/python_testing/TC_SC_4_3.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index b89e28b09af34b..66b3d9c59afac8 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -26,6 +26,7 @@ import ipaddress import logging +import re import chip.clusters as Clusters from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main @@ -160,6 +161,18 @@ def contains_ipv6_address(addresses): continue return False, "No IPv6 addresses found." + @staticmethod + def verify_hostname(hostname: str, char_length: int) -> bool: + # Remove '.local' or '.local.' suffix if present + if hostname.endswith('.local'): + hostname = hostname[:-6] + elif hostname.endswith('.local.'): + hostname = hostname[:-7] + + # Regular expression to match an uppercase hexadecimal string of the specified length + pattern = re.compile(rf'^[0-9A-F]{{{char_length}}}$') + return bool(pattern.match(hostname)) + @async_test_body async def test_TC_SC_4_3(self): supports_icd = None @@ -274,6 +287,17 @@ async def test_TC_SC_4_3(self): # is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) self.step(9) + # Check MCORE.COM PCIS + is_eth_or_wifi = self.check_pics('MCORE.COM.WIFI') or self.check_pics('MCORE.COM.ETH') + if is_eth_or_wifi: + asserts.assert_true(self.verify_hostname(hostname=server, char_length=12), + f"Hostname for '{server}' is not a 12-character uppercase hexadecimal string") + else: + is_thr = self.check_pics('MCORE.COM.THR') + if is_thr: + asserts.assert_true(self.verify_hostname(hostname=server, char_length=16), + f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string") + # ICD TXT KEY if supports_lit: logging.info("supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII).") From 86e49ada54541f66c879d950f8aba19122ed0729 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 00:15:36 -0700 Subject: [PATCH 47/75] Updates contains_ipv6_address --- src/python_testing/TC_SC_4_3.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 66b3d9c59afac8..5296297374b74d 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -157,8 +157,7 @@ def contains_ipv6_address(addresses): return True, "At least one IPv6 address is present." except ipaddress.AddressValueError: # If an AddressValueError is raised, the current address is not a valid IPv6 address. - # The loop will continue to the next address. - continue + return False, f"Invalid address encountered: {address}" return False, "No IPv6 addresses found." @staticmethod @@ -287,7 +286,7 @@ async def test_TC_SC_4_3(self): # is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) self.step(9) - # Check MCORE.COM PCIS + # Check MCORE.COM PICS is_eth_or_wifi = self.check_pics('MCORE.COM.WIFI') or self.check_pics('MCORE.COM.ETH') if is_eth_or_wifi: asserts.assert_true(self.verify_hostname(hostname=server, char_length=12), From 0a51fb5cc72bb0b89796abdae3fdbad2ce5d8304 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 00:24:29 -0700 Subject: [PATCH 48/75] Removes listener dealy --- src/python_testing/mdns_discovery/mdns_discovery.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 8c96bf5fea0140..14c102d7d0413a 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -88,7 +88,6 @@ def __init__(self): self.updated_event = asyncio.Event() def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: - sleep(0.5) self.updated_event.set() def remove_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: From 3a6840d63a0b87d8464a882446c7776af84ea44e Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 00:25:48 -0700 Subject: [PATCH 49/75] Fix restyled --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 5296297374b74d..3401ffa2f9a029 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -294,7 +294,7 @@ async def test_TC_SC_4_3(self): else: is_thr = self.check_pics('MCORE.COM.THR') if is_thr: - asserts.assert_true(self.verify_hostname(hostname=server, char_length=16), + asserts.assert_true(self.verify_hostname(hostname=server, char_length=16), f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string") # ICD TXT KEY From b6b1f0da97b17d9ec3bad09099f5ca16d9c3cbc7 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 00:27:30 -0700 Subject: [PATCH 50/75] Fix restyled --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 3401ffa2f9a029..b3c3404a41d145 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -295,7 +295,7 @@ async def test_TC_SC_4_3(self): is_thr = self.check_pics('MCORE.COM.THR') if is_thr: asserts.assert_true(self.verify_hostname(hostname=server, char_length=16), - f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string") + f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string") # ICD TXT KEY if supports_lit: From 32cb3d7a5327c9d7f2f7d9337f5d074033bda8dd Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 00:42:47 -0700 Subject: [PATCH 51/75] Fix lint --- src/python_testing/mdns_discovery/mdns_discovery.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 14c102d7d0413a..bf0e87c01e79b8 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -19,7 +19,6 @@ import json from dataclasses import asdict, dataclass from enum import Enum -from time import sleep from typing import Dict, List, Optional, Union, cast from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo From 2915ef77ec73389a8457e51117520089ef470740 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 14:19:01 -0700 Subject: [PATCH 52/75] Updates ipv6 check --- src/python_testing/TC_SC_4_3.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index b3c3404a41d145..3b478eade5e0da 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -157,7 +157,7 @@ def contains_ipv6_address(addresses): return True, "At least one IPv6 address is present." except ipaddress.AddressValueError: # If an AddressValueError is raised, the current address is not a valid IPv6 address. - return False, f"Invalid address encountered: {address}" + return False, f"Invalid IPv6 address encountered: {address}, provided addresses: {addresses}" return False, "No IPv6 addresses found." @staticmethod @@ -364,7 +364,7 @@ async def test_TC_SC_4_3(self): # AAAA logging.info("Verify the AAAA record contains at least one IPv6 address") - result, message = self.contains_ipv6_address(operational_record.addresses) + result, message = self.contains_ipv6_address(quada_record.addresses) asserts.assert_true(result, message) # # *** STEP 10 *** From 2b7adc81433079ae77288b4add751ad86ac31fbe Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 24 Jul 2024 17:50:37 -0700 Subject: [PATCH 53/75] Fixes ipv6 checks --- src/python_testing/TC_SC_4_3.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 3b478eade5e0da..07a4c715e66b46 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -149,7 +149,10 @@ def verify_t_value(self, t_value): return False, f"T value ({t_value}) is not a valid integer" @staticmethod - def contains_ipv6_address(addresses): + def is_ipv6_address(addresses): + if isinstance(addresses, str): + addresses = [addresses] + for address in addresses: try: # Attempt to create an IPv6 address object. If successful, this is an IPv6 address. @@ -160,6 +163,11 @@ def contains_ipv6_address(addresses): return False, f"Invalid IPv6 address encountered: {address}, provided addresses: {addresses}" return False, "No IPv6 addresses found." + @staticmethod + def extract_ipv6_address(text): + items = text.split(',') + return items[-1] + @staticmethod def verify_hostname(hostname: str, char_length: int) -> bool: # Remove '.local' or '.local.' suffix if present @@ -364,7 +372,8 @@ async def test_TC_SC_4_3(self): # AAAA logging.info("Verify the AAAA record contains at least one IPv6 address") - result, message = self.contains_ipv6_address(quada_record.addresses) + ipv6_address = self.extract_ipv6_address(str(quada_record)) + result, message = self.is_ipv6_address(ipv6_address) asserts.assert_true(result, message) # # *** STEP 10 *** From 1c6d562c340aa1f8d631fb485cca410ae7e0eec8 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Thu, 25 Jul 2024 08:15:57 -0700 Subject: [PATCH 54/75] Restore ms delay --- src/python_testing/mdns_discovery/mdns_discovery.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index bf0e87c01e79b8..670b7a7f405140 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -19,6 +19,7 @@ import json from dataclasses import asdict, dataclass from enum import Enum +from time import sleep from typing import Dict, List, Optional, Union, cast from mdns_discovery.mdns_async_service_info import DNSRecordType, MdnsAsyncServiceInfo @@ -87,6 +88,7 @@ def __init__(self): self.updated_event = asyncio.Event() def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: + sleep(0.25) self.updated_event.set() def remove_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: From 0d543c109d92ef32bed4b5da09dff2478bed2366 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 1 Oct 2024 21:41:44 -0700 Subject: [PATCH 55/75] continue --- src/python_testing/TC_SC_4_3.py | 19 +- src/python_testing/any_test.py | 299 ++++++++++++++++++++++++++++++++ 2 files changed, 314 insertions(+), 4 deletions(-) create mode 100644 src/python_testing/any_test.py diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 07a4c715e66b46..1172d46dea23d4 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -295,15 +295,26 @@ async def test_TC_SC_4_3(self): self.step(9) # Check MCORE.COM PICS - is_eth_or_wifi = self.check_pics('MCORE.COM.WIFI') or self.check_pics('MCORE.COM.ETH') + mc_wifi = 'MCORE.COM.WIFI' + mc_eth = 'MCORE.COM.ETH' + mc_thr = 'MCORE.COM.THR' + + +## wildcard read of cnet clusters, featuremaps all endpoints, does it support wifi/thread? + + is_mc_wifi = self.check_pics(mc_wifi) + is_mc_eth = self.check_pics(mc_eth) + is_thr = self.check_pics(mc_thr) + is_eth_or_wifi = is_mc_wifi or is_mc_eth + if is_eth_or_wifi: + mcore_com = mc_wifi if is_mc_wifi else mc_eth if is_mc_eth else None asserts.assert_true(self.verify_hostname(hostname=server, char_length=12), - f"Hostname for '{server}' is not a 12-character uppercase hexadecimal string") + f"Hostname for '{server}' is not a 12-character uppercase hexadecimal string for PICS {mcore_com}") else: - is_thr = self.check_pics('MCORE.COM.THR') if is_thr: asserts.assert_true(self.verify_hostname(hostname=server, char_length=16), - f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string") + f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string for PICS {mc_thr}") # ICD TXT KEY if supports_lit: diff --git a/src/python_testing/any_test.py b/src/python_testing/any_test.py new file mode 100644 index 00000000000000..b535340c15f345 --- /dev/null +++ b/src/python_testing/any_test.py @@ -0,0 +1,299 @@ +# +# Copyright (c) 2023 Project CHIP Authors +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. +# +# === BEGIN CI TEST ARGUMENTS === +# test-runner-runs: run1 +# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} +# test-runner-run/run1/factoryreset: True +# test-runner-run/run1/quiet: True +# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto +# === END CI TEST ARGUMENTS === + +import copy +import logging +import time + +import chip.clusters as Clusters +from chip.ChipDeviceCtrl import ChipDeviceController +from chip.clusters import ClusterObjects as ClusterObjects +from chip.clusters.Attribute import AttributePath, TypedAttributePath, AsyncReadTransaction +from chip.exceptions import ChipStackError +from chip.interaction_model import Status +from matter_testing_support import AttributeChangeCallback, MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from mobly import asserts + +from chip.clusters import Attribute +from global_attribute_ids import GlobalAttributeIds + + +import chip.clusters as Clusters +import chip.logging +import chip.native +from chip import discovery +from chip.ChipStack import ChipStack +from chip.clusters import Attribute +from chip.clusters import ClusterObjects as ClusterObjects +from chip.clusters.Attribute import EventReadResult, SubscriptionTransaction, TypedAttributePath +from chip.exceptions import ChipStackError +from chip.interaction_model import InteractionModelError, Status +from chip.setup_payload import SetupPayload +from chip.storage import PersistentStorage +from chip.tracing import TracingContext +from global_attribute_ids import GlobalAttributeIds +from mobly import asserts, base_test, signals, utils +from mobly.config_parser import ENV_MOBLY_LOGPATH, TestRunConfig +from mobly.test_runner import TestRunner +from pics_support import read_pics_from_file + + +from chip import ChipDeviceCtrl # Needed before chip.FabricAdmin +import chip.FabricAdmin # Needed before chip.CertificateAuthority +import chip.CertificateAuthority +from chip.ChipDeviceCtrl import CommissioningParameters + +import pprint + +''' +Category: +Functional + +Description: +Validates Interaction Data Model (IDM), specifically subscription responses. Some example of tests run: + - Subscriptions with varying MaxIntervalCeiling + - Checks for `InvalidAction` results when subscribing to clusters and attributes without access rights + - Checks that subscription is not established for invalid MinIntervalFloor + - Validates that only correctly filtered data is received when a subscription is established + +Full test plan link for details: +https://github.com/CHIP-Specifications/chip-test-plans/blob/master/src/interactiondatamodel.adoc#tc-idm-4-2-subscription-response-messages-from-dut-test-cases-dut_server +''' + + +class any_test(MatterBaseTest): + + def stringify_keys(self, d): + """Recursively converts keys in the dictionary to string format.""" + if isinstance(d, dict): + return {str(key): self.stringify_keys(value) for key, value in d.items()} + elif isinstance(d, list): + return [self.stringify_keys(item) for item in d] + else: + return d + + def pretty_print_unconventional_json(self, data): + """Pretty prints the unconventional JSON-like structure.""" + processed_data = self.stringify_keys(data) + print('\n\n\n') + pprint.pprint(processed_data, indent=64, width=100) + print('\n\n\n') + + def steps_any_test(self): + return [TestStep(0, "Some action", "Some check") ] + + ROOT_NODE_ENDPOINT_ID = 0 + + async def get_descriptor_server_list(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): + return await self.read_single_attribute_check_success( + endpoint=ep, + dev_ctrl=ctrl, + cluster=Clusters.Descriptor, + attribute=Clusters.Descriptor.Attributes.ServerList + ) + + async def get_descriptor_parts_list(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): + return await self.read_single_attribute_check_success( + endpoint=ep, + dev_ctrl=ctrl, + cluster=Clusters.Descriptor, + attribute=Clusters.Descriptor.Attributes.PartsList + ) + + async def get_idle_mode_duration_sec(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): + return await self.read_single_attribute_check_success( + endpoint=ep, + dev_ctrl=ctrl, + cluster=Clusters.IcdManagement, + attribute=Clusters.IcdManagement.Attributes.IdleModeDuration + ) + + @staticmethod + def verify_attribute_exists(sub, cluster, attribute, ep=ROOT_NODE_ENDPOINT_ID): + sub_attrs = sub + if isinstance(sub, Clusters.Attribute.SubscriptionTransaction): + sub_attrs = sub.GetAttributes() + + asserts.assert_true(ep in sub_attrs, "Must have read endpoint %s data" % ep) + asserts.assert_true(cluster in sub_attrs[ep], "Must have read %s cluster data" % cluster.__name__) + asserts.assert_true(attribute in sub_attrs[ep][cluster], + "Must have read back attribute %s" % attribute.__name__) + + @staticmethod + def get_typed_attribute_path(attribute, ep=ROOT_NODE_ENDPOINT_ID): + return TypedAttributePath( + Path=AttributePath.from_attribute( + EndpointId=ep, + Attribute=attribute + ) + ) + + async def write_dut_acl(self, ctrl, acl, ep=ROOT_NODE_ENDPOINT_ID): + result = await ctrl.WriteAttribute(self.dut_node_id, [(ep, Clusters.AccessControl.Attributes.Acl(acl))]) + asserts.assert_equal(result[ep].Status, Status.Success, "ACL write failed") + + async def get_dut_acl(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): + sub = await ctrl.ReadAttribute( + nodeid=self.dut_node_id, + attributes=[(ep, Clusters.AccessControl.Attributes.Acl)], + keepSubscriptions=False, + fabricFiltered=True + ) + + acl_list = sub[ep][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl] + + return acl_list + + async def add_ace_to_dut_acl(self, ctrl, ace, dut_acl_original): + dut_acl = copy.deepcopy(dut_acl_original) + dut_acl.append(ace) + await self.write_dut_acl(ctrl=ctrl, acl=dut_acl) + + @staticmethod + def is_valid_uint32_value(var): + return isinstance(var, int) and 0 <= var <= 0xFFFFFFFF + + @staticmethod + def is_valid_uint16_value(var): + return isinstance(var, int) and 0 <= var <= 0xFFFF + + @async_test_body + async def test_any_test(self): + + # Test setup + cluster_rev_attr = Clusters.BasicInformation.Attributes.ClusterRevision + cluster_rev_attr_typed_path = self.get_typed_attribute_path(cluster_rev_attr) + node_label_attr = Clusters.BasicInformation.Attributes.NodeLabel + node_label_attr_path = [(0, node_label_attr)] + subscription_max_interval_publisher_limit_sec = 0 + INVALID_ACTION_ERROR_CODE = 0x580 + + # Controller 1 setup + # Subscriber/client with admin access to the DUT + # Will write ACL for controller 2 and validate success/error codes + CR1: ChipDeviceController = self.default_controller + + # Original DUT ACL used for reseting the ACL on some steps + dut_acl_original = await self.get_dut_acl(CR1) + + # Controller 2 setup + # Subscriber/client with limited access to the DUT + # Will validate error status codes + fabric_admin = self.certificate_authority_manager.activeCaList[0].adminList[0] + CR2_nodeid = self.matter_test_config.controller_node_id + 1 + CR2: ChipDeviceController = fabric_admin.NewController( + nodeId=CR2_nodeid, + paaTrustStorePath=str(self.matter_test_config.paa_trust_store_path), + ) + + # *** Step 0 *** + # CR1 reads the ServerList attribute from the Descriptor cluster on EP0. If the ICDManagement cluster ID + # (70,0x46) is present, set SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC = IdleModeDuration and + # min_interval_floor_s to 0, otherwise, set SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC = 60 mins and + # min_interval_floor_s to 3. + self.step(0) + + + + + + + + + + + + + + + + + + + + + attributes = [ + # (Clusters.Descriptor), + # (Clusters.NetworkCommissioning.Attributes.FeatureMap), + (Clusters.NetworkCommissioning), + # Attribute.AttributePath(None, None, GlobalAttributeIds.ATTRIBUTE_LIST_ID), + # Attribute.AttributePath(None, None, GlobalAttributeIds.FEATURE_MAP_ID), + # Attribute.AttributePath(None, None, GlobalAttributeIds.ACCEPTED_COMMAND_LIST_ID), + ] + + wildcard: AsyncReadTransaction.ReadResponse = await CR1.Read( + nodeid=self.dut_node_id, + attributes=attributes + ) + + maps = str(wildcard.attributes.keys().mapping) + self.pretty_print_unconventional_json(maps) + + + + + + + + + + + + + + + + + + + # # Reads the ServerList attribute + # ep0_servers = await self.get_descriptor_server_list(CR1) + + # # Check if ep0_servers contains the ICD Management cluster ID (0x0046) + # if Clusters.IcdManagement.id in ep0_servers: + # # Read the IdleModeDuration attribute value from the DUT + # logging.info( + # "CR1 reads from the DUT the IdleModeDuration attribute and sets SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC = IdleModeDuration") + + # idleModeDuration = await self.get_idle_mode_duration_sec(CR1) + # subscription_max_interval_publisher_limit_sec = idleModeDuration + # min_interval_floor_sec = 0 + # else: + # # Defaulting SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC to 60 minutes + # subscription_max_interval_publisher_limit_sec = 60 * 60 + # min_interval_floor_sec = 3 + + # asserts.assert_greater_equal(subscription_max_interval_publisher_limit_sec, 1, + # "SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC must be at least 1") + + # logging.info( + # f"Set SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC to {subscription_max_interval_publisher_limit_sec} seconds") + +if __name__ == "__main__": + default_matter_test_main() From 20b726d99821067433f150a6f4df579cfb723e73 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Sat, 5 Oct 2024 00:24:43 -0700 Subject: [PATCH 56/75] Step 9 - Updates hostname character length check, other adjustments --- src/python_testing/TC_SC_4_3.py | 71 ++++++++++++--------------------- 1 file changed, 26 insertions(+), 45 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 1172d46dea23d4..3e29ee1541ab12 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -64,7 +64,7 @@ def steps_TC_SC_4_3(self): TestStep(8, "TH performs a query for the AAAA record against the target listed in the SRV record", "Verify AAAA record is returned"), TestStep(9, "TH verifies the following from the returned records:", - "Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a 12-character uppercase hexadecimal string. • If (MCORE.COM.THR) target, the hostname must be a 16-character hex string using capital letters. ICD TXT key: • If supports_lit is false, verify that the ICD key is NOT present in the TXT record • If supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII) SII TXT key: • If supports_icd is true and supports_lit is false, set sit_mode to true • If supports_icd is true and supports_lit is true, set sit_mode to true if ICD=0 otherwise set sit_mode to false • If supports_icd is false, set sit_mode to false • If sit_mode is true, verify that the SII key IS present in the TXT record • if the SII key is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) SAI TXT key: • if supports_icd is true, verify that the SAI key is present in the TXT record • If the SAI key is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms)"), + "TH verifies the following from the returned records: The hostname must be a fixed-length twelve-character (or sixteen-character) hexadecimal string, encoded as ASCII (UTF-8) text using capital letters.. ICD TXT key: • If supports_lit is false, verify that the ICD key is NOT present in the TXT record • If supports_lit is true, verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII) SII TXT key: • If supports_icd is true and supports_lit is false, set sit_mode to true • If supports_icd is true and supports_lit is true, set sit_mode to true if ICD=0 otherwise set sit_mode to false • If supports_icd is false, set sit_mode to false • If sit_mode is true, verify that the SII key IS present in the TXT record • if the SII key is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) SAI TXT key: • if supports_icd is true, verify that the SAI key is present in the TXT record • If the SAI key is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms)"), TestStep(10, "TH performs a DNS-SD browse for _I._sub._matter._tcp.local, where is the 64-bit compressed Fabric identifier, expressed as a fixed-length, sixteencharacter hexadecimal string, encoded as ASCII (UTF-8) text using capital letters.", "Verify DUT returns a PTR record with DNS-SD instance name set to instance_name"), TestStep(11, "TH performs a DNS-SD browse for _matter._tcp.local", @@ -169,15 +169,15 @@ def extract_ipv6_address(text): return items[-1] @staticmethod - def verify_hostname(hostname: str, char_length: int) -> bool: + def verify_hostname(hostname: str) -> bool: # Remove '.local' or '.local.' suffix if present if hostname.endswith('.local'): hostname = hostname[:-6] elif hostname.endswith('.local.'): hostname = hostname[:-7] - # Regular expression to match an uppercase hexadecimal string of the specified length - pattern = re.compile(rf'^[0-9A-F]{{{char_length}}}$') + # Regular expression to match an uppercase hexadecimal string of 12 or 16 characters + pattern = re.compile(r'^[0-9A-F]{12}$|^[0-9A-F]{16}$') return bool(pattern.match(hostname)) @async_test_body @@ -186,8 +186,6 @@ async def test_TC_SC_4_3(self): supports_lit = None active_mode_threshold_ms = None instance_name = None - # icd_value = None - # sit_mode = None # *** STEP 1 *** # DUT is commissioned on the same fabric as TH. @@ -243,7 +241,7 @@ async def test_TC_SC_4_3(self): # Will be used in Step 8 and 11 # This is the hostname - server = operational_record.server + hostname = operational_record.server # Verify SRV record is returned srv_record_returned = operational_record is not None and operational_record.service_name == instance_qname @@ -270,51 +268,33 @@ async def test_TC_SC_4_3(self): self.step(8) quada_record = await mdns.get_service_by_record_type( - service_name=server, + service_name=hostname, record_type=DNSRecordType.AAAA, log_output=True ) answer_record_type = quada_record.get_type(quada_record.type) - quada = _TYPES[_TYPE_AAAA] + quada_record_type = _TYPES[_TYPE_AAAA] # Verify AAAA record is returned - asserts.assert_equal(server, quada_record.name, f"Server name mismatch: {server} vs {quada_record.name}") - asserts.assert_equal(quada, answer_record_type, f"Record type should be {quada} but got {answer_record_type}") + asserts.assert_equal(hostname, quada_record.name, f"Server name mismatch: {hostname} vs {quada_record.name}") + asserts.assert_equal(quada_record_type, answer_record_type, f"Record type should be {quada_record_type} but got {answer_record_type}") # # *** STEP 9 *** - # TH verifies the following from the returned records: Hostname: • If (MCORE.COM.WIFI OR MCORE.COM.ETH) target, the hostname must be a - # 12-character uppercase hexadecimal string. • If (MCORE.COM.THR) target, the hostname must be a 16-character hex string using capital - # letters. ICD TXT key: • If supports_lit is false, verify that the ICD key is NOT present in the TXT record • If supports_lit is true, - # verify the ICD key IS present in the TXT record, and it has the value of 0 or 1 (ASCII) SII TXT key: • If supports_icd is true and - # supports_lit is false, set sit_mode to true • If supports_icd is true and supports_lit is true, set sit_mode to true if ICD=0 - # otherwise set sit_mode to false • If supports_icd is false, set sit_mode to false • If sit_mode is true, verify that the SII key IS - # present in the TXT record • if the SII key is present, verify it is a decimal value with no leading zeros and is less than or equal - # to 3600000 (1h in ms) SAI TXT key: • if supports_icd is true, verify that the SAI key is present in the TXT record • If the SAI key - # is present, verify it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) + # TH verifies the following from the returned records: The hostname must be a fixed-length twelve-character (or sixteen-character) + # hexadecimal string, encoded as ASCII (UTF-8) text using capital letters.. ICD TXT key: • If supports_lit is false, verify that the + # ICD key is NOT present in the TXT record • If supports_lit is true, verify the ICD key IS present in the TXT record, and it has the + # value of 0 or 1 (ASCII) SII TXT key: • If supports_icd is true and supports_lit is false, set sit_mode to true • If supports_icd is + # true and supports_lit is true, set sit_mode to true if ICD=0 otherwise set sit_mode to false • If supports_icd is false, set + # sit_mode to false • If sit_mode is true, verify that the SII key IS present in the TXT record • if the SII key is present, verify + # it is a decimal value with no leading zeros and is less than or equal to 3600000 (1h in ms) SAI TXT key: • if supports_icd is true, + # verify that the SAI key is present in the TXT record • If the SAI key is present, verify it is a decimal value with no leading + # zeros and is less than or equal to 3600000 (1h in ms) self.step(9) - # Check MCORE.COM PICS - mc_wifi = 'MCORE.COM.WIFI' - mc_eth = 'MCORE.COM.ETH' - mc_thr = 'MCORE.COM.THR' - - -## wildcard read of cnet clusters, featuremaps all endpoints, does it support wifi/thread? - - is_mc_wifi = self.check_pics(mc_wifi) - is_mc_eth = self.check_pics(mc_eth) - is_thr = self.check_pics(mc_thr) - is_eth_or_wifi = is_mc_wifi or is_mc_eth - - if is_eth_or_wifi: - mcore_com = mc_wifi if is_mc_wifi else mc_eth if is_mc_eth else None - asserts.assert_true(self.verify_hostname(hostname=server, char_length=12), - f"Hostname for '{server}' is not a 12-character uppercase hexadecimal string for PICS {mcore_com}") - else: - if is_thr: - asserts.assert_true(self.verify_hostname(hostname=server, char_length=16), - f"Hostname for '{server}' is not a 16-character uppercase hexadecimal string for PICS {mc_thr}") + # Verify hostname character length (12 or 16) + asserts.assert_true(self.verify_hostname(hostname=hostname), + f"Hostname for '{hostname}' is not a 12 or 16 character uppercase hexadecimal string") # ICD TXT KEY if supports_lit: @@ -388,12 +368,13 @@ async def test_TC_SC_4_3(self): asserts.assert_true(result, message) # # *** STEP 10 *** - # TH performs a DNS-SD browse for _I._sub._matter._tcp.local, where is the 64-bit compressed Fabric identifier, expressed as a fixed-length, sixteencharacter hexadecimal string, encoded as - # ASCII (UTF-8) text using capital letters. Verify DUT returns a PTR record with DNS-SD instance name set to instance_name + # TH performs a DNS-SD browse for _I._sub._matter._tcp.local, where is the 64-bit compressed + # Fabric identifier, expressed as a fixed-length, sixteencharacter hexadecimal string, encoded as ASCII (UTF-8) + # text using capital letters. Verify DUT returns a PTR record with DNS-SD instance name set to instance_name self.step(10) service_types = await mdns.get_service_types(log_output=True) op_sub_type = self.get_operational_subtype() - asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}'") + asserts.assert_in(op_sub_type, service_types, f"No PTR record with DNS-SD instance name '{op_sub_type}' wsa found.") # # *** STEP 11 *** # TH performs a DNS-SD browse for _matter._tcp.local @@ -406,7 +387,7 @@ async def test_TC_SC_4_3(self): ) # Verify DUT returns a PTR record with DNS-SD instance name set instance_name - asserts.assert_equal(op_service_info.server, server, + asserts.assert_equal(op_service_info.server, hostname, f"No PTR record with DNS-SD instance name '{MdnsServiceType.OPERATIONAL.value}'") asserts.assert_equal(instance_name, op_service_info.instance_name, "Instance name mismatch") From 8b43cfb51a2b30d149156d80c1ecf12175f4fa01 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Sat, 5 Oct 2024 00:36:45 -0700 Subject: [PATCH 57/75] removes temp test file --- src/python_testing/any_test.py | 299 --------------------------------- 1 file changed, 299 deletions(-) delete mode 100644 src/python_testing/any_test.py diff --git a/src/python_testing/any_test.py b/src/python_testing/any_test.py deleted file mode 100644 index b535340c15f345..00000000000000 --- a/src/python_testing/any_test.py +++ /dev/null @@ -1,299 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments -# for details about the block below. -# -# === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${ALL_CLUSTERS_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto -# === END CI TEST ARGUMENTS === - -import copy -import logging -import time - -import chip.clusters as Clusters -from chip.ChipDeviceCtrl import ChipDeviceController -from chip.clusters import ClusterObjects as ClusterObjects -from chip.clusters.Attribute import AttributePath, TypedAttributePath, AsyncReadTransaction -from chip.exceptions import ChipStackError -from chip.interaction_model import Status -from matter_testing_support import AttributeChangeCallback, MatterBaseTest, TestStep, async_test_body, default_matter_test_main -from mobly import asserts - -from chip.clusters import Attribute -from global_attribute_ids import GlobalAttributeIds - - -import chip.clusters as Clusters -import chip.logging -import chip.native -from chip import discovery -from chip.ChipStack import ChipStack -from chip.clusters import Attribute -from chip.clusters import ClusterObjects as ClusterObjects -from chip.clusters.Attribute import EventReadResult, SubscriptionTransaction, TypedAttributePath -from chip.exceptions import ChipStackError -from chip.interaction_model import InteractionModelError, Status -from chip.setup_payload import SetupPayload -from chip.storage import PersistentStorage -from chip.tracing import TracingContext -from global_attribute_ids import GlobalAttributeIds -from mobly import asserts, base_test, signals, utils -from mobly.config_parser import ENV_MOBLY_LOGPATH, TestRunConfig -from mobly.test_runner import TestRunner -from pics_support import read_pics_from_file - - -from chip import ChipDeviceCtrl # Needed before chip.FabricAdmin -import chip.FabricAdmin # Needed before chip.CertificateAuthority -import chip.CertificateAuthority -from chip.ChipDeviceCtrl import CommissioningParameters - -import pprint - -''' -Category: -Functional - -Description: -Validates Interaction Data Model (IDM), specifically subscription responses. Some example of tests run: - - Subscriptions with varying MaxIntervalCeiling - - Checks for `InvalidAction` results when subscribing to clusters and attributes without access rights - - Checks that subscription is not established for invalid MinIntervalFloor - - Validates that only correctly filtered data is received when a subscription is established - -Full test plan link for details: -https://github.com/CHIP-Specifications/chip-test-plans/blob/master/src/interactiondatamodel.adoc#tc-idm-4-2-subscription-response-messages-from-dut-test-cases-dut_server -''' - - -class any_test(MatterBaseTest): - - def stringify_keys(self, d): - """Recursively converts keys in the dictionary to string format.""" - if isinstance(d, dict): - return {str(key): self.stringify_keys(value) for key, value in d.items()} - elif isinstance(d, list): - return [self.stringify_keys(item) for item in d] - else: - return d - - def pretty_print_unconventional_json(self, data): - """Pretty prints the unconventional JSON-like structure.""" - processed_data = self.stringify_keys(data) - print('\n\n\n') - pprint.pprint(processed_data, indent=64, width=100) - print('\n\n\n') - - def steps_any_test(self): - return [TestStep(0, "Some action", "Some check") ] - - ROOT_NODE_ENDPOINT_ID = 0 - - async def get_descriptor_server_list(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): - return await self.read_single_attribute_check_success( - endpoint=ep, - dev_ctrl=ctrl, - cluster=Clusters.Descriptor, - attribute=Clusters.Descriptor.Attributes.ServerList - ) - - async def get_descriptor_parts_list(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): - return await self.read_single_attribute_check_success( - endpoint=ep, - dev_ctrl=ctrl, - cluster=Clusters.Descriptor, - attribute=Clusters.Descriptor.Attributes.PartsList - ) - - async def get_idle_mode_duration_sec(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): - return await self.read_single_attribute_check_success( - endpoint=ep, - dev_ctrl=ctrl, - cluster=Clusters.IcdManagement, - attribute=Clusters.IcdManagement.Attributes.IdleModeDuration - ) - - @staticmethod - def verify_attribute_exists(sub, cluster, attribute, ep=ROOT_NODE_ENDPOINT_ID): - sub_attrs = sub - if isinstance(sub, Clusters.Attribute.SubscriptionTransaction): - sub_attrs = sub.GetAttributes() - - asserts.assert_true(ep in sub_attrs, "Must have read endpoint %s data" % ep) - asserts.assert_true(cluster in sub_attrs[ep], "Must have read %s cluster data" % cluster.__name__) - asserts.assert_true(attribute in sub_attrs[ep][cluster], - "Must have read back attribute %s" % attribute.__name__) - - @staticmethod - def get_typed_attribute_path(attribute, ep=ROOT_NODE_ENDPOINT_ID): - return TypedAttributePath( - Path=AttributePath.from_attribute( - EndpointId=ep, - Attribute=attribute - ) - ) - - async def write_dut_acl(self, ctrl, acl, ep=ROOT_NODE_ENDPOINT_ID): - result = await ctrl.WriteAttribute(self.dut_node_id, [(ep, Clusters.AccessControl.Attributes.Acl(acl))]) - asserts.assert_equal(result[ep].Status, Status.Success, "ACL write failed") - - async def get_dut_acl(self, ctrl, ep=ROOT_NODE_ENDPOINT_ID): - sub = await ctrl.ReadAttribute( - nodeid=self.dut_node_id, - attributes=[(ep, Clusters.AccessControl.Attributes.Acl)], - keepSubscriptions=False, - fabricFiltered=True - ) - - acl_list = sub[ep][Clusters.AccessControl][Clusters.AccessControl.Attributes.Acl] - - return acl_list - - async def add_ace_to_dut_acl(self, ctrl, ace, dut_acl_original): - dut_acl = copy.deepcopy(dut_acl_original) - dut_acl.append(ace) - await self.write_dut_acl(ctrl=ctrl, acl=dut_acl) - - @staticmethod - def is_valid_uint32_value(var): - return isinstance(var, int) and 0 <= var <= 0xFFFFFFFF - - @staticmethod - def is_valid_uint16_value(var): - return isinstance(var, int) and 0 <= var <= 0xFFFF - - @async_test_body - async def test_any_test(self): - - # Test setup - cluster_rev_attr = Clusters.BasicInformation.Attributes.ClusterRevision - cluster_rev_attr_typed_path = self.get_typed_attribute_path(cluster_rev_attr) - node_label_attr = Clusters.BasicInformation.Attributes.NodeLabel - node_label_attr_path = [(0, node_label_attr)] - subscription_max_interval_publisher_limit_sec = 0 - INVALID_ACTION_ERROR_CODE = 0x580 - - # Controller 1 setup - # Subscriber/client with admin access to the DUT - # Will write ACL for controller 2 and validate success/error codes - CR1: ChipDeviceController = self.default_controller - - # Original DUT ACL used for reseting the ACL on some steps - dut_acl_original = await self.get_dut_acl(CR1) - - # Controller 2 setup - # Subscriber/client with limited access to the DUT - # Will validate error status codes - fabric_admin = self.certificate_authority_manager.activeCaList[0].adminList[0] - CR2_nodeid = self.matter_test_config.controller_node_id + 1 - CR2: ChipDeviceController = fabric_admin.NewController( - nodeId=CR2_nodeid, - paaTrustStorePath=str(self.matter_test_config.paa_trust_store_path), - ) - - # *** Step 0 *** - # CR1 reads the ServerList attribute from the Descriptor cluster on EP0. If the ICDManagement cluster ID - # (70,0x46) is present, set SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC = IdleModeDuration and - # min_interval_floor_s to 0, otherwise, set SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC = 60 mins and - # min_interval_floor_s to 3. - self.step(0) - - - - - - - - - - - - - - - - - - - - - attributes = [ - # (Clusters.Descriptor), - # (Clusters.NetworkCommissioning.Attributes.FeatureMap), - (Clusters.NetworkCommissioning), - # Attribute.AttributePath(None, None, GlobalAttributeIds.ATTRIBUTE_LIST_ID), - # Attribute.AttributePath(None, None, GlobalAttributeIds.FEATURE_MAP_ID), - # Attribute.AttributePath(None, None, GlobalAttributeIds.ACCEPTED_COMMAND_LIST_ID), - ] - - wildcard: AsyncReadTransaction.ReadResponse = await CR1.Read( - nodeid=self.dut_node_id, - attributes=attributes - ) - - maps = str(wildcard.attributes.keys().mapping) - self.pretty_print_unconventional_json(maps) - - - - - - - - - - - - - - - - - - - # # Reads the ServerList attribute - # ep0_servers = await self.get_descriptor_server_list(CR1) - - # # Check if ep0_servers contains the ICD Management cluster ID (0x0046) - # if Clusters.IcdManagement.id in ep0_servers: - # # Read the IdleModeDuration attribute value from the DUT - # logging.info( - # "CR1 reads from the DUT the IdleModeDuration attribute and sets SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC = IdleModeDuration") - - # idleModeDuration = await self.get_idle_mode_duration_sec(CR1) - # subscription_max_interval_publisher_limit_sec = idleModeDuration - # min_interval_floor_sec = 0 - # else: - # # Defaulting SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC to 60 minutes - # subscription_max_interval_publisher_limit_sec = 60 * 60 - # min_interval_floor_sec = 3 - - # asserts.assert_greater_equal(subscription_max_interval_publisher_limit_sec, 1, - # "SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC must be at least 1") - - # logging.info( - # f"Set SUBSCRIPTION_MAX_INTERVAL_PUBLISHER_LIMIT_SEC to {subscription_max_interval_publisher_limit_sec} seconds") - -if __name__ == "__main__": - default_matter_test_main() From dfdcd657dcb482b2c364b144513172b4260122d0 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Sat, 5 Oct 2024 07:37:11 +0000 Subject: [PATCH 58/75] Restyled by autopep8 --- src/python_testing/TC_SC_4_3.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 3e29ee1541ab12..83f9249acf2af6 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -278,7 +278,8 @@ async def test_TC_SC_4_3(self): # Verify AAAA record is returned asserts.assert_equal(hostname, quada_record.name, f"Server name mismatch: {hostname} vs {quada_record.name}") - asserts.assert_equal(quada_record_type, answer_record_type, f"Record type should be {quada_record_type} but got {answer_record_type}") + asserts.assert_equal(quada_record_type, answer_record_type, + f"Record type should be {quada_record_type} but got {answer_record_type}") # # *** STEP 9 *** # TH verifies the following from the returned records: The hostname must be a fixed-length twelve-character (or sixteen-character) @@ -294,7 +295,7 @@ async def test_TC_SC_4_3(self): # Verify hostname character length (12 or 16) asserts.assert_true(self.verify_hostname(hostname=hostname), - f"Hostname for '{hostname}' is not a 12 or 16 character uppercase hexadecimal string") + f"Hostname for '{hostname}' is not a 12 or 16 character uppercase hexadecimal string") # ICD TXT KEY if supports_lit: From 21748a70fb69706c4cc3d0fd2086db8dbb914db3 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 9 Oct 2024 13:28:41 -0700 Subject: [PATCH 59/75] Removes test case YAML and manualTests.json reference --- .../suites/certification/Test_TC_SC_4_3.yaml | 55 ------ src/app/tests/suites/manualTests.json | 160 ++++++++++++++---- 2 files changed, 123 insertions(+), 92 deletions(-) delete mode 100644 src/app/tests/suites/certification/Test_TC_SC_4_3.yaml diff --git a/src/app/tests/suites/certification/Test_TC_SC_4_3.yaml b/src/app/tests/suites/certification/Test_TC_SC_4_3.yaml deleted file mode 100644 index 8521cb24bc8daa..00000000000000 --- a/src/app/tests/suites/certification/Test_TC_SC_4_3.yaml +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2021 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# Auto-generated scripts for harness use only, please review before automation. The endpoints and cluster names are currently set to default - -name: 3.4.3. [TC-SC-4.3] Discovery [DUT as Commissionee] - -PICS: - - MCORE.ROLE.COMMISSIONEE - -config: - nodeId: 0x12344321 - cluster: "Basic Information" - endpoint: 0 - -tests: - - label: "Note" - verification: | - Chip-tool command used below are an example to verify the DUT as controller test cases. For certification test, we expect DUT should have a capability or way to run the equivalent command. - disabled: true - - - label: - "Step 1: DUT is commissioned to TH and DUT is instructed to advertise - its operational service (_matter._tcp)." - verification: | - 1. Provision the DUT by TH (Chip-tool) - disabled: true - - - label: "Step 2: Scan for DNS-SD advertising" - PICS: - MCORE.COM.WIFI && MCORE.COM.ETH && MCORE.COM.THR && MCORE.ICD && - MCORE.SC.SII_OP_DISCOVERY_KEY && MCORE.SC.SAI_OP_DISCOVERY_KEY && - MCORE.SC.SAT_OP_DISCOVERY_KEY && MCORE.SC.T_KEY - verification: | - avahi-browse -rt _matter._tcp - - Verify the device is advertising _matterc._udp service like below output in TH terminal Log: (Verify for the DUT's actual values (like vendor ID, PID ..etc) as mentioned in the expected outcome of the test plan, The below log contains the data from the reference raspi accessory) - - + veth721e1d9 IPv6 433B62F8F07F4327-0000000000000001 _matter._tcp local - = veth721e1d9 IPv6 433B62F8F07F4327-0000000000000001 _matter._tcp local - hostname = [E45F0149AE290000.local] - address = [fe80::28e0:95ff:fed9:3085] - port = [5540] - txt = ["T=1" "SAI=300" "SII=5000"] - disabled: true diff --git a/src/app/tests/suites/manualTests.json b/src/app/tests/suites/manualTests.json index 3b0b354840e1c6..66b39cd9d9819f 100644 --- a/src/app/tests/suites/manualTests.json +++ b/src/app/tests/suites/manualTests.json @@ -55,7 +55,12 @@ "Test_TC_BDX_2_4", "Test_TC_BDX_2_5" ], - "bridge": ["Test_TC_BR_1", "Test_TC_BR_2", "Test_TC_BR_3", "Test_TC_BR_4"], + "bridge": [ + "Test_TC_BR_1", + "Test_TC_BR_2", + "Test_TC_BR_3", + "Test_TC_BR_4" + ], "DeviceAttestation": [ "Test_TC_DA_1_1", "Test_TC_DA_1_3", @@ -110,13 +115,25 @@ "Test_TC_DLOG_2_2", "Test_TC_DLOG_3_1" ], - "Descriptor": ["Test_TC_DESC_2_1"], - "DeviceEnergyManagementMode": ["Test_TC_DEMM_1_2"], - "EnergyEVSEMode": ["Test_TC_EEVSEM_1_2"], + "Descriptor": [ + "Test_TC_DESC_2_1" + ], + "DeviceEnergyManagementMode": [ + "Test_TC_DEMM_1_2" + ], + "EnergyEVSEMode": [ + "Test_TC_EEVSEM_1_2" + ], "FanControl": [], - "GeneralCommissioning": ["Test_TC_CGEN_2_2"], - "GeneralDiagnostics": ["Test_TC_DGGEN_2_2"], - "Identify": ["Test_TC_I_3_2"], + "GeneralCommissioning": [ + "Test_TC_CGEN_2_2" + ], + "GeneralDiagnostics": [ + "Test_TC_DGGEN_2_2" + ], + "Identify": [ + "Test_TC_I_3_2" + ], "IcdManagement": [], "IlluminanceMeasurement": [], "InteractionDataModel": [ @@ -194,7 +211,11 @@ "Test_TC_CADMIN_1_25", "Test_TC_CADMIN_1_26" ], - "ModeSelect": ["Test_TC_MOD_1_2", "Test_TC_MOD_1_3", "Test_TC_MOD_2_2"], + "ModeSelect": [ + "Test_TC_MOD_1_2", + "Test_TC_MOD_1_3", + "Test_TC_MOD_2_2" + ], "OTASoftwareUpdate": [ "Test_TC_SU_1_1", "Test_TC_SU_2_1", @@ -212,7 +233,9 @@ "Test_TC_SU_4_1", "Test_TC_SU_4_2" ], - "PowerSourceConfiguration": ["Test_TC_PSCFG_2_2"], + "PowerSourceConfiguration": [ + "Test_TC_PSCFG_2_2" + ], "PressureMeasurement": [], "SecureChannel": [ "Test_TC_SC_1_1", @@ -229,7 +252,6 @@ "Test_TC_SC_3_4", "Test_TC_SC_4_1", "Test_TC_SC_4_2", - "Test_TC_SC_4_3", "Test_TC_SC_4_4", "Test_TC_SC_4_5", "Test_TC_SC_4_6", @@ -246,13 +268,25 @@ "Test_TC_DGSW_2_3" ], "EthernetNetworkDiagnostics": [], - "WiFiNetworkDiagnostics": ["Test_TC_DGWIFI_2_2"], + "WiFiNetworkDiagnostics": [ + "Test_TC_DGWIFI_2_2" + ], "WindowCovering": [], - "FlowMeasurement": ["Test_TC_FLW_2_2"], - "GroupKeyManagement": ["Test_TC_GRPKEY_5_4"], - "OccupancySensing": ["Test_TC_OCC_3_1"], - "PowerSource": ["Test_TC_PS_2_2"], - "BooleanState": ["Test_TC_BOOL_2_2"], + "FlowMeasurement": [ + "Test_TC_FLW_2_2" + ], + "GroupKeyManagement": [ + "Test_TC_GRPKEY_5_4" + ], + "OccupancySensing": [ + "Test_TC_OCC_3_1" + ], + "PowerSource": [ + "Test_TC_PS_2_2" + ], + "BooleanState": [ + "Test_TC_BOOL_2_2" + ], "ColorControl": [ "Test_TC_CC_3_1", "Test_TC_CC_7_1", @@ -260,34 +294,74 @@ "Test_TC_CC_9_2", "Test_TC_CC_9_3" ], - "DoorLock": ["Test_TC_DRLK_2_10", "Test_TC_DRLK_3_2"], - "DeviceEnergyManagement": ["Test_TC_DEM_1_1"], + "DoorLock": [ + "Test_TC_DRLK_2_10", + "Test_TC_DRLK_3_2" + ], + "DeviceEnergyManagement": [ + "Test_TC_DEM_1_1" + ], "LocalizationConfiguration": [], "LevelControl": [], - "LaundryWasherMode": ["Test_TC_LWM_1_2"], - "OnOff": ["Test_TC_OO_2_3"], - "RelativeHumidityMeasurement": ["Test_TC_RH_2_2"], + "LaundryWasherMode": [ + "Test_TC_LWM_1_2" + ], + "OnOff": [ + "Test_TC_OO_2_3" + ], + "RelativeHumidityMeasurement": [ + "Test_TC_RH_2_2" + ], "SmokeCOAlarm": [], - "RefrigeratorAlarm": ["Test_TC_REFALM_2_2", "Test_TC_REFALM_2_3"], - "RVCCleanMode": ["Test_TC_RVCCLEANM_3_3"], - "RVCOperationalState": ["Test_TC_RVCOPSTATE_2_2"], - "RVCRunMode": ["Test_TC_RVCRUNM_3_3"], + "RefrigeratorAlarm": [ + "Test_TC_REFALM_2_2", + "Test_TC_REFALM_2_3" + ], + "RVCCleanMode": [ + "Test_TC_RVCCLEANM_3_3" + ], + "RVCOperationalState": [ + "Test_TC_RVCOPSTATE_2_2" + ], + "RVCRunMode": [ + "Test_TC_RVCRUNM_3_3" + ], "TemperatureControlledCabinetMode": [ "Test_TC_TCCM_1_2", "Test_TC_TCCM_2_1" ], - "Switch": ["Test_TC_SWTCH_3_2"], + "Switch": [ + "Test_TC_SWTCH_3_2" + ], "TemperatureControl": [], - "TemperatureMeasurement": ["Test_TC_TMP_2_2"], - "Thermostat": ["Test_TC_TSTAT_3_2"], + "TemperatureMeasurement": [ + "Test_TC_TMP_2_2" + ], + "Thermostat": [ + "Test_TC_TSTAT_3_2" + ], "ThermostatUserConfiguration": [], - "ThreadNetworkDiagnostics": ["Test_TC_DGTHREAD_2_5"], - "Actions": ["Test_TC_ACT_2_1", "Test_TC_ACT_2_2", "Test_TC_ACT_3_2"], + "ThreadNetworkDiagnostics": [ + "Test_TC_DGTHREAD_2_5" + ], + "Actions": [ + "Test_TC_ACT_2_1", + "Test_TC_ACT_2_2", + "Test_TC_ACT_3_2" + ], "TimeFormatLocalization": [], "TimeSynchronization": [], "UnitLocalization": [], - "Binding": ["Test_TC_BIND_2_1", "Test_TC_BIND_2_2", "Test_TC_BIND_2_3"], - "ScenesManagement": ["Test_TC_S_2_5", "Test_TC_S_2_6", "Test_TC_S_3_1"], + "Binding": [ + "Test_TC_BIND_2_1", + "Test_TC_BIND_2_2", + "Test_TC_BIND_2_3" + ], + "ScenesManagement": [ + "Test_TC_S_2_5", + "Test_TC_S_2_6", + "Test_TC_S_3_1" + ], "PumpConfigurationControl": [], "AccessControl": [], "UserLabel": [], @@ -296,11 +370,23 @@ "Test_TC_BRBINFO_3_1" ], "LaundryWasherControl": [], - "OvenMode": ["Test_TC_OTCCM_1_2", "Test_TC_OTCCM_3_2", "Test_TC_OTCCM_3_3"], + "OvenMode": [ + "Test_TC_OTCCM_1_2", + "Test_TC_OTCCM_3_2", + "Test_TC_OTCCM_3_3" + ], "AccessControlEnforcement": [], - "OvenMode": ["Test_TC_OTCCM_1_1", "Test_TC_OTCCM_1_2"], - "EnergyEVSE": ["Test_TC_EEVSE_1_1", "Test_TC_EEVSE_2_1"], - "PowerTopology": ["Test_TC_PWRTL_1_1"], + "OvenMode": [ + "Test_TC_OTCCM_1_1", + "Test_TC_OTCCM_1_2" + ], + "EnergyEVSE": [ + "Test_TC_EEVSE_1_1", + "Test_TC_EEVSE_2_1" + ], + "PowerTopology": [ + "Test_TC_PWRTL_1_1" + ], "collection": [ "DeviceDiscovery", "Groups", @@ -375,4 +461,4 @@ "AccessControlEnforcement", "LaundryWasherControl" ] -} +} \ No newline at end of file From 10bea7815b60c0c460fcab00cdc066bb2309e660 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 9 Oct 2024 14:11:02 -0700 Subject: [PATCH 60/75] Fix restyle --- src/app/tests/suites/manualTests.json | 159 ++++++-------------------- 1 file changed, 36 insertions(+), 123 deletions(-) diff --git a/src/app/tests/suites/manualTests.json b/src/app/tests/suites/manualTests.json index 66b39cd9d9819f..49a10b3070d451 100644 --- a/src/app/tests/suites/manualTests.json +++ b/src/app/tests/suites/manualTests.json @@ -55,12 +55,7 @@ "Test_TC_BDX_2_4", "Test_TC_BDX_2_5" ], - "bridge": [ - "Test_TC_BR_1", - "Test_TC_BR_2", - "Test_TC_BR_3", - "Test_TC_BR_4" - ], + "bridge": ["Test_TC_BR_1", "Test_TC_BR_2", "Test_TC_BR_3", "Test_TC_BR_4"], "DeviceAttestation": [ "Test_TC_DA_1_1", "Test_TC_DA_1_3", @@ -115,25 +110,13 @@ "Test_TC_DLOG_2_2", "Test_TC_DLOG_3_1" ], - "Descriptor": [ - "Test_TC_DESC_2_1" - ], - "DeviceEnergyManagementMode": [ - "Test_TC_DEMM_1_2" - ], - "EnergyEVSEMode": [ - "Test_TC_EEVSEM_1_2" - ], + "Descriptor": ["Test_TC_DESC_2_1"], + "DeviceEnergyManagementMode": ["Test_TC_DEMM_1_2"], + "EnergyEVSEMode": ["Test_TC_EEVSEM_1_2"], "FanControl": [], - "GeneralCommissioning": [ - "Test_TC_CGEN_2_2" - ], - "GeneralDiagnostics": [ - "Test_TC_DGGEN_2_2" - ], - "Identify": [ - "Test_TC_I_3_2" - ], + "GeneralCommissioning": ["Test_TC_CGEN_2_2"], + "GeneralDiagnostics": ["Test_TC_DGGEN_2_2"], + "Identify": ["Test_TC_I_3_2"], "IcdManagement": [], "IlluminanceMeasurement": [], "InteractionDataModel": [ @@ -211,11 +194,7 @@ "Test_TC_CADMIN_1_25", "Test_TC_CADMIN_1_26" ], - "ModeSelect": [ - "Test_TC_MOD_1_2", - "Test_TC_MOD_1_3", - "Test_TC_MOD_2_2" - ], + "ModeSelect": ["Test_TC_MOD_1_2", "Test_TC_MOD_1_3", "Test_TC_MOD_2_2"], "OTASoftwareUpdate": [ "Test_TC_SU_1_1", "Test_TC_SU_2_1", @@ -233,9 +212,7 @@ "Test_TC_SU_4_1", "Test_TC_SU_4_2" ], - "PowerSourceConfiguration": [ - "Test_TC_PSCFG_2_2" - ], + "PowerSourceConfiguration": ["Test_TC_PSCFG_2_2"], "PressureMeasurement": [], "SecureChannel": [ "Test_TC_SC_1_1", @@ -268,25 +245,13 @@ "Test_TC_DGSW_2_3" ], "EthernetNetworkDiagnostics": [], - "WiFiNetworkDiagnostics": [ - "Test_TC_DGWIFI_2_2" - ], + "WiFiNetworkDiagnostics": ["Test_TC_DGWIFI_2_2"], "WindowCovering": [], - "FlowMeasurement": [ - "Test_TC_FLW_2_2" - ], - "GroupKeyManagement": [ - "Test_TC_GRPKEY_5_4" - ], - "OccupancySensing": [ - "Test_TC_OCC_3_1" - ], - "PowerSource": [ - "Test_TC_PS_2_2" - ], - "BooleanState": [ - "Test_TC_BOOL_2_2" - ], + "FlowMeasurement": ["Test_TC_FLW_2_2"], + "GroupKeyManagement": ["Test_TC_GRPKEY_5_4"], + "OccupancySensing": ["Test_TC_OCC_3_1"], + "PowerSource": ["Test_TC_PS_2_2"], + "BooleanState": ["Test_TC_BOOL_2_2"], "ColorControl": [ "Test_TC_CC_3_1", "Test_TC_CC_7_1", @@ -294,74 +259,34 @@ "Test_TC_CC_9_2", "Test_TC_CC_9_3" ], - "DoorLock": [ - "Test_TC_DRLK_2_10", - "Test_TC_DRLK_3_2" - ], - "DeviceEnergyManagement": [ - "Test_TC_DEM_1_1" - ], + "DoorLock": ["Test_TC_DRLK_2_10", "Test_TC_DRLK_3_2"], + "DeviceEnergyManagement": ["Test_TC_DEM_1_1"], "LocalizationConfiguration": [], "LevelControl": [], - "LaundryWasherMode": [ - "Test_TC_LWM_1_2" - ], - "OnOff": [ - "Test_TC_OO_2_3" - ], - "RelativeHumidityMeasurement": [ - "Test_TC_RH_2_2" - ], + "LaundryWasherMode": ["Test_TC_LWM_1_2"], + "OnOff": ["Test_TC_OO_2_3"], + "RelativeHumidityMeasurement": ["Test_TC_RH_2_2"], "SmokeCOAlarm": [], - "RefrigeratorAlarm": [ - "Test_TC_REFALM_2_2", - "Test_TC_REFALM_2_3" - ], - "RVCCleanMode": [ - "Test_TC_RVCCLEANM_3_3" - ], - "RVCOperationalState": [ - "Test_TC_RVCOPSTATE_2_2" - ], - "RVCRunMode": [ - "Test_TC_RVCRUNM_3_3" - ], + "RefrigeratorAlarm": ["Test_TC_REFALM_2_2", "Test_TC_REFALM_2_3"], + "RVCCleanMode": ["Test_TC_RVCCLEANM_3_3"], + "RVCOperationalState": ["Test_TC_RVCOPSTATE_2_2"], + "RVCRunMode": ["Test_TC_RVCRUNM_3_3"], "TemperatureControlledCabinetMode": [ "Test_TC_TCCM_1_2", "Test_TC_TCCM_2_1" ], - "Switch": [ - "Test_TC_SWTCH_3_2" - ], + "Switch": ["Test_TC_SWTCH_3_2"], "TemperatureControl": [], - "TemperatureMeasurement": [ - "Test_TC_TMP_2_2" - ], - "Thermostat": [ - "Test_TC_TSTAT_3_2" - ], + "TemperatureMeasurement": ["Test_TC_TMP_2_2"], + "Thermostat": ["Test_TC_TSTAT_3_2"], "ThermostatUserConfiguration": [], - "ThreadNetworkDiagnostics": [ - "Test_TC_DGTHREAD_2_5" - ], - "Actions": [ - "Test_TC_ACT_2_1", - "Test_TC_ACT_2_2", - "Test_TC_ACT_3_2" - ], + "ThreadNetworkDiagnostics": ["Test_TC_DGTHREAD_2_5"], + "Actions": ["Test_TC_ACT_2_1", "Test_TC_ACT_2_2", "Test_TC_ACT_3_2"], "TimeFormatLocalization": [], "TimeSynchronization": [], "UnitLocalization": [], - "Binding": [ - "Test_TC_BIND_2_1", - "Test_TC_BIND_2_2", - "Test_TC_BIND_2_3" - ], - "ScenesManagement": [ - "Test_TC_S_2_5", - "Test_TC_S_2_6", - "Test_TC_S_3_1" - ], + "Binding": ["Test_TC_BIND_2_1", "Test_TC_BIND_2_2", "Test_TC_BIND_2_3"], + "ScenesManagement": ["Test_TC_S_2_5", "Test_TC_S_2_6", "Test_TC_S_3_1"], "PumpConfigurationControl": [], "AccessControl": [], "UserLabel": [], @@ -370,23 +295,11 @@ "Test_TC_BRBINFO_3_1" ], "LaundryWasherControl": [], - "OvenMode": [ - "Test_TC_OTCCM_1_2", - "Test_TC_OTCCM_3_2", - "Test_TC_OTCCM_3_3" - ], + "OvenMode": ["Test_TC_OTCCM_1_2", "Test_TC_OTCCM_3_2", "Test_TC_OTCCM_3_3"], "AccessControlEnforcement": [], - "OvenMode": [ - "Test_TC_OTCCM_1_1", - "Test_TC_OTCCM_1_2" - ], - "EnergyEVSE": [ - "Test_TC_EEVSE_1_1", - "Test_TC_EEVSE_2_1" - ], - "PowerTopology": [ - "Test_TC_PWRTL_1_1" - ], + "OvenMode": ["Test_TC_OTCCM_1_1", "Test_TC_OTCCM_1_2"], + "EnergyEVSE": ["Test_TC_EEVSE_1_1", "Test_TC_EEVSE_2_1"], + "PowerTopology": ["Test_TC_PWRTL_1_1"], "collection": [ "DeviceDiscovery", "Groups", @@ -461,4 +374,4 @@ "AccessControlEnforcement", "LaundryWasherControl" ] -} \ No newline at end of file +} From 2daf1939abea6553c0a59401b6ff51a7cd471c79 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 9 Oct 2024 22:44:14 -0700 Subject: [PATCH 61/75] Updates CI python test arguments --- src/python_testing/TC_SC_4_3.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 83f9249acf2af6..6e057b77922902 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -15,13 +15,23 @@ # limitations under the License. # +# See https://github.com/project-chip/connectedhomeip/blob/master/docs/testing/python.md#defining-the-ci-test-arguments +# for details about the block below. + # === BEGIN CI TEST ARGUMENTS === -# test-runner-runs: run1 -# test-runner-run/run1/app: ${LIT_ICD_APP} -# test-runner-run/run1/factoryreset: True -# test-runner-run/run1/quiet: True -# test-runner-run/run1/app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json -# test-runner-run/run1/script-args: --storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --trace-to json:${TRACE_TEST_JSON}.json --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto +# test-runner-runs: +# run1: +# app: ${LIT_ICD_APP}S +# factory-reset: true +# quiet: true +# app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json +# script-args: > +# --storage-path admin_storage.json +# --commissioning-method on-network +# --discriminator 1234 +# --passcode 20202021 +# --trace-to json:${TRACE_TEST_JSON}.json +# --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto # === END CI TEST ARGUMENTS === import ipaddress From c03ed00a4f0a9044dac960769a55e6226138a32a Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Thu, 10 Oct 2024 01:07:03 -0700 Subject: [PATCH 62/75] Fix typo --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 6e057b77922902..fedc433d4783c3 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -21,7 +21,7 @@ # === BEGIN CI TEST ARGUMENTS === # test-runner-runs: # run1: -# app: ${LIT_ICD_APP}S +# app: ${LIT_ICD_APP} # factory-reset: true # quiet: true # app-args: --discriminator 1234 --KVS kvs1 --trace-to json:${TRACE_APP}.json From 929a12dd0bdefb218b39290fa654e19139bcd061 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 15 Oct 2024 09:07:20 -0700 Subject: [PATCH 63/75] matter_testing import update --- src/python_testing/TC_SC_4_3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index fedc433d4783c3..a38c24f7e32da3 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -39,7 +39,7 @@ import re import chip.clusters as Clusters -from matter_testing_support import MatterBaseTest, TestStep, async_test_body, default_matter_test_main +from chip.testing.matter_testing import MatterBaseTest, TestStep, async_test_body, default_matter_test_main from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType from mobly import asserts from zeroconf.const import _TYPE_AAAA, _TYPES From 418e8f1f17aee4880c6c6a8dd3fdda2763e12d1a Mon Sep 17 00:00:00 2001 From: Raul Marquez <130402456+raul-marquez-csa@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:36:09 -0700 Subject: [PATCH 64/75] Update src/python_testing/TC_SC_4_3.py Co-authored-by: C Freeman --- src/python_testing/TC_SC_4_3.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index a38c24f7e32da3..4926eba8d78720 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -45,7 +45,6 @@ from zeroconf.const import _TYPE_AAAA, _TYPES ''' -Category Functional conformance Purpose From 61274f22fbeb6eb9d7a1d10bd211567be587e1ce Mon Sep 17 00:00:00 2001 From: Raul Marquez <130402456+raul-marquez-csa@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:37:01 -0700 Subject: [PATCH 65/75] Update src/python_testing/TC_SC_4_3.py Co-authored-by: C Freeman --- src/python_testing/TC_SC_4_3.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 4926eba8d78720..1a384103415148 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -45,7 +45,6 @@ from zeroconf.const import _TYPE_AAAA, _TYPES ''' -Functional conformance Purpose The purpose of this test case is to verify that a Matter node is discoverable From 819ea06d77b95de2d83fdae85a5a6e128b801674 Mon Sep 17 00:00:00 2001 From: Raul Marquez <130402456+raul-marquez-csa@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:37:12 -0700 Subject: [PATCH 66/75] Update src/python_testing/TC_SC_4_3.py Co-authored-by: C Freeman --- src/python_testing/TC_SC_4_3.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 1a384103415148..3ad93abe49c987 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -45,7 +45,6 @@ from zeroconf.const import _TYPE_AAAA, _TYPES ''' - Purpose The purpose of this test case is to verify that a Matter node is discoverable and can advertise its services in a Matter network. From 5b05c696d1c7d1964e3f66e77ffeb6bc26b61b17 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 15 Oct 2024 12:10:53 -0700 Subject: [PATCH 67/75] Addresses latest --- src/python_testing/TC_SC_4_3.py | 16 +++--- .../mdns_discovery/mdns_discovery.py | 54 +++++++++++-------- 2 files changed, 41 insertions(+), 29 deletions(-) diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index 3ad93abe49c987..b495066d654a72 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -177,11 +177,13 @@ def extract_ipv6_address(text): @staticmethod def verify_hostname(hostname: str) -> bool: - # Remove '.local' or '.local.' suffix if present + # Remove any trailing dot + if hostname.endswith('.'): + hostname = hostname[:-1] + + # Remove '.local' suffix if present if hostname.endswith('.local'): hostname = hostname[:-6] - elif hostname.endswith('.local.'): - hostname = hostname[:-7] # Regular expression to match an uppercase hexadecimal string of 12 or 16 characters pattern = re.compile(r'^[0-9A-F]{12}$|^[0-9A-F]{16}$') @@ -204,9 +206,9 @@ async def test_TC_SC_4_3(self): self.step(2) ep0_servers = await self.get_descriptor_server_list() - # Check if ep0_servers contains the ICD Management cluster ID (0x0046) + # Check if ep0_servers contain the ICD Management cluster ID (0x0046) supports_icd = Clusters.IcdManagement.id in ep0_servers - logging.info(f"\n\n\tsupports_icd: {supports_icd}\n\n") + logging.info(f"supports_icd: {supports_icd}") # *** STEP 3 *** # If supports_icd is true, TH reads ActiveModeThreshold from the ICD Management cluster on EP0 and saves @@ -214,7 +216,7 @@ async def test_TC_SC_4_3(self): self.step(3) if supports_icd: active_mode_threshold_ms = await self.get_idle_mode_threshhold_ms() - logging.info(f"\n\n\tactive_mode_threshold_ms: {active_mode_threshold_ms}\n\n") + logging.info(f"active_mode_threshold_ms: {active_mode_threshold_ms}") # *** STEP 4 *** # If supports_icd is true, TH reads FeatureMap from the ICD Management cluster on EP0. If the LITS feature @@ -224,7 +226,7 @@ async def test_TC_SC_4_3(self): feature_map = await self.get_icd_feature_map() LITS = Clusters.IcdManagement.Bitmaps.Feature.kLongIdleTimeSupport supports_lit = bool(feature_map & LITS == LITS) - logging.info(f"\n\n\tkLongIdleTimeSupport set: {supports_lit}\n\n") + logging.info(f"kLongIdleTimeSupport set: {supports_lit}") # *** STEP 5 *** # TH constructs the instance name for the DUT as the 64-bit compressed Fabric identifier, and the diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 1dc31744b4ea06..2a68be6832371e 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -84,14 +84,14 @@ class MdnsServiceType(Enum): class MdnsServiceListener(ServiceListener): """ - A service listener required for the TXT record data to get populated and come back + A service listener required during mDNS service discovery """ def __init__(self): self.updated_event = asyncio.Event() def add_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: - sleep(0.25) + sleep(0.125) self.updated_event.set() def remove_service(self, zeroconf: Zeroconf, service_type: str, name: str) -> None: @@ -141,7 +141,7 @@ async def get_commissioner_service(self, log_output: bool = False, """ Asynchronously discovers a commissioner mDNS service within the network. - Args: + Optional args: log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. @@ -157,7 +157,7 @@ async def get_commissionable_service(self, log_output: bool = False, """ Asynchronously discovers a commissionable mDNS service within the network. - Args: + Optional args: log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. @@ -176,16 +176,19 @@ async def get_operational_service(self, """ Asynchronously discovers an operational mDNS service within the network. - Args: + Optional args: log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. - node_id: the node id to create the service name from - compressed_fabric_id: the fabric id to create the service name from + node_id: the node id to create the service name from + compressed_fabric_id: the fabric id to create the service name from Returns: Optional[MdnsServiceInfo]: An instance of MdnsServiceInfo or None if timeout reached. """ - # Validation to ensure both or none of the parameters are provided + + # Validation to ensure that both node_id and compressed_fabric_id are provided or both are None. + if (node_id is None) != (compressed_fabric_id is None): + raise ValueError("Both node_id and compressed_fabric_id must be provided together or not at all.") self._name_filter = f'{compressed_fabric_id:016x}-{node_id:016x}.{MdnsServiceType.OPERATIONAL.value}'.upper() return await self._get_service(MdnsServiceType.OPERATIONAL, log_output, discovery_timeout_sec) @@ -196,7 +199,7 @@ async def get_border_router_service(self, log_output: bool = False, """ Asynchronously discovers a border router mDNS service within the network. - Args: + Optional args: log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. @@ -211,7 +214,7 @@ async def get_all_services(self, log_output: bool = False, """ Asynchronously discovers all available mDNS services within the network. - Args: + Optional args: log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. @@ -229,7 +232,7 @@ async def get_service_types(self, log_output: bool = False, discovery_timeout_se of the service types discovered. This method utilizes the AsyncZeroconfServiceTypes.async_find() function to perform the network scan for mDNS services. - Args: + Optional args: log_output (bool): If set to True, the discovered service types are logged to the console. This can be useful for debugging or informational purposes. Defaults to False. discovery_timeout_sec (float): The maximum time (in seconds) to wait for the discovery process. Defaults to 10.0 seconds. @@ -242,11 +245,11 @@ async def get_service_types(self, log_output: bool = False, discovery_timeout_se try: discovered_services = list(await asyncio.wait_for(AsyncZeroconfServiceTypes.async_find(), timeout=discovery_timeout_sec)) except asyncio.TimeoutError: - print(f"MDNS service types discovery timed out after {discovery_timeout_sec} seconds.") + logger.info(f"MDNS service types discovery timed out after {discovery_timeout_sec} seconds.") discovered_services = [] if log_output: - print(f"MDNS discovered service types: {discovered_services}") + logger.info(f"MDNS discovered service types: {discovered_services}") return discovered_services @@ -260,12 +263,19 @@ async def get_service_by_record_type(self, service_name: str, Asynchronously discovers an mDNS service within the network by service name, service type, and record type. - Args: + Required args: + service_name (str): The unique name of the mDNS service. + Example: + C82B83803DECA0B2-0000000012344321._matter._tcp.local. + + record_type (DNSRecordType): The type of record to look for (SRV, TXT, AAAA, A). + Example: + _matterd._tcp.local. (from the MdnsServiceType enum) + + Optional args: + service_type (str): The service type of the service. Defaults to None. log_output (bool): Logs the discovered services to the console. Defaults to False. discovery_timeout_sec (float): Defaults to 15 seconds. - service_name (str): The unique name of the mDNS service. Defaults to None. - service_type (str): The service type of the service. Defaults to None. - record_type (DNSRecordType): The type of record to look for (SRV, TXT, AAAA, A). Returns: Union[Optional[MdnsServiceInfo], Optional[DNSRecord]]: An instance of MdnsServiceInfo, @@ -274,10 +284,10 @@ async def get_service_by_record_type(self, service_name: str, mdns_service_info = None if service_type: - print( + logger.info( f"\nLooking for MDNS service type '{service_type}', service name '{service_name}', record type '{record_type.name}'\n") else: - print( + logger.info( f"\nLooking for MDNS service with service name '{service_name}', record type '{record_type.name}'\n") # Adds service listener @@ -288,7 +298,7 @@ async def get_service_by_record_type(self, service_name: str, try: await asyncio.wait_for(service_listener.updated_event.wait(), discovery_timeout_sec) except asyncio.TimeoutError: - print(f"Service lookup for {service_name} timeout ({discovery_timeout_sec}) reached without an update.") + logger.info(f"Service lookup for {service_name} timeout ({discovery_timeout_sec}) reached without an update.") finally: self._zc.remove_service_listener(service_listener) @@ -307,7 +317,7 @@ async def get_service_by_record_type(self, service_name: str, dns_incoming = DNSIncoming(listener.data) if dns_incoming.data: answers = dns_incoming.answers() - print(f"\nIncoming DNSRecord: {answers}\n") + logger.info(f"\nIncoming DNSRecord: {answers}\n") return answers.pop(0) if answers else None else: # Adds service to discovered services @@ -510,7 +520,7 @@ async def _get_service(self, service_type: MdnsServiceType, def _log_output(self) -> str: """ - Converts the discovered services to a JSON string and log it. + Converts the discovered services to a JSON string and logs it. The method is intended to be used for debugging or informational purposes, providing a clear and comprehensive view of all services discovered during the mDNS service discovery process. From b42f4cb7ac8ceb5057a3ae4864c4734cf67c4800 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 15 Oct 2024 12:15:47 -0700 Subject: [PATCH 68/75] Fix restyle --- src/python_testing/mdns_discovery/mdns_discovery.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index 2a68be6832371e..cc3d7c8e823055 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -267,7 +267,7 @@ async def get_service_by_record_type(self, service_name: str, service_name (str): The unique name of the mDNS service. Example: C82B83803DECA0B2-0000000012344321._matter._tcp.local. - + record_type (DNSRecordType): The type of record to look for (SRV, TXT, AAAA, A). Example: _matterd._tcp.local. (from the MdnsServiceType enum) From 20a35bb096cdbab5770111716654c72d084e9e01 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Tue, 12 Nov 2024 09:51:33 -0800 Subject: [PATCH 69/75] Testing zeroconf class imports --- src/python_testing/TC_SC_000.py | 23 + .../mdns_discovery/mdns_async_service_info.py | 137 +-- .../mdns_discovery/service_info_base.py | 959 ++++++++++++++++++ 3 files changed, 998 insertions(+), 121 deletions(-) create mode 100644 src/python_testing/TC_SC_000.py create mode 100644 src/python_testing/mdns_discovery/service_info_base.py diff --git a/src/python_testing/TC_SC_000.py b/src/python_testing/TC_SC_000.py new file mode 100644 index 00000000000000..b1aae5126b9a37 --- /dev/null +++ b/src/python_testing/TC_SC_000.py @@ -0,0 +1,23 @@ +from chip.testing.matter_testing import MatterBaseTest, async_test_body, default_matter_test_main +from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType + +class TC_SC_000(MatterBaseTest): + + @async_test_body + async def test_TC_SC_000(self): + node_id = self.dut_node_id + compressed_fabric_id = self.default_controller.GetCompressedFabricId() + instance_name = f'{compressed_fabric_id:016X}-{node_id:016X}' + instance_qname = f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}" + mdns = MdnsDiscovery() + + await mdns.get_service_by_record_type( + service_name=instance_qname, + service_type=MdnsServiceType.OPERATIONAL.value, + record_type=DNSRecordType.TXT, + log_output=True + ) + + +if __name__ == "__main__": + default_matter_test_main() diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index d836b358cd6460..0406b3db256cdc 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -16,18 +16,21 @@ # -import asyncio import enum -from ipaddress import IPv4Address, IPv6Address -from random import randint -from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast +from typing import TYPE_CHECKING, Optional -from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, - DNSService, DNSText, RecordUpdateListener, ServiceInfo, Zeroconf, current_time_millis, service_type_name) -from zeroconf._utils.net import _encode_address -from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, +from zeroconf import (DNSOutgoing, DNSQuestion, DNSQuestionType, Zeroconf, current_time_millis) +from zeroconf.const import (_CLASS_IN, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) + +# Import from zeroconf blows up, import from clone class works :\ +# ▼ ▼ ▼ ▼ ▼ + +# from zeroconf import ServiceInfo +from mdns_discovery.service_info_base import ServiceInfo + + int_ = int float_ = float str_ = str @@ -35,7 +38,6 @@ QU_QUESTION = DNSQuestionType.QU QM_QUESTION = DNSQuestionType.QM -_AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) @enum.unique @@ -55,61 +57,9 @@ class DNSRecordType(enum.Enum): class MdnsAsyncServiceInfo(ServiceInfo): - def __init__( - self, - zc: 'Zeroconf', - name: str, - type_: str = None, - port: Optional[int] = None, - weight: int = 0, - priority: int = 0, - properties: Union[bytes, Dict] = b'', - server: Optional[str] = None, - host_ttl: int = _DNS_HOST_TTL, - other_ttl: int = _DNS_OTHER_TTL, - *, - addresses: Optional[List[bytes]] = None, - parsed_addresses: Optional[List[str]] = None, - interface_index: Optional[int] = None, - ) -> None: - # Accept both none, or one, but not both. - if addresses is not None and parsed_addresses is not None: - raise TypeError("addresses and parsed_addresses cannot be provided together") - - if type_ and not type_.endswith(service_type_name(name, strict=False)): - raise BadTypeInNameException - - self.interface_index = interface_index - self.text = b'' + def __init__(self, zc: 'Zeroconf', *args, **kwargs): + super().__init__(*args, **kwargs) self._zc = zc - self._name = name - self.type = type_ - self.key = name.lower() - self._ipv4_addresses: List[IPv4Address] = [] - self._ipv6_addresses: List[IPv6Address] = [] - if addresses is not None: - self.addresses = addresses - elif parsed_addresses is not None: - self.addresses = [_encode_address(a) for a in parsed_addresses] - self.port = port - self.weight = weight - self.priority = priority - self.server = server if server else None - self.server_key = server.lower() if server else None - self._properties: Optional[Dict[bytes, Optional[bytes]]] = None - self._decoded_properties: Optional[Dict[str, Optional[str]]] = None - if isinstance(properties, bytes): - self._set_text(properties) - else: - self._set_properties(properties) - self.host_ttl = host_ttl - self.other_ttl = other_ttl - self._new_records_futures: Optional[Set[asyncio.Future]] = None - self._dns_address_cache: Optional[List[DNSAddress]] = None - self._dns_pointer_cache: Optional[DNSPointer] = None - self._dns_service_cache: Optional[DNSService] = None - self._dns_text_cache: Optional[DNSText] = None - self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None async def async_request( self, @@ -142,13 +92,13 @@ async def async_request( next_ = now last = now + timeout try: - self.async_add_listener(self, None) + self._zc.async_add_listener(self, None) while not self._is_complete: if last <= now: return False if next_ <= now: this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION - out: DNSOutgoing = self._generate_request_query(self._zc, now, this_question_type, record_type) + out: DNSOutgoing = self._generate_request_query(this_question_type, record_type) first_request = False if out.questions: # All questions may have been suppressed @@ -174,19 +124,8 @@ async def async_request( return True - def async_add_listener( - self, listener: RecordUpdateListener, question: Optional[Union[DNSQuestion, List[DNSQuestion]]] - ) -> None: - """Adds a listener for a given question. The listener will have - its update_record method called when information is available to - answer the question(s). - - This function is not threadsafe and must be called in the eventloop. - """ - self._zc.record_manager.async_add_listener(listener, question) - def _generate_request_query( - self, zc: 'Zeroconf', now: float_, question_type: DNSQuestionType, record_type: DNSRecordType + self, question_type: DNSQuestionType, record_type: DNSRecordType ) -> DNSOutgoing: """Generate the request query.""" out = DNSOutgoing(_FLAGS_QR_QUERY) @@ -227,47 +166,3 @@ def _add_question( question = DNSQuestion(name, type_, class_) question.unicast = qu_question out.add_question(question) - - def _get_initial_delay(self) -> float_: - return _LISTENER_TIME - - def _get_random_delay(self) -> int_: - return randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) - - def _set_properties(self, properties: Dict[Union[str, bytes], Optional[Union[str, bytes]]]) -> None: - """Sets properties and text of this info from a dictionary""" - list_: List[bytes] = [] - properties_contain_str = False - result = b'' - for key, value in properties.items(): - if isinstance(key, str): - key = key.encode('utf-8') - properties_contain_str = True - - record = key - if value is not None: - if not isinstance(value, bytes): - value = str(value).encode('utf-8') - properties_contain_str = True - record += b'=' + value - list_.append(record) - for item in list_: - result = b''.join((result, bytes((len(item),)), item)) - if not properties_contain_str: - # If there are no str keys or values, we can use the properties - # as-is, without decoding them, otherwise calling - # self.properties will lazy decode them, which is expensive. - if TYPE_CHECKING: - self._properties = cast("Dict[bytes, Optional[bytes]]", properties) - else: - self._properties = properties - self.text = result - - def _set_text(self, text: bytes) -> None: - """Sets properties and text given a text field""" - if text == self.text: - return - self.text = text - # Clear the properties cache - self._properties = None - self._decoded_properties = None diff --git a/src/python_testing/mdns_discovery/service_info_base.py b/src/python_testing/mdns_discovery/service_info_base.py new file mode 100644 index 00000000000000..0a907cf93a17dc --- /dev/null +++ b/src/python_testing/mdns_discovery/service_info_base.py @@ -0,0 +1,959 @@ +"""Multicast DNS Service Discovery for Python, v0.14-wmcbrine +Copyright 2003 Paul Scott-Murphy, 2014 William McBrine + +This module provides a framework for the use of DNS Service Discovery +using IP multicast. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 +USA +""" + +import asyncio +import random +import sys +from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast + +from zeroconf._cache import DNSCache +from zeroconf._dns import ( + DNSAddress, + DNSNsec, + DNSPointer, + DNSQuestion, + DNSQuestionType, + DNSRecord, + DNSService, + DNSText, +) +from zeroconf._exceptions import BadTypeInNameException +from zeroconf._history import QuestionHistory +from zeroconf._logger import log +from zeroconf._protocol.outgoing import DNSOutgoing +from zeroconf._record_update import RecordUpdate +from zeroconf._updates import RecordUpdateListener +from zeroconf._utils.asyncio import ( + _resolve_all_futures_to_none, + get_running_loop, + run_coro_with_timeout, + wait_for_future_set_or_timeout, +) +from zeroconf._utils.ipaddress import ( + ZeroconfIPv4Address, + ZeroconfIPv6Address, + cached_ip_addresses, + get_ip_address_object_from_record, + ip_bytes_and_scope_to_address, + str_without_scope_id, +) +from zeroconf._utils.name import service_type_name +from zeroconf._utils.net import IPVersion, _encode_address +from zeroconf._utils.time import current_time_millis +from zeroconf.const import ( + _ADDRESS_RECORD_TYPES, + _CLASS_IN, + _CLASS_IN_UNIQUE, + _DNS_HOST_TTL, + _DNS_OTHER_TTL, + _DUPLICATE_QUESTION_INTERVAL, + _FLAGS_QR_QUERY, + _LISTENER_TIME, + _MDNS_PORT, + _TYPE_A, + _TYPE_AAAA, + _TYPE_NSEC, + _TYPE_PTR, + _TYPE_SRV, + _TYPE_TXT, +) + +IPADDRESS_SUPPORTS_SCOPE_ID = sys.version_info >= (3, 9, 0) + +_IPVersion_All_value = IPVersion.All.value +_IPVersion_V4Only_value = IPVersion.V4Only.value +# https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 +# The most common case for calling ServiceInfo is from a +# ServiceBrowser. After the first request we add a few random +# milliseconds to the delay between requests to reduce the chance +# that there are multiple ServiceBrowser callbacks running on +# the network that are firing at the same time when they +# see the same multicast response and decide to refresh +# the A/AAAA/SRV records for a host. +_AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) + +bytes_ = bytes +float_ = float +int_ = int +str_ = str + +QU_QUESTION = DNSQuestionType.QU +QM_QUESTION = DNSQuestionType.QM + +randint = random.randint + +if TYPE_CHECKING: + from .._core import Zeroconf + + +def instance_name_from_service_info(info: "ServiceInfo", strict: bool = True) -> str: + """Calculate the instance name from the ServiceInfo.""" + # This is kind of funky because of the subtype based tests + # need to make subtypes a first class citizen + service_name = service_type_name(info.name, strict=strict) + if not info.type.endswith(service_name): + raise BadTypeInNameException + return info.name[: -len(service_name) - 1] + + +class ServiceInfo(RecordUpdateListener): + """Service information. + + Constructor parameters are as follows: + + * `type_`: fully qualified service type name + * `name`: fully qualified service name + * `port`: port that the service runs on + * `weight`: weight of the service + * `priority`: priority of the service + * `properties`: dictionary of properties (or a bytes object holding the contents of the `text` field). + converted to str and then encoded to bytes using UTF-8. Keys with `None` values are converted to + value-less attributes. + * `server`: fully qualified name for service host (defaults to name) + * `host_ttl`: ttl used for A/SRV records + * `other_ttl`: ttl used for PTR/TXT records + * `addresses` and `parsed_addresses`: List of IP addresses (either as bytes, network byte order, + or in parsed form as text; at most one of those parameters can be provided) + * interface_index: scope_id or zone_id for IPv6 link-local addresses i.e. an identifier of the interface + where the peer is connected to + """ + + __slots__ = ( + "text", + "type", + "_name", + "key", + "_ipv4_addresses", + "_ipv6_addresses", + "port", + "weight", + "priority", + "server", + "server_key", + "_properties", + "_decoded_properties", + "host_ttl", + "other_ttl", + "interface_index", + "_new_records_futures", + "_dns_pointer_cache", + "_dns_service_cache", + "_dns_text_cache", + "_dns_address_cache", + "_get_address_and_nsec_records_cache", + ) + + def __init__( + self, + type_: str, + name: str, + port: Optional[int] = None, + weight: int = 0, + priority: int = 0, + properties: Union[bytes, Dict] = b"", + server: Optional[str] = None, + host_ttl: int = _DNS_HOST_TTL, + other_ttl: int = _DNS_OTHER_TTL, + *, + addresses: Optional[List[bytes]] = None, + parsed_addresses: Optional[List[str]] = None, + interface_index: Optional[int] = None, + ) -> None: + # Accept both none, or one, but not both. + if addresses is not None and parsed_addresses is not None: + raise TypeError("addresses and parsed_addresses cannot be provided together") + if not type_.endswith(service_type_name(name, strict=False)): + raise BadTypeInNameException + self.interface_index = interface_index + self.text = b"" + self.type = type_ + self._name = name + self.key = name.lower() + self._ipv4_addresses: List[ZeroconfIPv4Address] = [] + self._ipv6_addresses: List[ZeroconfIPv6Address] = [] + if addresses is not None: + self.addresses = addresses + elif parsed_addresses is not None: + self.addresses = [_encode_address(a) for a in parsed_addresses] + self.port = port + self.weight = weight + self.priority = priority + self.server = server if server else None + self.server_key = server.lower() if server else None + self._properties: Optional[Dict[bytes, Optional[bytes]]] = None + self._decoded_properties: Optional[Dict[str, Optional[str]]] = None + if isinstance(properties, bytes): + self._set_text(properties) + else: + self._set_properties(properties) + self.host_ttl = host_ttl + self.other_ttl = other_ttl + self._new_records_futures: Optional[Set[asyncio.Future]] = None + self._dns_address_cache: Optional[List[DNSAddress]] = None + self._dns_pointer_cache: Optional[DNSPointer] = None + self._dns_service_cache: Optional[DNSService] = None + self._dns_text_cache: Optional[DNSText] = None + self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None + + @property + def name(self) -> str: + """The name of the service.""" + return self._name + + @name.setter + def name(self, name: str) -> None: + """Replace the name and reset the key.""" + self._name = name + self.key = name.lower() + self._dns_service_cache = None + self._dns_pointer_cache = None + self._dns_text_cache = None + + @property + def addresses(self) -> List[bytes]: + """IPv4 addresses of this service. + + Only IPv4 addresses are returned for backward compatibility. + Use :meth:`addresses_by_version` or :meth:`parsed_addresses` to + include IPv6 addresses as well. + """ + return self.addresses_by_version(IPVersion.V4Only) + + @addresses.setter + def addresses(self, value: List[bytes]) -> None: + """Replace the addresses list. + + This replaces all currently stored addresses, both IPv4 and IPv6. + """ + self._ipv4_addresses.clear() + self._ipv6_addresses.clear() + self._dns_address_cache = None + self._get_address_and_nsec_records_cache = None + + for address in value: + if IPADDRESS_SUPPORTS_SCOPE_ID and len(address) == 16 and self.interface_index is not None: + addr = ip_bytes_and_scope_to_address(address, self.interface_index) + else: + addr = cached_ip_addresses(address) + if addr is None: + raise TypeError( + "Addresses must either be IPv4 or IPv6 strings, bytes, or integers;" + f" got {address!r}. Hint: convert string addresses with socket.inet_pton" + ) + if addr.version == 4: + if TYPE_CHECKING: + assert isinstance(addr, ZeroconfIPv4Address) + self._ipv4_addresses.append(addr) + else: + if TYPE_CHECKING: + assert isinstance(addr, ZeroconfIPv6Address) + self._ipv6_addresses.append(addr) + + @property + def properties(self) -> Dict[bytes, Optional[bytes]]: + """Return properties as bytes.""" + if self._properties is None: + self._unpack_text_into_properties() + if TYPE_CHECKING: + assert self._properties is not None + return self._properties + + @property + def decoded_properties(self) -> Dict[str, Optional[str]]: + """Return properties as strings.""" + if self._decoded_properties is None: + self._generate_decoded_properties() + if TYPE_CHECKING: + assert self._decoded_properties is not None + return self._decoded_properties + + def async_clear_cache(self) -> None: + """Clear the cache for this service info.""" + self._dns_address_cache = None + self._dns_pointer_cache = None + self._dns_service_cache = None + self._dns_text_cache = None + self._get_address_and_nsec_records_cache = None + + async def async_wait(self, timeout: float, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + """Calling task waits for a given number of milliseconds or until notified.""" + if not self._new_records_futures: + self._new_records_futures = set() + await wait_for_future_set_or_timeout( + loop or asyncio.get_running_loop(), self._new_records_futures, timeout + ) + + def addresses_by_version(self, version: IPVersion) -> List[bytes]: + """List addresses matching IP version. + + Addresses are guaranteed to be returned in LIFO (last in, first out) + order with IPv4 addresses first and IPv6 addresses second. + + This means the first address will always be the most recently added + address of the given IP version. + """ + version_value = version.value + if version_value == _IPVersion_All_value: + ip_v4_packed = [addr.packed for addr in self._ipv4_addresses] + ip_v6_packed = [addr.packed for addr in self._ipv6_addresses] + return [*ip_v4_packed, *ip_v6_packed] + if version_value == _IPVersion_V4Only_value: + return [addr.packed for addr in self._ipv4_addresses] + return [addr.packed for addr in self._ipv6_addresses] + + def ip_addresses_by_version( + self, version: IPVersion + ) -> Union[List[ZeroconfIPv4Address], List[ZeroconfIPv6Address]]: + """List ip_address objects matching IP version. + + Addresses are guaranteed to be returned in LIFO (last in, first out) + order with IPv4 addresses first and IPv6 addresses second. + + This means the first address will always be the most recently added + address of the given IP version. + """ + return self._ip_addresses_by_version_value(version.value) + + def _ip_addresses_by_version_value( + self, version_value: int_ + ) -> Union[List[ZeroconfIPv4Address], List[ZeroconfIPv6Address]]: + """Backend for addresses_by_version that uses the raw value.""" + if version_value == _IPVersion_All_value: + return [*self._ipv4_addresses, *self._ipv6_addresses] # type: ignore[return-value] + if version_value == _IPVersion_V4Only_value: + return self._ipv4_addresses + return self._ipv6_addresses + + def parsed_addresses(self, version: IPVersion = IPVersion.All) -> List[str]: + """List addresses in their parsed string form. + + Addresses are guaranteed to be returned in LIFO (last in, first out) + order with IPv4 addresses first and IPv6 addresses second. + + This means the first address will always be the most recently added + address of the given IP version. + """ + return [str_without_scope_id(addr) for addr in self._ip_addresses_by_version_value(version.value)] + + def parsed_scoped_addresses(self, version: IPVersion = IPVersion.All) -> List[str]: + """Equivalent to parsed_addresses, with the exception that IPv6 Link-Local + addresses are qualified with % when available + + Addresses are guaranteed to be returned in LIFO (last in, first out) + order with IPv4 addresses first and IPv6 addresses second. + + This means the first address will always be the most recently added + address of the given IP version. + """ + return [str(addr) for addr in self._ip_addresses_by_version_value(version.value)] + + def _set_properties(self, properties: Dict[Union[str, bytes], Optional[Union[str, bytes]]]) -> None: + """Sets properties and text of this info from a dictionary""" + list_: List[bytes] = [] + properties_contain_str = False + result = b"" + for key, value in properties.items(): + if isinstance(key, str): + key = key.encode("utf-8") + properties_contain_str = True + + record = key + if value is not None: + if not isinstance(value, bytes): + value = str(value).encode("utf-8") + properties_contain_str = True + record += b"=" + value + list_.append(record) + for item in list_: + result = b"".join((result, bytes((len(item),)), item)) + if not properties_contain_str: + # If there are no str keys or values, we can use the properties + # as-is, without decoding them, otherwise calling + # self.properties will lazy decode them, which is expensive. + if TYPE_CHECKING: + self._properties = cast("Dict[bytes, Optional[bytes]]", properties) + else: + self._properties = properties + self.text = result + + def _set_text(self, text: bytes) -> None: + """Sets properties and text given a text field""" + if text == self.text: + return + self.text = text + # Clear the properties cache + self._properties = None + self._decoded_properties = None + + def _generate_decoded_properties(self) -> None: + """Generates decoded properties from the properties""" + self._decoded_properties = { + k.decode("ascii", "replace"): None if v is None else v.decode("utf-8", "replace") + for k, v in self.properties.items() + } + + def _unpack_text_into_properties(self) -> None: + """Unpacks the text field into properties""" + text = self.text + end = len(text) + if end == 0: + # Properties should be set atomically + # in case another thread is reading them + self._properties = {} + return + + index = 0 + properties: Dict[bytes, Optional[bytes]] = {} + while index < end: + length = text[index] + index += 1 + key_value = text[index : index + length] + key_sep_value = key_value.partition(b"=") + key = key_sep_value[0] + if key not in properties: + properties[key] = key_sep_value[2] or None + index += length + + self._properties = properties + + def get_name(self) -> str: + """Name accessor""" + return self._name[: len(self._name) - len(self.type) - 1] + + def _get_ip_addresses_from_cache_lifo( + self, zc: "Zeroconf", now: float_, type: int_ + ) -> List[Union[ZeroconfIPv4Address, ZeroconfIPv6Address]]: + """Set IPv6 addresses from the cache.""" + address_list: List[Union[ZeroconfIPv4Address, ZeroconfIPv6Address]] = [] + for record in self._get_address_records_from_cache_by_type(zc, type): + if record.is_expired(now): + continue + ip_addr = get_ip_address_object_from_record(record) + if ip_addr is not None and ip_addr not in address_list: + address_list.append(ip_addr) + address_list.reverse() # Reverse to get LIFO order + return address_list + + def _set_ipv6_addresses_from_cache(self, zc: "Zeroconf", now: float_) -> None: + """Set IPv6 addresses from the cache.""" + if TYPE_CHECKING: + self._ipv6_addresses = cast( + "List[ZeroconfIPv6Address]", + self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_AAAA), + ) + else: + self._ipv6_addresses = self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_AAAA) + + def _set_ipv4_addresses_from_cache(self, zc: "Zeroconf", now: float_) -> None: + """Set IPv4 addresses from the cache.""" + if TYPE_CHECKING: + self._ipv4_addresses = cast( + "List[ZeroconfIPv4Address]", + self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_A), + ) + else: + self._ipv4_addresses = self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_A) + + def async_update_records(self, zc: "Zeroconf", now: float_, records: List[RecordUpdate]) -> None: + """Updates service information from a DNS record. + + This method will be run in the event loop. + """ + new_records_futures = self._new_records_futures + updated: bool = False + for record_update in records: + updated |= self._process_record_threadsafe(zc, record_update.new, now) + if updated and new_records_futures: + _resolve_all_futures_to_none(new_records_futures) + + def _process_record_threadsafe(self, zc: "Zeroconf", record: DNSRecord, now: float_) -> bool: + """Thread safe record updating. + + Returns True if a new record was added. + """ + if record.is_expired(now): + return False + + record_key = record.key + record_type = type(record) + if record_type is DNSAddress and record_key == self.server_key: + dns_address_record = record + if TYPE_CHECKING: + assert isinstance(dns_address_record, DNSAddress) + ip_addr = get_ip_address_object_from_record(dns_address_record) + if ip_addr is None: + log.warning( + "Encountered invalid address while processing %s: %s", + dns_address_record, + dns_address_record.address, + ) + return False + + if ip_addr.version == 4: + if TYPE_CHECKING: + assert isinstance(ip_addr, ZeroconfIPv4Address) + ipv4_addresses = self._ipv4_addresses + if ip_addr not in ipv4_addresses: + ipv4_addresses.insert(0, ip_addr) + return True + # Use int() to compare the addresses as integers + # since by default IPv4Address.__eq__ compares the + # the addresses on version and int which more than + # we need here since we know the version is 4. + elif ip_addr.zc_integer != ipv4_addresses[0].zc_integer: + ipv4_addresses.remove(ip_addr) + ipv4_addresses.insert(0, ip_addr) + + return False + + if TYPE_CHECKING: + assert isinstance(ip_addr, ZeroconfIPv6Address) + ipv6_addresses = self._ipv6_addresses + if ip_addr not in self._ipv6_addresses: + ipv6_addresses.insert(0, ip_addr) + return True + # Use int() to compare the addresses as integers + # since by default IPv6Address.__eq__ compares the + # the addresses on version and int which more than + # we need here since we know the version is 6. + elif ip_addr.zc_integer != self._ipv6_addresses[0].zc_integer: + ipv6_addresses.remove(ip_addr) + ipv6_addresses.insert(0, ip_addr) + + return False + + if record_key != self.key: + return False + + if record_type is DNSText: + dns_text_record = record + if TYPE_CHECKING: + assert isinstance(dns_text_record, DNSText) + self._set_text(dns_text_record.text) + return True + + if record_type is DNSService: + dns_service_record = record + if TYPE_CHECKING: + assert isinstance(dns_service_record, DNSService) + old_server_key = self.server_key + self._name = dns_service_record.name + self.key = dns_service_record.key + self.server = dns_service_record.server + self.server_key = dns_service_record.server_key + self.port = dns_service_record.port + self.weight = dns_service_record.weight + self.priority = dns_service_record.priority + if old_server_key != self.server_key: + self._set_ipv4_addresses_from_cache(zc, now) + self._set_ipv6_addresses_from_cache(zc, now) + return True + + return False + + def dns_addresses( + self, + override_ttl: Optional[int] = None, + version: IPVersion = IPVersion.All, + ) -> List[DNSAddress]: + """Return matching DNSAddress from ServiceInfo.""" + return self._dns_addresses(override_ttl, version) + + def _dns_addresses( + self, + override_ttl: Optional[int], + version: IPVersion, + ) -> List[DNSAddress]: + """Return matching DNSAddress from ServiceInfo.""" + cacheable = version is IPVersion.All and override_ttl is None + if self._dns_address_cache is not None and cacheable: + return self._dns_address_cache + name = self.server or self._name + ttl = override_ttl if override_ttl is not None else self.host_ttl + class_ = _CLASS_IN_UNIQUE + version_value = version.value + records = [ + DNSAddress( + name, + _TYPE_AAAA if ip_addr.version == 6 else _TYPE_A, + class_, + ttl, + ip_addr.packed, + created=0.0, + ) + for ip_addr in self._ip_addresses_by_version_value(version_value) + ] + if cacheable: + self._dns_address_cache = records + return records + + def dns_pointer(self, override_ttl: Optional[int] = None) -> DNSPointer: + """Return DNSPointer from ServiceInfo.""" + return self._dns_pointer(override_ttl) + + def _dns_pointer(self, override_ttl: Optional[int]) -> DNSPointer: + """Return DNSPointer from ServiceInfo.""" + cacheable = override_ttl is None + if self._dns_pointer_cache is not None and cacheable: + return self._dns_pointer_cache + record = DNSPointer( + self.type, + _TYPE_PTR, + _CLASS_IN, + override_ttl if override_ttl is not None else self.other_ttl, + self._name, + 0.0, + ) + if cacheable: + self._dns_pointer_cache = record + return record + + def dns_service(self, override_ttl: Optional[int] = None) -> DNSService: + """Return DNSService from ServiceInfo.""" + return self._dns_service(override_ttl) + + def _dns_service(self, override_ttl: Optional[int]) -> DNSService: + """Return DNSService from ServiceInfo.""" + cacheable = override_ttl is None + if self._dns_service_cache is not None and cacheable: + return self._dns_service_cache + port = self.port + if TYPE_CHECKING: + assert isinstance(port, int) + record = DNSService( + self._name, + _TYPE_SRV, + _CLASS_IN_UNIQUE, + override_ttl if override_ttl is not None else self.host_ttl, + self.priority, + self.weight, + port, + self.server or self._name, + 0.0, + ) + if cacheable: + self._dns_service_cache = record + return record + + def dns_text(self, override_ttl: Optional[int] = None) -> DNSText: + """Return DNSText from ServiceInfo.""" + return self._dns_text(override_ttl) + + def _dns_text(self, override_ttl: Optional[int]) -> DNSText: + """Return DNSText from ServiceInfo.""" + cacheable = override_ttl is None + if self._dns_text_cache is not None and cacheable: + return self._dns_text_cache + record = DNSText( + self._name, + _TYPE_TXT, + _CLASS_IN_UNIQUE, + override_ttl if override_ttl is not None else self.other_ttl, + self.text, + 0.0, + ) + if cacheable: + self._dns_text_cache = record + return record + + def dns_nsec(self, missing_types: List[int], override_ttl: Optional[int] = None) -> DNSNsec: + """Return DNSNsec from ServiceInfo.""" + return self._dns_nsec(missing_types, override_ttl) + + def _dns_nsec(self, missing_types: List[int], override_ttl: Optional[int]) -> DNSNsec: + """Return DNSNsec from ServiceInfo.""" + return DNSNsec( + self._name, + _TYPE_NSEC, + _CLASS_IN_UNIQUE, + override_ttl if override_ttl is not None else self.host_ttl, + self._name, + missing_types, + 0.0, + ) + + def get_address_and_nsec_records(self, override_ttl: Optional[int] = None) -> Set[DNSRecord]: + """Build a set of address records and NSEC records for non-present record types.""" + return self._get_address_and_nsec_records(override_ttl) + + def _get_address_and_nsec_records(self, override_ttl: Optional[int]) -> Set[DNSRecord]: + """Build a set of address records and NSEC records for non-present record types.""" + cacheable = override_ttl is None + if self._get_address_and_nsec_records_cache is not None and cacheable: + return self._get_address_and_nsec_records_cache + missing_types: Set[int] = _ADDRESS_RECORD_TYPES.copy() + records: Set[DNSRecord] = set() + for dns_address in self._dns_addresses(override_ttl, IPVersion.All): + missing_types.discard(dns_address.type) + records.add(dns_address) + if missing_types: + assert self.server is not None, "Service server must be set for NSEC record." + records.add(self._dns_nsec(list(missing_types), override_ttl)) + if cacheable: + self._get_address_and_nsec_records_cache = records + return records + + def _get_address_records_from_cache_by_type(self, zc: "Zeroconf", _type: int_) -> List[DNSAddress]: + """Get the addresses from the cache.""" + if self.server_key is None: + return [] + cache = zc.cache + if TYPE_CHECKING: + records = cast( + "List[DNSAddress]", + cache.get_all_by_details(self.server_key, _type, _CLASS_IN), + ) + else: + records = cache.get_all_by_details(self.server_key, _type, _CLASS_IN) + return records + + def set_server_if_missing(self) -> None: + """Set the server if it is missing. + + This function is for backwards compatibility. + """ + if self.server is None: + self.server = self._name + self.server_key = self.key + + def load_from_cache(self, zc: "Zeroconf", now: Optional[float_] = None) -> bool: + """Populate the service info from the cache. + + This method is designed to be threadsafe. + """ + return self._load_from_cache(zc, now or current_time_millis()) + + def _load_from_cache(self, zc: "Zeroconf", now: float_) -> bool: + """Populate the service info from the cache. + + This method is designed to be threadsafe. + """ + cache = zc.cache + original_server_key = self.server_key + cached_srv_record = cache.get_by_details(self._name, _TYPE_SRV, _CLASS_IN) + if cached_srv_record: + self._process_record_threadsafe(zc, cached_srv_record, now) + cached_txt_record = cache.get_by_details(self._name, _TYPE_TXT, _CLASS_IN) + if cached_txt_record: + self._process_record_threadsafe(zc, cached_txt_record, now) + if original_server_key == self.server_key: + # If there is a srv which changes the server_key, + # A and AAAA will already be loaded from the cache + # and we do not want to do it twice + for record in self._get_address_records_from_cache_by_type(zc, _TYPE_A): + self._process_record_threadsafe(zc, record, now) + for record in self._get_address_records_from_cache_by_type(zc, _TYPE_AAAA): + self._process_record_threadsafe(zc, record, now) + return self._is_complete + + @property + def _is_complete(self) -> bool: + """The ServiceInfo has all expected properties.""" + return bool(self.text is not None and (self._ipv4_addresses or self._ipv6_addresses)) + + def request( + self, + zc: "Zeroconf", + timeout: float, + question_type: Optional[DNSQuestionType] = None, + addr: Optional[str] = None, + port: int = _MDNS_PORT, + ) -> bool: + """Returns true if the service could be discovered on the + network, and updates this object with details discovered. + + While it is not expected during normal operation, + this function may raise EventLoopBlocked if the underlying + call to `async_request` cannot be completed. + + :param zc: Zeroconf instance + :param timeout: time in milliseconds to wait for a response + :param question_type: question type to ask + :param addr: address to send the request to + :param port: port to send the request to + """ + assert zc.loop is not None, "Zeroconf instance must have a loop, was it not started?" + assert zc.loop.is_running(), "Zeroconf instance loop must be running, was it already stopped?" + if zc.loop == get_running_loop(): + raise RuntimeError("Use AsyncServiceInfo.async_request from the event loop") + return bool( + run_coro_with_timeout( + self.async_request(zc, timeout, question_type, addr, port), + zc.loop, + timeout, + ) + ) + + def _get_initial_delay(self) -> float_: + return _LISTENER_TIME + + def _get_random_delay(self) -> int_: + return randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) + + async def async_request( + self, + zc: "Zeroconf", + timeout: float, + question_type: Optional[DNSQuestionType] = None, + addr: Optional[str] = None, + port: int = _MDNS_PORT, + ) -> bool: + """Returns true if the service could be discovered on the + network, and updates this object with details discovered. + + This method will be run in the event loop. + + Passing addr and port is optional, and will default to the + mDNS multicast address and port. This is useful for directing + requests to a specific host that may be able to respond across + subnets. + + :param zc: Zeroconf instance + :param timeout: time in milliseconds to wait for a response + :param question_type: question type to ask + :param addr: address to send the request to + :param port: port to send the request to + """ + if not zc.started: + await zc.async_wait_for_start() + + now = current_time_millis() + + if self._load_from_cache(zc, now): + return True + + if TYPE_CHECKING: + assert zc.loop is not None + + first_request = True + delay = self._get_initial_delay() + next_ = now + last = now + timeout + try: + zc.async_add_listener(self, None) + while not self._is_complete: + if last <= now: + return False + if next_ <= now: + this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION + out = self._generate_request_query(zc, now, this_question_type) + first_request = False + if out.questions: + # All questions may have been suppressed + # by the question history, so nothing to send, + # but keep waiting for answers in case another + # client on the network is asking the same + # question or they have not arrived yet. + zc.async_send(out, addr, port) + next_ = now + delay + next_ += self._get_random_delay() + if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: + # If we just asked a QM question, we need to + # wait at least the duplicate question interval + # before asking another QM question otherwise + # its likely to be suppressed by the question + # history of the remote responder. + delay = _DUPLICATE_QUESTION_INTERVAL + + await self.async_wait(min(next_, last) - now, zc.loop) + now = current_time_millis() + finally: + zc.async_remove_listener(self) + + return True + + def _add_question_with_known_answers( + self, + out: DNSOutgoing, + qu_question: bool, + question_history: QuestionHistory, + cache: DNSCache, + now: float_, + name: str_, + type_: int_, + class_: int_, + skip_if_known_answers: bool, + ) -> None: + """Add a question with known answers if its not suppressed.""" + known_answers = { + answer for answer in cache.get_all_by_details(name, type_, class_) if not answer.is_stale(now) + } + if skip_if_known_answers and known_answers: + return + question = DNSQuestion(name, type_, class_) + if qu_question: + question.unicast = True + elif question_history.suppresses(question, now, known_answers): + return + else: + question_history.add_question_at_time(question, now, known_answers) + out.add_question(question) + for answer in known_answers: + out.add_answer_at_time(answer, now) + + def _generate_request_query( + self, zc: "Zeroconf", now: float_, question_type: DNSQuestionType + ) -> DNSOutgoing: + """Generate the request query.""" + out = DNSOutgoing(_FLAGS_QR_QUERY) + name = self._name + server = self.server or name + cache = zc.cache + history = zc.question_history + qu_question = question_type is QU_QUESTION + self._add_question_with_known_answers( + out, qu_question, history, cache, now, name, _TYPE_SRV, _CLASS_IN, True + ) + self._add_question_with_known_answers( + out, qu_question, history, cache, now, name, _TYPE_TXT, _CLASS_IN, True + ) + self._add_question_with_known_answers( + out, qu_question, history, cache, now, server, _TYPE_A, _CLASS_IN, False + ) + self._add_question_with_known_answers( + out, qu_question, history, cache, now, server, _TYPE_AAAA, _CLASS_IN, False + ) + return out + + def __repr__(self) -> str: + """String representation""" + return "{}({})".format( + type(self).__name__, + ", ".join( + f"{name}={getattr(self, name)!r}" + for name in ( + "type", + "name", + "addresses", + "port", + "weight", + "priority", + "server", + "properties", + "interface_index", + ) + ), + ) + + +class AsyncServiceInfo(ServiceInfo): + """An async version of ServiceInfo.""" From 671f2b5ca35038984aa9807803b12ced9d8b1cde Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 13 Nov 2024 16:55:34 -0800 Subject: [PATCH 70/75] service info refactor --- src/python_testing/TC_SC_000.py | 23 - src/python_testing/TC_SC_4_3.py | 1 + .../mdns_discovery/mdns_async_service_info.py | 169 +-- .../mdns_discovery/mdns_discovery.py | 6 +- .../mdns_discovery/service_info_base.py | 959 ------------------ 5 files changed, 94 insertions(+), 1064 deletions(-) delete mode 100644 src/python_testing/TC_SC_000.py delete mode 100644 src/python_testing/mdns_discovery/service_info_base.py diff --git a/src/python_testing/TC_SC_000.py b/src/python_testing/TC_SC_000.py deleted file mode 100644 index b1aae5126b9a37..00000000000000 --- a/src/python_testing/TC_SC_000.py +++ /dev/null @@ -1,23 +0,0 @@ -from chip.testing.matter_testing import MatterBaseTest, async_test_body, default_matter_test_main -from mdns_discovery.mdns_discovery import DNSRecordType, MdnsDiscovery, MdnsServiceType - -class TC_SC_000(MatterBaseTest): - - @async_test_body - async def test_TC_SC_000(self): - node_id = self.dut_node_id - compressed_fabric_id = self.default_controller.GetCompressedFabricId() - instance_name = f'{compressed_fabric_id:016X}-{node_id:016X}' - instance_qname = f"{instance_name}.{MdnsServiceType.OPERATIONAL.value}" - mdns = MdnsDiscovery() - - await mdns.get_service_by_record_type( - service_name=instance_qname, - service_type=MdnsServiceType.OPERATIONAL.value, - record_type=DNSRecordType.TXT, - log_output=True - ) - - -if __name__ == "__main__": - default_matter_test_main() diff --git a/src/python_testing/TC_SC_4_3.py b/src/python_testing/TC_SC_4_3.py index b495066d654a72..e0ce02d2a58398 100644 --- a/src/python_testing/TC_SC_4_3.py +++ b/src/python_testing/TC_SC_4_3.py @@ -278,6 +278,7 @@ async def test_TC_SC_4_3(self): quada_record = await mdns.get_service_by_record_type( service_name=hostname, + service_type=MdnsServiceType.OPERATIONAL.value, record_type=DNSRecordType.AAAA, log_output=True ) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 0406b3db256cdc..3228193d094864 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -16,28 +16,20 @@ # +import asyncio import enum -from typing import TYPE_CHECKING, Optional - -from zeroconf import (DNSOutgoing, DNSQuestion, DNSQuestionType, Zeroconf, current_time_millis) -from zeroconf.const import (_CLASS_IN, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, +from ipaddress import IPv4Address, IPv6Address +from random import randint +from typing import TYPE_CHECKING, Dict, List, Optional, Set + +from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, + DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) +from zeroconf._utils.net import _encode_address +from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) -# Import from zeroconf blows up, import from clone class works :\ -# ▼ ▼ ▼ ▼ ▼ - -# from zeroconf import ServiceInfo -from mdns_discovery.service_info_base import ServiceInfo - - -int_ = int -float_ = float -str_ = str - - -QU_QUESTION = DNSQuestionType.QU -QM_QUESTION = DNSQuestionType.QM +_AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) @enum.unique @@ -57,12 +49,57 @@ class DNSRecordType(enum.Enum): class MdnsAsyncServiceInfo(ServiceInfo): - def __init__(self, zc: 'Zeroconf', *args, **kwargs): - super().__init__(*args, **kwargs) - self._zc = zc + def __init__( + self, + name: str, + type_: str, + port: Optional[int] = None, + weight: int = 0, + priority: int = 0, + server: Optional[str] = None, + host_ttl: int = _DNS_HOST_TTL, + other_ttl: int = _DNS_OTHER_TTL, + *, + addresses: Optional[List[bytes]] = None, + parsed_addresses: Optional[List[str]] = None, + interface_index: Optional[int] = None, + ) -> None: + # Accept both none, or one, but not both. + if addresses is not None and parsed_addresses is not None: + raise TypeError("addresses and parsed_addresses cannot be provided together") + + if type_ and not type_.endswith(service_type_name(name, strict=False)): + raise BadTypeInNameException + + self.interface_index = interface_index + self._name = name + self.type = type_ + self.key = name.lower() + self._ipv4_addresses: List[IPv4Address] = [] + self._ipv6_addresses: List[IPv6Address] = [] + if addresses is not None: + self.addresses = addresses + elif parsed_addresses is not None: + self.addresses = [_encode_address(a) for a in parsed_addresses] + self.port = port + self.weight = weight + self.priority = priority + self.server = server if server else None + self.server_key = server.lower() if server else None + self._properties: Optional[Dict[bytes, Optional[bytes]]] = None + self._decoded_properties: Optional[Dict[str, Optional[str]]] = None + self.host_ttl = host_ttl + self.other_ttl = other_ttl + self._new_records_futures: Optional[Set[asyncio.Future]] = None + self._dns_address_cache: Optional[List[DNSAddress]] = None + self._dns_pointer_cache: Optional[DNSPointer] = None + self._dns_service_cache: Optional[DNSService] = None + self._dns_text_cache: Optional[DNSText] = None + self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None async def async_request( self, + zc: Zeroconf, timeout: float, question_type: Optional[DNSQuestionType] = None, addr: Optional[str] = None, @@ -79,90 +116,62 @@ async def async_request( requests to a specific host that may be able to respond across subnets. """ - if not self._zc.started: - await self._zc.async_wait_for_start() + if not zc.started: + await zc.async_wait_for_start() now = current_time_millis() if TYPE_CHECKING: - assert self._zc.loop is not None + assert zc.loop is not None first_request = True - delay = self._get_initial_delay() + delay = _LISTENER_TIME next_ = now last = now + timeout try: - self._zc.async_add_listener(self, None) + zc.async_add_listener(self, None) while not self._is_complete: if last <= now: return False if next_ <= now: - this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION + this_question_type = question_type or DNSQuestionType.QU if first_request else DNSQuestionType.QM out: DNSOutgoing = self._generate_request_query(this_question_type, record_type) first_request = False + if out.questions: - # All questions may have been suppressed - # by the question history, so nothing to send, - # but keep waiting for answers in case another - # client on the network is asking the same - # question or they have not arrived yet. - self._zc.async_send(out, addr, port) + zc.async_send(out, addr, port) next_ = now + delay - next_ += self._get_random_delay() - if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: - # If we just asked a QM question, we need to - # wait at least the duplicate question interval - # before asking another QM question otherwise - # its likely to be suppressed by the question - # history of the remote responder. + next_ += randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) + + if this_question_type is DNSQuestionType.QM and delay < _DUPLICATE_QUESTION_INTERVAL: delay = _DUPLICATE_QUESTION_INTERVAL - await self.async_wait(min(next_, last) - now, self._zc.loop) + await self.async_wait(min(next_, last) - now, zc.loop) now = current_time_millis() finally: - self._zc.async_remove_listener(self) + zc.async_remove_listener(self) return True - def _generate_request_query( - self, question_type: DNSQuestionType, record_type: DNSRecordType - ) -> DNSOutgoing: + def _generate_request_query(self, question_type: DNSQuestionType, record_type: DNSRecordType) -> DNSOutgoing: """Generate the request query.""" out = DNSOutgoing(_FLAGS_QR_QUERY) name = self._name - server = self.server or name - qu_question = question_type is QU_QUESTION - if record_type is None or record_type is DNSRecordType.SRV: - print("Requesting MDNS SRV record...") - self._add_question( - out, qu_question, server, _TYPE_SRV, _CLASS_IN - ) - if record_type is None or record_type is DNSRecordType.TXT: - print("Requesting MDNS TXT record...") - self._add_question( - out, qu_question, server, _TYPE_TXT, _CLASS_IN - ) - if record_type is None or record_type is DNSRecordType.A: - print("Requesting MDNS A record...") - self._add_question( - out, qu_question, server, _TYPE_A, _CLASS_IN - ) - if record_type is None or record_type is DNSRecordType.AAAA: - print("Requesting MDNS AAAA record...") - self._add_question( - out, qu_question, server, _TYPE_AAAA, _CLASS_IN - ) - return out + qu_question = question_type is DNSQuestionType.QU + + record_types = { + DNSRecordType.SRV: (_TYPE_SRV, "Requesting MDNS SRV record..."), + DNSRecordType.TXT: (_TYPE_TXT, "Requesting MDNS TXT record..."), + DNSRecordType.A: (_TYPE_A, "Requesting MDNS A record..."), + DNSRecordType.AAAA: (_TYPE_AAAA, "Requesting MDNS AAAA record..."), + } + + # Iterate over record types, add question uppon match + for r_type, (type_const, message) in record_types.items(): + if record_type is None or record_type == r_type: + print(message) + question = DNSQuestion(name, type_const, _CLASS_IN) + question.unicast = qu_question + out.add_question(question) - def _add_question( - self, - out: DNSOutgoing, - qu_question: bool, - name: str_, - type_: int_, - class_: int_ - ) -> None: - """Add a question.""" - question = DNSQuestion(name, type_, class_) - question.unicast = qu_question - out.add_question(question) + return out diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index cc3d7c8e823055..c006cf26d94399 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -303,12 +303,14 @@ async def get_service_by_record_type(self, service_name: str, self._zc.remove_service_listener(service_listener) # Prepare and perform query - service_info = MdnsAsyncServiceInfo(self._zc, name=service_name, type_=service_type) + service_info = MdnsAsyncServiceInfo(name=service_name, type_=service_type) is_discovered = await service_info.async_request( + self._zc, 3000, record_type=record_type) - if not service_type: + # if not service_type: + if record_type in [DNSRecordType.A, DNSRecordType.AAAA]: # Service type not supplied so we can # query against the target/server for protocols in self._zc.engine.protocols: diff --git a/src/python_testing/mdns_discovery/service_info_base.py b/src/python_testing/mdns_discovery/service_info_base.py deleted file mode 100644 index 0a907cf93a17dc..00000000000000 --- a/src/python_testing/mdns_discovery/service_info_base.py +++ /dev/null @@ -1,959 +0,0 @@ -"""Multicast DNS Service Discovery for Python, v0.14-wmcbrine -Copyright 2003 Paul Scott-Murphy, 2014 William McBrine - -This module provides a framework for the use of DNS Service Discovery -using IP multicast. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -USA -""" - -import asyncio -import random -import sys -from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union, cast - -from zeroconf._cache import DNSCache -from zeroconf._dns import ( - DNSAddress, - DNSNsec, - DNSPointer, - DNSQuestion, - DNSQuestionType, - DNSRecord, - DNSService, - DNSText, -) -from zeroconf._exceptions import BadTypeInNameException -from zeroconf._history import QuestionHistory -from zeroconf._logger import log -from zeroconf._protocol.outgoing import DNSOutgoing -from zeroconf._record_update import RecordUpdate -from zeroconf._updates import RecordUpdateListener -from zeroconf._utils.asyncio import ( - _resolve_all_futures_to_none, - get_running_loop, - run_coro_with_timeout, - wait_for_future_set_or_timeout, -) -from zeroconf._utils.ipaddress import ( - ZeroconfIPv4Address, - ZeroconfIPv6Address, - cached_ip_addresses, - get_ip_address_object_from_record, - ip_bytes_and_scope_to_address, - str_without_scope_id, -) -from zeroconf._utils.name import service_type_name -from zeroconf._utils.net import IPVersion, _encode_address -from zeroconf._utils.time import current_time_millis -from zeroconf.const import ( - _ADDRESS_RECORD_TYPES, - _CLASS_IN, - _CLASS_IN_UNIQUE, - _DNS_HOST_TTL, - _DNS_OTHER_TTL, - _DUPLICATE_QUESTION_INTERVAL, - _FLAGS_QR_QUERY, - _LISTENER_TIME, - _MDNS_PORT, - _TYPE_A, - _TYPE_AAAA, - _TYPE_NSEC, - _TYPE_PTR, - _TYPE_SRV, - _TYPE_TXT, -) - -IPADDRESS_SUPPORTS_SCOPE_ID = sys.version_info >= (3, 9, 0) - -_IPVersion_All_value = IPVersion.All.value -_IPVersion_V4Only_value = IPVersion.V4Only.value -# https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 -# The most common case for calling ServiceInfo is from a -# ServiceBrowser. After the first request we add a few random -# milliseconds to the delay between requests to reduce the chance -# that there are multiple ServiceBrowser callbacks running on -# the network that are firing at the same time when they -# see the same multicast response and decide to refresh -# the A/AAAA/SRV records for a host. -_AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) - -bytes_ = bytes -float_ = float -int_ = int -str_ = str - -QU_QUESTION = DNSQuestionType.QU -QM_QUESTION = DNSQuestionType.QM - -randint = random.randint - -if TYPE_CHECKING: - from .._core import Zeroconf - - -def instance_name_from_service_info(info: "ServiceInfo", strict: bool = True) -> str: - """Calculate the instance name from the ServiceInfo.""" - # This is kind of funky because of the subtype based tests - # need to make subtypes a first class citizen - service_name = service_type_name(info.name, strict=strict) - if not info.type.endswith(service_name): - raise BadTypeInNameException - return info.name[: -len(service_name) - 1] - - -class ServiceInfo(RecordUpdateListener): - """Service information. - - Constructor parameters are as follows: - - * `type_`: fully qualified service type name - * `name`: fully qualified service name - * `port`: port that the service runs on - * `weight`: weight of the service - * `priority`: priority of the service - * `properties`: dictionary of properties (or a bytes object holding the contents of the `text` field). - converted to str and then encoded to bytes using UTF-8. Keys with `None` values are converted to - value-less attributes. - * `server`: fully qualified name for service host (defaults to name) - * `host_ttl`: ttl used for A/SRV records - * `other_ttl`: ttl used for PTR/TXT records - * `addresses` and `parsed_addresses`: List of IP addresses (either as bytes, network byte order, - or in parsed form as text; at most one of those parameters can be provided) - * interface_index: scope_id or zone_id for IPv6 link-local addresses i.e. an identifier of the interface - where the peer is connected to - """ - - __slots__ = ( - "text", - "type", - "_name", - "key", - "_ipv4_addresses", - "_ipv6_addresses", - "port", - "weight", - "priority", - "server", - "server_key", - "_properties", - "_decoded_properties", - "host_ttl", - "other_ttl", - "interface_index", - "_new_records_futures", - "_dns_pointer_cache", - "_dns_service_cache", - "_dns_text_cache", - "_dns_address_cache", - "_get_address_and_nsec_records_cache", - ) - - def __init__( - self, - type_: str, - name: str, - port: Optional[int] = None, - weight: int = 0, - priority: int = 0, - properties: Union[bytes, Dict] = b"", - server: Optional[str] = None, - host_ttl: int = _DNS_HOST_TTL, - other_ttl: int = _DNS_OTHER_TTL, - *, - addresses: Optional[List[bytes]] = None, - parsed_addresses: Optional[List[str]] = None, - interface_index: Optional[int] = None, - ) -> None: - # Accept both none, or one, but not both. - if addresses is not None and parsed_addresses is not None: - raise TypeError("addresses and parsed_addresses cannot be provided together") - if not type_.endswith(service_type_name(name, strict=False)): - raise BadTypeInNameException - self.interface_index = interface_index - self.text = b"" - self.type = type_ - self._name = name - self.key = name.lower() - self._ipv4_addresses: List[ZeroconfIPv4Address] = [] - self._ipv6_addresses: List[ZeroconfIPv6Address] = [] - if addresses is not None: - self.addresses = addresses - elif parsed_addresses is not None: - self.addresses = [_encode_address(a) for a in parsed_addresses] - self.port = port - self.weight = weight - self.priority = priority - self.server = server if server else None - self.server_key = server.lower() if server else None - self._properties: Optional[Dict[bytes, Optional[bytes]]] = None - self._decoded_properties: Optional[Dict[str, Optional[str]]] = None - if isinstance(properties, bytes): - self._set_text(properties) - else: - self._set_properties(properties) - self.host_ttl = host_ttl - self.other_ttl = other_ttl - self._new_records_futures: Optional[Set[asyncio.Future]] = None - self._dns_address_cache: Optional[List[DNSAddress]] = None - self._dns_pointer_cache: Optional[DNSPointer] = None - self._dns_service_cache: Optional[DNSService] = None - self._dns_text_cache: Optional[DNSText] = None - self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None - - @property - def name(self) -> str: - """The name of the service.""" - return self._name - - @name.setter - def name(self, name: str) -> None: - """Replace the name and reset the key.""" - self._name = name - self.key = name.lower() - self._dns_service_cache = None - self._dns_pointer_cache = None - self._dns_text_cache = None - - @property - def addresses(self) -> List[bytes]: - """IPv4 addresses of this service. - - Only IPv4 addresses are returned for backward compatibility. - Use :meth:`addresses_by_version` or :meth:`parsed_addresses` to - include IPv6 addresses as well. - """ - return self.addresses_by_version(IPVersion.V4Only) - - @addresses.setter - def addresses(self, value: List[bytes]) -> None: - """Replace the addresses list. - - This replaces all currently stored addresses, both IPv4 and IPv6. - """ - self._ipv4_addresses.clear() - self._ipv6_addresses.clear() - self._dns_address_cache = None - self._get_address_and_nsec_records_cache = None - - for address in value: - if IPADDRESS_SUPPORTS_SCOPE_ID and len(address) == 16 and self.interface_index is not None: - addr = ip_bytes_and_scope_to_address(address, self.interface_index) - else: - addr = cached_ip_addresses(address) - if addr is None: - raise TypeError( - "Addresses must either be IPv4 or IPv6 strings, bytes, or integers;" - f" got {address!r}. Hint: convert string addresses with socket.inet_pton" - ) - if addr.version == 4: - if TYPE_CHECKING: - assert isinstance(addr, ZeroconfIPv4Address) - self._ipv4_addresses.append(addr) - else: - if TYPE_CHECKING: - assert isinstance(addr, ZeroconfIPv6Address) - self._ipv6_addresses.append(addr) - - @property - def properties(self) -> Dict[bytes, Optional[bytes]]: - """Return properties as bytes.""" - if self._properties is None: - self._unpack_text_into_properties() - if TYPE_CHECKING: - assert self._properties is not None - return self._properties - - @property - def decoded_properties(self) -> Dict[str, Optional[str]]: - """Return properties as strings.""" - if self._decoded_properties is None: - self._generate_decoded_properties() - if TYPE_CHECKING: - assert self._decoded_properties is not None - return self._decoded_properties - - def async_clear_cache(self) -> None: - """Clear the cache for this service info.""" - self._dns_address_cache = None - self._dns_pointer_cache = None - self._dns_service_cache = None - self._dns_text_cache = None - self._get_address_and_nsec_records_cache = None - - async def async_wait(self, timeout: float, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: - """Calling task waits for a given number of milliseconds or until notified.""" - if not self._new_records_futures: - self._new_records_futures = set() - await wait_for_future_set_or_timeout( - loop or asyncio.get_running_loop(), self._new_records_futures, timeout - ) - - def addresses_by_version(self, version: IPVersion) -> List[bytes]: - """List addresses matching IP version. - - Addresses are guaranteed to be returned in LIFO (last in, first out) - order with IPv4 addresses first and IPv6 addresses second. - - This means the first address will always be the most recently added - address of the given IP version. - """ - version_value = version.value - if version_value == _IPVersion_All_value: - ip_v4_packed = [addr.packed for addr in self._ipv4_addresses] - ip_v6_packed = [addr.packed for addr in self._ipv6_addresses] - return [*ip_v4_packed, *ip_v6_packed] - if version_value == _IPVersion_V4Only_value: - return [addr.packed for addr in self._ipv4_addresses] - return [addr.packed for addr in self._ipv6_addresses] - - def ip_addresses_by_version( - self, version: IPVersion - ) -> Union[List[ZeroconfIPv4Address], List[ZeroconfIPv6Address]]: - """List ip_address objects matching IP version. - - Addresses are guaranteed to be returned in LIFO (last in, first out) - order with IPv4 addresses first and IPv6 addresses second. - - This means the first address will always be the most recently added - address of the given IP version. - """ - return self._ip_addresses_by_version_value(version.value) - - def _ip_addresses_by_version_value( - self, version_value: int_ - ) -> Union[List[ZeroconfIPv4Address], List[ZeroconfIPv6Address]]: - """Backend for addresses_by_version that uses the raw value.""" - if version_value == _IPVersion_All_value: - return [*self._ipv4_addresses, *self._ipv6_addresses] # type: ignore[return-value] - if version_value == _IPVersion_V4Only_value: - return self._ipv4_addresses - return self._ipv6_addresses - - def parsed_addresses(self, version: IPVersion = IPVersion.All) -> List[str]: - """List addresses in their parsed string form. - - Addresses are guaranteed to be returned in LIFO (last in, first out) - order with IPv4 addresses first and IPv6 addresses second. - - This means the first address will always be the most recently added - address of the given IP version. - """ - return [str_without_scope_id(addr) for addr in self._ip_addresses_by_version_value(version.value)] - - def parsed_scoped_addresses(self, version: IPVersion = IPVersion.All) -> List[str]: - """Equivalent to parsed_addresses, with the exception that IPv6 Link-Local - addresses are qualified with % when available - - Addresses are guaranteed to be returned in LIFO (last in, first out) - order with IPv4 addresses first and IPv6 addresses second. - - This means the first address will always be the most recently added - address of the given IP version. - """ - return [str(addr) for addr in self._ip_addresses_by_version_value(version.value)] - - def _set_properties(self, properties: Dict[Union[str, bytes], Optional[Union[str, bytes]]]) -> None: - """Sets properties and text of this info from a dictionary""" - list_: List[bytes] = [] - properties_contain_str = False - result = b"" - for key, value in properties.items(): - if isinstance(key, str): - key = key.encode("utf-8") - properties_contain_str = True - - record = key - if value is not None: - if not isinstance(value, bytes): - value = str(value).encode("utf-8") - properties_contain_str = True - record += b"=" + value - list_.append(record) - for item in list_: - result = b"".join((result, bytes((len(item),)), item)) - if not properties_contain_str: - # If there are no str keys or values, we can use the properties - # as-is, without decoding them, otherwise calling - # self.properties will lazy decode them, which is expensive. - if TYPE_CHECKING: - self._properties = cast("Dict[bytes, Optional[bytes]]", properties) - else: - self._properties = properties - self.text = result - - def _set_text(self, text: bytes) -> None: - """Sets properties and text given a text field""" - if text == self.text: - return - self.text = text - # Clear the properties cache - self._properties = None - self._decoded_properties = None - - def _generate_decoded_properties(self) -> None: - """Generates decoded properties from the properties""" - self._decoded_properties = { - k.decode("ascii", "replace"): None if v is None else v.decode("utf-8", "replace") - for k, v in self.properties.items() - } - - def _unpack_text_into_properties(self) -> None: - """Unpacks the text field into properties""" - text = self.text - end = len(text) - if end == 0: - # Properties should be set atomically - # in case another thread is reading them - self._properties = {} - return - - index = 0 - properties: Dict[bytes, Optional[bytes]] = {} - while index < end: - length = text[index] - index += 1 - key_value = text[index : index + length] - key_sep_value = key_value.partition(b"=") - key = key_sep_value[0] - if key not in properties: - properties[key] = key_sep_value[2] or None - index += length - - self._properties = properties - - def get_name(self) -> str: - """Name accessor""" - return self._name[: len(self._name) - len(self.type) - 1] - - def _get_ip_addresses_from_cache_lifo( - self, zc: "Zeroconf", now: float_, type: int_ - ) -> List[Union[ZeroconfIPv4Address, ZeroconfIPv6Address]]: - """Set IPv6 addresses from the cache.""" - address_list: List[Union[ZeroconfIPv4Address, ZeroconfIPv6Address]] = [] - for record in self._get_address_records_from_cache_by_type(zc, type): - if record.is_expired(now): - continue - ip_addr = get_ip_address_object_from_record(record) - if ip_addr is not None and ip_addr not in address_list: - address_list.append(ip_addr) - address_list.reverse() # Reverse to get LIFO order - return address_list - - def _set_ipv6_addresses_from_cache(self, zc: "Zeroconf", now: float_) -> None: - """Set IPv6 addresses from the cache.""" - if TYPE_CHECKING: - self._ipv6_addresses = cast( - "List[ZeroconfIPv6Address]", - self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_AAAA), - ) - else: - self._ipv6_addresses = self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_AAAA) - - def _set_ipv4_addresses_from_cache(self, zc: "Zeroconf", now: float_) -> None: - """Set IPv4 addresses from the cache.""" - if TYPE_CHECKING: - self._ipv4_addresses = cast( - "List[ZeroconfIPv4Address]", - self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_A), - ) - else: - self._ipv4_addresses = self._get_ip_addresses_from_cache_lifo(zc, now, _TYPE_A) - - def async_update_records(self, zc: "Zeroconf", now: float_, records: List[RecordUpdate]) -> None: - """Updates service information from a DNS record. - - This method will be run in the event loop. - """ - new_records_futures = self._new_records_futures - updated: bool = False - for record_update in records: - updated |= self._process_record_threadsafe(zc, record_update.new, now) - if updated and new_records_futures: - _resolve_all_futures_to_none(new_records_futures) - - def _process_record_threadsafe(self, zc: "Zeroconf", record: DNSRecord, now: float_) -> bool: - """Thread safe record updating. - - Returns True if a new record was added. - """ - if record.is_expired(now): - return False - - record_key = record.key - record_type = type(record) - if record_type is DNSAddress and record_key == self.server_key: - dns_address_record = record - if TYPE_CHECKING: - assert isinstance(dns_address_record, DNSAddress) - ip_addr = get_ip_address_object_from_record(dns_address_record) - if ip_addr is None: - log.warning( - "Encountered invalid address while processing %s: %s", - dns_address_record, - dns_address_record.address, - ) - return False - - if ip_addr.version == 4: - if TYPE_CHECKING: - assert isinstance(ip_addr, ZeroconfIPv4Address) - ipv4_addresses = self._ipv4_addresses - if ip_addr not in ipv4_addresses: - ipv4_addresses.insert(0, ip_addr) - return True - # Use int() to compare the addresses as integers - # since by default IPv4Address.__eq__ compares the - # the addresses on version and int which more than - # we need here since we know the version is 4. - elif ip_addr.zc_integer != ipv4_addresses[0].zc_integer: - ipv4_addresses.remove(ip_addr) - ipv4_addresses.insert(0, ip_addr) - - return False - - if TYPE_CHECKING: - assert isinstance(ip_addr, ZeroconfIPv6Address) - ipv6_addresses = self._ipv6_addresses - if ip_addr not in self._ipv6_addresses: - ipv6_addresses.insert(0, ip_addr) - return True - # Use int() to compare the addresses as integers - # since by default IPv6Address.__eq__ compares the - # the addresses on version and int which more than - # we need here since we know the version is 6. - elif ip_addr.zc_integer != self._ipv6_addresses[0].zc_integer: - ipv6_addresses.remove(ip_addr) - ipv6_addresses.insert(0, ip_addr) - - return False - - if record_key != self.key: - return False - - if record_type is DNSText: - dns_text_record = record - if TYPE_CHECKING: - assert isinstance(dns_text_record, DNSText) - self._set_text(dns_text_record.text) - return True - - if record_type is DNSService: - dns_service_record = record - if TYPE_CHECKING: - assert isinstance(dns_service_record, DNSService) - old_server_key = self.server_key - self._name = dns_service_record.name - self.key = dns_service_record.key - self.server = dns_service_record.server - self.server_key = dns_service_record.server_key - self.port = dns_service_record.port - self.weight = dns_service_record.weight - self.priority = dns_service_record.priority - if old_server_key != self.server_key: - self._set_ipv4_addresses_from_cache(zc, now) - self._set_ipv6_addresses_from_cache(zc, now) - return True - - return False - - def dns_addresses( - self, - override_ttl: Optional[int] = None, - version: IPVersion = IPVersion.All, - ) -> List[DNSAddress]: - """Return matching DNSAddress from ServiceInfo.""" - return self._dns_addresses(override_ttl, version) - - def _dns_addresses( - self, - override_ttl: Optional[int], - version: IPVersion, - ) -> List[DNSAddress]: - """Return matching DNSAddress from ServiceInfo.""" - cacheable = version is IPVersion.All and override_ttl is None - if self._dns_address_cache is not None and cacheable: - return self._dns_address_cache - name = self.server or self._name - ttl = override_ttl if override_ttl is not None else self.host_ttl - class_ = _CLASS_IN_UNIQUE - version_value = version.value - records = [ - DNSAddress( - name, - _TYPE_AAAA if ip_addr.version == 6 else _TYPE_A, - class_, - ttl, - ip_addr.packed, - created=0.0, - ) - for ip_addr in self._ip_addresses_by_version_value(version_value) - ] - if cacheable: - self._dns_address_cache = records - return records - - def dns_pointer(self, override_ttl: Optional[int] = None) -> DNSPointer: - """Return DNSPointer from ServiceInfo.""" - return self._dns_pointer(override_ttl) - - def _dns_pointer(self, override_ttl: Optional[int]) -> DNSPointer: - """Return DNSPointer from ServiceInfo.""" - cacheable = override_ttl is None - if self._dns_pointer_cache is not None and cacheable: - return self._dns_pointer_cache - record = DNSPointer( - self.type, - _TYPE_PTR, - _CLASS_IN, - override_ttl if override_ttl is not None else self.other_ttl, - self._name, - 0.0, - ) - if cacheable: - self._dns_pointer_cache = record - return record - - def dns_service(self, override_ttl: Optional[int] = None) -> DNSService: - """Return DNSService from ServiceInfo.""" - return self._dns_service(override_ttl) - - def _dns_service(self, override_ttl: Optional[int]) -> DNSService: - """Return DNSService from ServiceInfo.""" - cacheable = override_ttl is None - if self._dns_service_cache is not None and cacheable: - return self._dns_service_cache - port = self.port - if TYPE_CHECKING: - assert isinstance(port, int) - record = DNSService( - self._name, - _TYPE_SRV, - _CLASS_IN_UNIQUE, - override_ttl if override_ttl is not None else self.host_ttl, - self.priority, - self.weight, - port, - self.server or self._name, - 0.0, - ) - if cacheable: - self._dns_service_cache = record - return record - - def dns_text(self, override_ttl: Optional[int] = None) -> DNSText: - """Return DNSText from ServiceInfo.""" - return self._dns_text(override_ttl) - - def _dns_text(self, override_ttl: Optional[int]) -> DNSText: - """Return DNSText from ServiceInfo.""" - cacheable = override_ttl is None - if self._dns_text_cache is not None and cacheable: - return self._dns_text_cache - record = DNSText( - self._name, - _TYPE_TXT, - _CLASS_IN_UNIQUE, - override_ttl if override_ttl is not None else self.other_ttl, - self.text, - 0.0, - ) - if cacheable: - self._dns_text_cache = record - return record - - def dns_nsec(self, missing_types: List[int], override_ttl: Optional[int] = None) -> DNSNsec: - """Return DNSNsec from ServiceInfo.""" - return self._dns_nsec(missing_types, override_ttl) - - def _dns_nsec(self, missing_types: List[int], override_ttl: Optional[int]) -> DNSNsec: - """Return DNSNsec from ServiceInfo.""" - return DNSNsec( - self._name, - _TYPE_NSEC, - _CLASS_IN_UNIQUE, - override_ttl if override_ttl is not None else self.host_ttl, - self._name, - missing_types, - 0.0, - ) - - def get_address_and_nsec_records(self, override_ttl: Optional[int] = None) -> Set[DNSRecord]: - """Build a set of address records and NSEC records for non-present record types.""" - return self._get_address_and_nsec_records(override_ttl) - - def _get_address_and_nsec_records(self, override_ttl: Optional[int]) -> Set[DNSRecord]: - """Build a set of address records and NSEC records for non-present record types.""" - cacheable = override_ttl is None - if self._get_address_and_nsec_records_cache is not None and cacheable: - return self._get_address_and_nsec_records_cache - missing_types: Set[int] = _ADDRESS_RECORD_TYPES.copy() - records: Set[DNSRecord] = set() - for dns_address in self._dns_addresses(override_ttl, IPVersion.All): - missing_types.discard(dns_address.type) - records.add(dns_address) - if missing_types: - assert self.server is not None, "Service server must be set for NSEC record." - records.add(self._dns_nsec(list(missing_types), override_ttl)) - if cacheable: - self._get_address_and_nsec_records_cache = records - return records - - def _get_address_records_from_cache_by_type(self, zc: "Zeroconf", _type: int_) -> List[DNSAddress]: - """Get the addresses from the cache.""" - if self.server_key is None: - return [] - cache = zc.cache - if TYPE_CHECKING: - records = cast( - "List[DNSAddress]", - cache.get_all_by_details(self.server_key, _type, _CLASS_IN), - ) - else: - records = cache.get_all_by_details(self.server_key, _type, _CLASS_IN) - return records - - def set_server_if_missing(self) -> None: - """Set the server if it is missing. - - This function is for backwards compatibility. - """ - if self.server is None: - self.server = self._name - self.server_key = self.key - - def load_from_cache(self, zc: "Zeroconf", now: Optional[float_] = None) -> bool: - """Populate the service info from the cache. - - This method is designed to be threadsafe. - """ - return self._load_from_cache(zc, now or current_time_millis()) - - def _load_from_cache(self, zc: "Zeroconf", now: float_) -> bool: - """Populate the service info from the cache. - - This method is designed to be threadsafe. - """ - cache = zc.cache - original_server_key = self.server_key - cached_srv_record = cache.get_by_details(self._name, _TYPE_SRV, _CLASS_IN) - if cached_srv_record: - self._process_record_threadsafe(zc, cached_srv_record, now) - cached_txt_record = cache.get_by_details(self._name, _TYPE_TXT, _CLASS_IN) - if cached_txt_record: - self._process_record_threadsafe(zc, cached_txt_record, now) - if original_server_key == self.server_key: - # If there is a srv which changes the server_key, - # A and AAAA will already be loaded from the cache - # and we do not want to do it twice - for record in self._get_address_records_from_cache_by_type(zc, _TYPE_A): - self._process_record_threadsafe(zc, record, now) - for record in self._get_address_records_from_cache_by_type(zc, _TYPE_AAAA): - self._process_record_threadsafe(zc, record, now) - return self._is_complete - - @property - def _is_complete(self) -> bool: - """The ServiceInfo has all expected properties.""" - return bool(self.text is not None and (self._ipv4_addresses or self._ipv6_addresses)) - - def request( - self, - zc: "Zeroconf", - timeout: float, - question_type: Optional[DNSQuestionType] = None, - addr: Optional[str] = None, - port: int = _MDNS_PORT, - ) -> bool: - """Returns true if the service could be discovered on the - network, and updates this object with details discovered. - - While it is not expected during normal operation, - this function may raise EventLoopBlocked if the underlying - call to `async_request` cannot be completed. - - :param zc: Zeroconf instance - :param timeout: time in milliseconds to wait for a response - :param question_type: question type to ask - :param addr: address to send the request to - :param port: port to send the request to - """ - assert zc.loop is not None, "Zeroconf instance must have a loop, was it not started?" - assert zc.loop.is_running(), "Zeroconf instance loop must be running, was it already stopped?" - if zc.loop == get_running_loop(): - raise RuntimeError("Use AsyncServiceInfo.async_request from the event loop") - return bool( - run_coro_with_timeout( - self.async_request(zc, timeout, question_type, addr, port), - zc.loop, - timeout, - ) - ) - - def _get_initial_delay(self) -> float_: - return _LISTENER_TIME - - def _get_random_delay(self) -> int_: - return randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) - - async def async_request( - self, - zc: "Zeroconf", - timeout: float, - question_type: Optional[DNSQuestionType] = None, - addr: Optional[str] = None, - port: int = _MDNS_PORT, - ) -> bool: - """Returns true if the service could be discovered on the - network, and updates this object with details discovered. - - This method will be run in the event loop. - - Passing addr and port is optional, and will default to the - mDNS multicast address and port. This is useful for directing - requests to a specific host that may be able to respond across - subnets. - - :param zc: Zeroconf instance - :param timeout: time in milliseconds to wait for a response - :param question_type: question type to ask - :param addr: address to send the request to - :param port: port to send the request to - """ - if not zc.started: - await zc.async_wait_for_start() - - now = current_time_millis() - - if self._load_from_cache(zc, now): - return True - - if TYPE_CHECKING: - assert zc.loop is not None - - first_request = True - delay = self._get_initial_delay() - next_ = now - last = now + timeout - try: - zc.async_add_listener(self, None) - while not self._is_complete: - if last <= now: - return False - if next_ <= now: - this_question_type = question_type or QU_QUESTION if first_request else QM_QUESTION - out = self._generate_request_query(zc, now, this_question_type) - first_request = False - if out.questions: - # All questions may have been suppressed - # by the question history, so nothing to send, - # but keep waiting for answers in case another - # client on the network is asking the same - # question or they have not arrived yet. - zc.async_send(out, addr, port) - next_ = now + delay - next_ += self._get_random_delay() - if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: - # If we just asked a QM question, we need to - # wait at least the duplicate question interval - # before asking another QM question otherwise - # its likely to be suppressed by the question - # history of the remote responder. - delay = _DUPLICATE_QUESTION_INTERVAL - - await self.async_wait(min(next_, last) - now, zc.loop) - now = current_time_millis() - finally: - zc.async_remove_listener(self) - - return True - - def _add_question_with_known_answers( - self, - out: DNSOutgoing, - qu_question: bool, - question_history: QuestionHistory, - cache: DNSCache, - now: float_, - name: str_, - type_: int_, - class_: int_, - skip_if_known_answers: bool, - ) -> None: - """Add a question with known answers if its not suppressed.""" - known_answers = { - answer for answer in cache.get_all_by_details(name, type_, class_) if not answer.is_stale(now) - } - if skip_if_known_answers and known_answers: - return - question = DNSQuestion(name, type_, class_) - if qu_question: - question.unicast = True - elif question_history.suppresses(question, now, known_answers): - return - else: - question_history.add_question_at_time(question, now, known_answers) - out.add_question(question) - for answer in known_answers: - out.add_answer_at_time(answer, now) - - def _generate_request_query( - self, zc: "Zeroconf", now: float_, question_type: DNSQuestionType - ) -> DNSOutgoing: - """Generate the request query.""" - out = DNSOutgoing(_FLAGS_QR_QUERY) - name = self._name - server = self.server or name - cache = zc.cache - history = zc.question_history - qu_question = question_type is QU_QUESTION - self._add_question_with_known_answers( - out, qu_question, history, cache, now, name, _TYPE_SRV, _CLASS_IN, True - ) - self._add_question_with_known_answers( - out, qu_question, history, cache, now, name, _TYPE_TXT, _CLASS_IN, True - ) - self._add_question_with_known_answers( - out, qu_question, history, cache, now, server, _TYPE_A, _CLASS_IN, False - ) - self._add_question_with_known_answers( - out, qu_question, history, cache, now, server, _TYPE_AAAA, _CLASS_IN, False - ) - return out - - def __repr__(self) -> str: - """String representation""" - return "{}({})".format( - type(self).__name__, - ", ".join( - f"{name}={getattr(self, name)!r}" - for name in ( - "type", - "name", - "addresses", - "port", - "weight", - "priority", - "server", - "properties", - "interface_index", - ) - ), - ) - - -class AsyncServiceInfo(ServiceInfo): - """An async version of ServiceInfo.""" From 837274d910837c3144e5a883203fdd10898b7a1f Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 13 Nov 2024 17:04:12 -0800 Subject: [PATCH 71/75] Fix restyle --- src/python_testing/mdns_discovery/mdns_async_service_info.py | 1 - src/python_testing/mdns_discovery/mdns_discovery.py | 1 - 2 files changed, 2 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 3228193d094864..c8dbb93ea2cb09 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -28,7 +28,6 @@ from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) - _AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) diff --git a/src/python_testing/mdns_discovery/mdns_discovery.py b/src/python_testing/mdns_discovery/mdns_discovery.py index c006cf26d94399..2d7337b622a536 100644 --- a/src/python_testing/mdns_discovery/mdns_discovery.py +++ b/src/python_testing/mdns_discovery/mdns_discovery.py @@ -309,7 +309,6 @@ async def get_service_by_record_type(self, service_name: str, 3000, record_type=record_type) - # if not service_type: if record_type in [DNSRecordType.A, DNSRecordType.AAAA]: # Service type not supplied so we can # query against the target/server From 41ffddc9fbeea30957292e66b55d03fdd87f070e Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 13 Nov 2024 17:07:03 -0800 Subject: [PATCH 72/75] Fix restyle --- src/python_testing/mdns_discovery/mdns_async_service_info.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index c8dbb93ea2cb09..bc7083a3eed84b 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -136,12 +136,12 @@ async def async_request( this_question_type = question_type or DNSQuestionType.QU if first_request else DNSQuestionType.QM out: DNSOutgoing = self._generate_request_query(this_question_type, record_type) first_request = False - + if out.questions: zc.async_send(out, addr, port) next_ = now + delay next_ += randint(*_AVOID_SYNC_DELAY_RANDOM_INTERVAL) - + if this_question_type is DNSQuestionType.QM and delay < _DUPLICATE_QUESTION_INTERVAL: delay = _DUPLICATE_QUESTION_INTERVAL From a3fa1dd20e0e36d699155b57341c1ca0ebb7d8a5 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Thu, 14 Nov 2024 08:38:32 -0800 Subject: [PATCH 73/75] Updates mdns service info init --- .../mdns_discovery/mdns_async_service_info.py | 46 ++----------------- 1 file changed, 4 insertions(+), 42 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index bc7083a3eed84b..7514d4948dcbe5 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -16,16 +16,13 @@ # -import asyncio import enum -from ipaddress import IPv4Address, IPv6Address from random import randint -from typing import TYPE_CHECKING, Dict, List, Optional, Set +from typing import TYPE_CHECKING, Optional -from zeroconf import (BadTypeInNameException, DNSAddress, DNSOutgoing, DNSPointer, DNSQuestion, DNSQuestionType, DNSRecord, - DNSService, DNSText, ServiceInfo, Zeroconf, current_time_millis, service_type_name) +from zeroconf import (BadTypeInNameException, DNSOutgoing, DNSQuestion, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis, service_type_name) from zeroconf._utils.net import _encode_address -from zeroconf.const import (_CLASS_IN, _DNS_HOST_TTL, _DNS_OTHER_TTL, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, +from zeroconf.const import (_CLASS_IN, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) _AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) @@ -51,50 +48,15 @@ class MdnsAsyncServiceInfo(ServiceInfo): def __init__( self, name: str, - type_: str, - port: Optional[int] = None, - weight: int = 0, - priority: int = 0, - server: Optional[str] = None, - host_ttl: int = _DNS_HOST_TTL, - other_ttl: int = _DNS_OTHER_TTL, - *, - addresses: Optional[List[bytes]] = None, - parsed_addresses: Optional[List[str]] = None, - interface_index: Optional[int] = None, + type_: str ) -> None: - # Accept both none, or one, but not both. - if addresses is not None and parsed_addresses is not None: - raise TypeError("addresses and parsed_addresses cannot be provided together") if type_ and not type_.endswith(service_type_name(name, strict=False)): raise BadTypeInNameException - self.interface_index = interface_index self._name = name self.type = type_ self.key = name.lower() - self._ipv4_addresses: List[IPv4Address] = [] - self._ipv6_addresses: List[IPv6Address] = [] - if addresses is not None: - self.addresses = addresses - elif parsed_addresses is not None: - self.addresses = [_encode_address(a) for a in parsed_addresses] - self.port = port - self.weight = weight - self.priority = priority - self.server = server if server else None - self.server_key = server.lower() if server else None - self._properties: Optional[Dict[bytes, Optional[bytes]]] = None - self._decoded_properties: Optional[Dict[str, Optional[str]]] = None - self.host_ttl = host_ttl - self.other_ttl = other_ttl - self._new_records_futures: Optional[Set[asyncio.Future]] = None - self._dns_address_cache: Optional[List[DNSAddress]] = None - self._dns_pointer_cache: Optional[DNSPointer] = None - self._dns_service_cache: Optional[DNSService] = None - self._dns_text_cache: Optional[DNSText] = None - self._get_address_and_nsec_records_cache: Optional[Set[DNSRecord]] = None async def async_request( self, From 78a768acf85164d6f2a15c43bc07abbf6456519b Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Thu, 14 Nov 2024 08:43:00 -0800 Subject: [PATCH 74/75] Fix restyle --- .../mdns_discovery/mdns_async_service_info.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 7514d4948dcbe5..94f25f552dbf02 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -20,10 +20,10 @@ from random import randint from typing import TYPE_CHECKING, Optional -from zeroconf import (BadTypeInNameException, DNSOutgoing, DNSQuestion, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis, service_type_name) -from zeroconf._utils.net import _encode_address -from zeroconf.const import (_CLASS_IN, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, - _MDNS_PORT, _TYPE_A, _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) +from zeroconf import (BadTypeInNameException, DNSOutgoing, DNSQuestion, DNSQuestionType, ServiceInfo, Zeroconf, current_time_millis, + service_type_name) +from zeroconf.const import (_CLASS_IN, _DUPLICATE_QUESTION_INTERVAL, _FLAGS_QR_QUERY, _LISTENER_TIME, _MDNS_PORT, _TYPE_A, + _TYPE_AAAA, _TYPE_SRV, _TYPE_TXT) _AVOID_SYNC_DELAY_RANDOM_INTERVAL = (20, 120) From b48a69020d398b2b9642e65d5976e75abafb0c60 Mon Sep 17 00:00:00 2001 From: Raul Marquez Date: Wed, 20 Nov 2024 16:27:18 -0800 Subject: [PATCH 75/75] Updates MdnsAsyncServiceInfo --- .../mdns_discovery/mdns_async_service_info.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/python_testing/mdns_discovery/mdns_async_service_info.py b/src/python_testing/mdns_discovery/mdns_async_service_info.py index 94f25f552dbf02..61d1dc73ebcb04 100644 --- a/src/python_testing/mdns_discovery/mdns_async_service_info.py +++ b/src/python_testing/mdns_discovery/mdns_async_service_info.py @@ -45,11 +45,8 @@ class DNSRecordType(enum.Enum): class MdnsAsyncServiceInfo(ServiceInfo): - def __init__( - self, - name: str, - type_: str - ) -> None: + def __init__(self, name: str, type_: str) -> None: + super().__init__(type_=type_, name=name) if type_ and not type_.endswith(service_type_name(name, strict=False)): raise BadTypeInNameException