[HVAC] Add check for per-preset-scenario limit (#35310)

* [HVAC] Check if number of preset scenarios exceeds maximum number of scenarios

* [NXP][Zephyr] Provide AP band in connection request parameters (#35181)

Signed-off-by: Axel Le Bourhis <axel.lebourhis@nxp.com>

* Plumbing for CADMIN attribute updates from fabric-admin to fabric-bridge (#35222)

* Fix TC_BRBINFO_4_1 for execution on TH (#35257)

* [Fabric-Admin] Move DeviceSynchronization from pairing command to device_manager (#35260)

* Move DeviceSynchronization from pairing command to device_manager

* Restyled by gn

---------

Co-authored-by: Restyled.io <commits@restyled.io>

* Add command-line argument to allow userprompt at start of ECOINFO_2_1 (#35234)

---------

Co-authored-by: Restyled.io <commits@restyled.io>
Co-authored-by: saurabhst <s.kumar9@samsung.com>

* Testing fixes for TC_SWTCH from TE2 (#34984)

* Testing fixes for TC_SWTCH from TE2

- all-clusters-app was not generating button position
  changes in some cases. This was not detected in some
  situations since the test cases don't always test for this.
- Prompts are missing endpoint ID which makes it hard when running
  per-endpoint tests to know where it applies.
- Some partials could fail on decode errors, causing test errors
  instead of fails.

This PR:

- Adds correct generation of positions on press/release.
- Adds a way to claim endpoint tested in user prompts
- Fixes failing on decode errors in partials

Testing done:

- TC_SWTCH still passes
- Manually validated button position in multi-press test/simulation
  (update to TC_SWTCH needs test plan changes). Issue is in
  all-clusters-app for CI only. See
  https://github.com/CHIP-Specifications/chip-test-plans/issues/4493

* Restyled by autopep8

* Update prompt support

---------

Co-authored-by: Restyled.io <commits@restyled.io>

* Add test cases for testing additional Presets write and commit constr… (#35141)

* Add test cases for testing additional Presets write and commit constraints

- Add a test for adding a preset with a preset scenario not present in PresetTypes

- Add a test for testing addition of presets such that the total number of presets added is greater than the total number of presets supported

* Add rollback after test step 18

* Modify the number of presets supported test case to read the number of presets supported and build a preset list whose size exceeds that to test

* Modify the number of presets supported test case to read the number of presets supported and build a preset list whose size exceeds that to test

* Update thermostat-delegate-impl.h

* Address review comments

* Add support to check for numberOfPresets supported for each preset type and build the presets list with multiple presets of each type

* Restyled by autopep8

* Fix log line formatting

* Update src/python_testing/TC_TSTAT_4_2.py

Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>

* Fix test step 17 to find a preset scenario in PresetScenarioEnum that is not present in PresetTypes to run the test

- Fix test step 18 to build a presets list that exceeds the number of presets supported correctly

* Restyled by autopep8

* Fix lint errors

* Add a while loop to add more presets until max is reached

---------

Co-authored-by: Restyled.io <commits@restyled.io>
Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>

* Allow TestAccessControl to run with ARL (#35262)

* Allow TestAccessControl to run with ARL

Since RequestType is required, set each test data entry to some
value that will pass AccessRestrictionProvider checks (since the
focus is on AccessControl for these tests).

* Copy the test data's request path and optionally add RequestType

* Make zap_downloadl.py create a usable zap.app on Mac (#35242)

Use the unzip utility on Mac for unzipping instead of zipfile.

In addition to not supporting file modes (which the script already works
around) the zipfile module also doesn't support symlinks. The embedded
frameworks inside zap.app rely on symlinks for the application to work.

* TBRM Tests scripts consistency with  te2 fixes (#35153)

* Add files via upload

Add yaml test script for TBRM

* Update TEST_TC_TBRM_2.2.yaml

* Update TEST_TC_TBRM_2.3.yaml

* Update TEST_TC_TBRM_2.4.yaml

* Test script consitancy wit test plan after TE2

* Test script consitancy wit test plan after TE2

* Update src/app/tests/suites/certification/Test_TC_TBRM_2_3.yaml

Co-authored-by: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com>

* Update src/app/tests/suites/certification/Test_TC_TBRM_2_2.yaml

Co-authored-by: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com>

* Restyled by whitespace

* Restyled by prettier-yaml

* Test_TC_TBRM_2_4. synchronisation with TC-THNETDIR-2.3 according test Plan

* Restyled by whitespace

* Test tweaks to get CI to pass

- Use pairing payload matching the other parameters
- Check response of ArmFailSafe commands
- Fix bad merge in commissioner_commands.py

* Restyled by prettier-yaml

---------

Co-authored-by: StephaneGUELEC <94045077+StephaneGUELEC@users.noreply.github.com>
Co-authored-by: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com>
Co-authored-by: Restyled.io <commits@restyled.io>
Co-authored-by: Karsten Sperling <ksperling@apple.com>

* [HVAC] Alter Thermostat Preset tests to not rely on knowledge of the server's initial state

* Pick midpoint setpoints for new presets

* Lint fixes

* Apply suggestions from code review

Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>

* Fixes from code review

* Apply suggestions from code review

Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>

* Fix remaining places with hard-coded setpoints

* Don't abort test if there are no built-in presets

* Remove unneeded length check

* Fix max number of preset types

* Add test for individual preset scenario limits

* Fix lint issue

* Return invalid in state if we're unable to iterate over the preset types for some reason

* Apply suggestions from code review

Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>

* Remove unneeded active preset setting

* Restyled patch

* Suggestions from code review

---------

Signed-off-by: Axel Le Bourhis <axel.lebourhis@nxp.com>
Co-authored-by: Axel Le Bourhis <45206070+axelnxp@users.noreply.github.com>
Co-authored-by: Terence Hampson <thampson@google.com>
Co-authored-by: Yufeng Wang <yufengwang@google.com>
Co-authored-by: Restyled.io <commits@restyled.io>
Co-authored-by: saurabhst <s.kumar9@samsung.com>
Co-authored-by: Tennessee Carmel-Veilleux <tennessee.carmelveilleux@gmail.com>
Co-authored-by: Nivi Sarkar <55898241+nivi-apple@users.noreply.github.com>
Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>
Co-authored-by: Thomas Lea <35579828+tleacmcsa@users.noreply.github.com>
Co-authored-by: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com>
Co-authored-by: marchemi <56955785+marchemi@users.noreply.github.com>
Co-authored-by: StephaneGUELEC <94045077+StephaneGUELEC@users.noreply.github.com>
Co-authored-by: Karsten Sperling <ksperling@apple.com>
diff --git a/src/app/clusters/thermostat-server/thermostat-server-presets.cpp b/src/app/clusters/thermostat-server/thermostat-server-presets.cpp
index 9413513..1dede07 100644
--- a/src/app/clusters/thermostat-server/thermostat-server-presets.cpp
+++ b/src/app/clusters/thermostat-server/thermostat-server-presets.cpp
@@ -152,69 +152,36 @@
 }
 
 /**
- * @brief Returns the length of the list of presets if the pending presets were to be applied. The size of the pending presets list
- *        calculated, after all the constraint checks are done, is the new size of the updated Presets attribute since the pending
- *        preset list is expected to have all existing presets with or without edits plus new presets.
- *        This is called before changes are actually applied.
+ * @brief Gets the maximum number of presets allowed for a given preset scenario.
  *
- * @param[in] delegate The delegate to use.
- *
- * @return count of the updated Presets attribute if the pending presets were applied to it. Return 0 for error cases.
+ * @param[in]  delegate The delegate to use.
+ * @param[in]  presetScenario The presetScenario to match with.
+ * @param[out] count The maximum number of presets for the specified presetScenario
+ * @return CHIP_NO_ERROR if the maximum number was determined, or an error if not
  */
-uint8_t CountNumberOfPendingPresets(Delegate * delegate)
+CHIP_ERROR MaximumPresetScenarioCount(Delegate * delegate, PresetScenarioEnum presetScenario, size_t & count)
 {
-    uint8_t numberOfPendingPresets = 0;
-
-    VerifyOrReturnValue(delegate != nullptr, 0);
-
-    for (uint8_t i = 0; true; i++)
-    {
-        PresetStructWithOwnedMembers pendingPreset;
-        CHIP_ERROR err = delegate->GetPendingPresetAtIndex(i, pendingPreset);
-
-        if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED)
-        {
-            break;
-        }
-        if (err != CHIP_NO_ERROR)
-        {
-            ChipLogError(Zcl, "CountNumberOfPendingPresets: GetPendingPresetAtIndex failed with error %" CHIP_ERROR_FORMAT,
-                         err.Format());
-            return 0;
-        }
-        numberOfPendingPresets++;
-    }
-
-    return numberOfPendingPresets;
-}
-
-/**
- * @brief Checks if the presetScenario is present in the PresetTypes attribute.
- *
- * @param[in] delegate The delegate to use.
- * @param[in] presetScenario The presetScenario to match with.
- *
- * @return true if the presetScenario is found, false otherwise.
- */
-bool PresetScenarioExistsInPresetTypes(Delegate * delegate, PresetScenarioEnum presetScenario)
-{
-    VerifyOrReturnValue(delegate != nullptr, false);
-
+    count = 0;
     for (uint8_t i = 0; true; i++)
     {
         PresetTypeStruct::Type presetType;
         auto err = delegate->GetPresetTypeAtIndex(i, presetType);
+        if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED)
+        {
+            // We exhausted the list trying to find the preset scenario
+            return CHIP_NO_ERROR;
+        }
         if (err != CHIP_NO_ERROR)
         {
-            return false;
+            return err;
         }
-
         if (presetType.presetScenario == presetScenario)
         {
-            return true;
+            count = presetType.numberOfPresets;
+            return CHIP_NO_ERROR;
         }
     }
-    return false;
+    return CHIP_NO_ERROR;
 }
 
 /**
@@ -410,8 +377,16 @@
         }
     }
 
-    if (!PresetScenarioExistsInPresetTypes(delegate, preset.GetPresetScenario()))
+    size_t maximumPresetCount         = delegate->GetNumberOfPresets();
+    size_t maximumPresetScenarioCount = 0;
+    if (MaximumPresetScenarioCount(delegate, preset.GetPresetScenario(), maximumPresetScenarioCount) != CHIP_NO_ERROR)
     {
+        return CHIP_IM_GLOBAL_STATUS(InvalidInState);
+    }
+
+    if (maximumPresetScenarioCount == 0)
+    {
+        // This is not a supported preset scenario
         return CHIP_IM_GLOBAL_STATUS(ConstraintError);
     }
 
@@ -423,16 +398,42 @@
     // Before adding this preset to the pending presets, if the expected length of the pending presets' list
     // exceeds the total number of presets supported, return RESOURCE_EXHAUSTED. Note that the preset has not been appended yet.
 
-    uint8_t numberOfPendingPresets = CountNumberOfPendingPresets(delegate);
-
-    // We will be adding one more preset, so reject if the length is already at max.
-    if (numberOfPendingPresets >= delegate->GetNumberOfPresets())
+    // We're going to append this preset, so let's assume a count as though it had already been inserted
+    size_t presetCount         = 1;
+    size_t presetScenarioCount = 1;
+    for (uint8_t i = 0; true; i++)
     {
+        PresetStructWithOwnedMembers otherPreset;
+        CHIP_ERROR err = delegate->GetPendingPresetAtIndex(i, otherPreset);
+
+        if (err == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED)
+        {
+            break;
+        }
+        if (err != CHIP_NO_ERROR)
+        {
+            return CHIP_IM_GLOBAL_STATUS(InvalidInState);
+        }
+        presetCount++;
+        if (preset.GetPresetScenario() == otherPreset.GetPresetScenario())
+        {
+            presetScenarioCount++;
+        }
+    }
+
+    if (presetCount > maximumPresetCount)
+    {
+        ChipLogError(Zcl, "Preset count exceeded %u: %u ", static_cast<unsigned>(maximumPresetCount),
+                     static_cast<unsigned>(presetCount));
         return CHIP_IM_GLOBAL_STATUS(ResourceExhausted);
     }
 
-    // TODO #34556 : Check if the number of presets for each presetScenario exceeds the max number of presets supported for that
-    // scenario. We plan to support only one preset for each presetScenario for our use cases so defer this for re-evaluation.
+    if (presetScenarioCount > maximumPresetScenarioCount)
+    {
+        ChipLogError(Zcl, "Preset scenario count exceeded %u: %u ", static_cast<unsigned>(maximumPresetScenarioCount),
+                     static_cast<unsigned>(presetScenarioCount));
+        return CHIP_IM_GLOBAL_STATUS(ResourceExhausted);
+    }
 
     return delegate->AppendToPendingPresetList(preset);
 }
diff --git a/src/python_testing/TC_TSTAT_4_2.py b/src/python_testing/TC_TSTAT_4_2.py
index 6dad144..85ff487 100644
--- a/src/python_testing/TC_TSTAT_4_2.py
+++ b/src/python_testing/TC_TSTAT_4_2.py
@@ -37,6 +37,7 @@
 import copy
 import logging
 import random
+from collections import namedtuple
 
 import chip.clusters as Clusters
 from chip import ChipDeviceCtrl  # Needed before chip.FabricAdmin
@@ -418,11 +419,6 @@
                 logger.info(
                     "Couldn't run test step 4 since there were no built-in presets")
 
-            # Send the SetActivePresetRequest command
-            await self.send_set_active_preset_handle_request_command(value=b'\x03')
-
-            activePresetHandle = await self.read_single_attribute_check_success(endpoint=endpoint, cluster=cluster, attribute=cluster.Attributes.ActivePresetHandle)
-
         self.step("5")
         if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")):
 
@@ -714,6 +710,28 @@
         self.step("18")
         if self.pics_guard(self.check_pics("TSTAT.S.F08") and self.check_pics("TSTAT.S.A0050") and self.check_pics("TSTAT.S.Cfe.Rsp")):
 
+            ScenarioHeadroom = namedtuple("ScenarioHeadroom", "presetScenario remaining")
+            # Generate list of tuples of scenarios and number of remaining presets per scenario allowed
+            presetScenarioHeadrooms = list(ScenarioHeadroom(presetType.presetScenario,
+                                           presetType.numberOfPresets - presetScenarioCounts.get(presetType.presetScenario, 0)) for presetType in presetTypes)
+
+            if presetScenarioHeadrooms:
+                # Find the preset scenario with the smallest number of remaining allowed presets
+                presetScenarioHeadrooms = sorted(presetScenarioHeadrooms, key=lambda psh: psh.remaining)
+                presetScenarioHeadroom = presetScenarioHeadrooms[0]
+
+                # Add one more preset than is allowed by the preset type
+                test_presets = copy.deepcopy(current_presets)
+                test_presets.extend([cluster.Structs.PresetStruct(presetHandle=NullValue, presetScenario=presetScenarioHeadroom.presetScenario,
+                                                                  coolingSetpoint=coolSetpoint, heatingSetpoint=heatSetpoint, builtIn=False)] * (presetScenarioHeadroom.remaining + 1))
+
+                await self.send_atomic_request_begin_command()
+
+                await self.write_presets(endpoint=endpoint, presets=test_presets, expected_status=Status.ResourceExhausted)
+
+                # Clear state for next test.
+                await self.send_atomic_request_rollback_command()
+
             # Calculate the length of the Presets list that could be created using the preset scenarios in PresetTypes and numberOfPresets supported for each scenario.
             totalExpectedPresetsLength = sum(presetType.numberOfPresets for presetType in presetTypes)