From e17900b02abc1dae61a5a8c13fbef5826ca36b3b Mon Sep 17 00:00:00 2001 From: Rodrigo Garcia Date: Wed, 11 Dec 2024 15:57:54 -0300 Subject: [PATCH 1/5] feat(matter): adds matter occupancy sensor endpoint --- CMakeLists.txt | 1 + .../MatterOccupancySensor.ino | 129 ++++++++++++++++++ .../examples/MatterOccupancySensor/ci.json | 7 + libraries/Matter/keywords.txt | 3 + libraries/Matter/src/Matter.h | 2 + .../MatterEndpoints/MatterOccupancySensor.cpp | 107 +++++++++++++++ .../MatterEndpoints/MatterOccupancySensor.h | 73 ++++++++++ 7 files changed, 322 insertions(+) create mode 100644 libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino create mode 100644 libraries/Matter/examples/MatterOccupancySensor/ci.json create mode 100644 libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp create mode 100644 libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h diff --git a/CMakeLists.txt b/CMakeLists.txt index b6478aa16a3..322824f11ab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -179,6 +179,7 @@ set(ARDUINO_LIBRARY_Matter_SRCS libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.cpp libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp + libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp libraries/Matter/src/Matter.cpp) set(ARDUINO_LIBRARY_PPP_SRCS diff --git a/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino b/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino new file mode 100644 index 00000000000..5b4baf23442 --- /dev/null +++ b/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino @@ -0,0 +1,129 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// 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. + +/* + * This example is an example code that will create a Matter Device which can be + * commissioned and controlled from a Matter Environment APP. + * Additionally the ESP32 will send debug messages indicating the Matter activity. + * Turning DEBUG Level ON may be useful to following Matter Accessory and Controller messages. + * + * The example will create a Matter Occupancy Sensor Device. + * The Occupancy Sensor will be simulated to change its state every 2 minutes. + * + * The onboard button can be kept pressed for 5 seconds to decommission the Matter Node. + * The example will also show the manual commissioning code and QR code to be used in the Matter environment. + * + */ + +// Matter Manager +#include +#include + +// List of Matter Endpoints for this Node +// Matter Occupancy Sensor Endpoint +MatterOccupancySensor OccupancySensor; + +// set your board USER BUTTON pin here - decommissioning only +const uint8_t buttonPin = BOOT_PIN; // Set your pin here. Using BOOT Button. + +// WiFi is manually set and started +const char *ssid = "your-ssid"; // Change this to your WiFi SSID +const char *password = "your-password"; // Change this to your WiFi password + +// Button control +uint32_t button_time_stamp = 0; // debouncing control +bool button_state = false; // false = released | true = pressed +const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s, or longer, to decommission + +void setup() { + // Initialize the USER BUTTON (Boot button) that will be used to decommission the Matter Node + // The button will also be used to manually toggle the Occupancy Sensor state + pinMode(buttonPin, INPUT_PULLUP); + + Serial.begin(115200); + + // Manually connect to WiFi + WiFi.begin(ssid, password); + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(); + + // set initial occupancy sensor state as false and connected to a PIR sensor type (default) + OccupancySensor.begin(); + + // Matter beginning - Last step, after all EndPoints are initialized + Matter.begin(); + + // Check Matter Accessory Commissioning state, which may change during execution of loop() + if (!Matter.isDeviceCommissioned()) { + Serial.println(""); + Serial.println("Matter Node is not commissioned yet."); + Serial.println("Initiate the device discovery in your Matter environment."); + Serial.println("Commission it to your Matter hub with the manual pairing code or QR code"); + Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str()); + Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str()); + // waits for Matter Occupancy Sensor Commissioning. + uint32_t timeCount = 0; + while (!Matter.isDeviceCommissioned()) { + delay(100); + if ((timeCount++ % 50) == 0) { // 50*100ms = 5 sec + Serial.println("Matter Node not commissioned yet. Waiting for commissioning."); + } + } + Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); + } +} + +bool simulatedHWOccupancySensor() { + // Simulated Occupancy Sensor + static bool occupancyState = false; + static uint32_t lastTime = millis(); + const uint32_t occupancyTimeout = 120000; // 2 minutes to toggle the state + + // Simulate a Occupancy Sensor state change every 2 minutes + if (millis() - lastTime > occupancyTimeout) { + occupancyState = !occupancyState; + lastTime = millis(); + } + return occupancyState; +} + +void loop() { + // Check if the button has been pressed + if (digitalRead(buttonPin) == LOW && !button_state) { + // deals with button debouncing + button_time_stamp = millis(); // record the time while the button is pressed. + button_state = true; // pressed. + } + + if (button_state && digitalRead(buttonPin) == HIGH) { + button_state = false; // released + } + + // Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node + uint32_t time_diff = millis() - button_time_stamp; + if (button_state && time_diff > decommissioningTimeout) { + Serial.println("Decommissioning the Generic Switch Matter Accessory. It shall be commissioned again."); + Matter.decommission(); + button_time_stamp = millis(); // avoid running decommissining again, reboot takes a second or so + } + + // Check Simulated Occupancy Sensor and set Matter Attribute + OccupancySensor.setOccupancy(simulatedHWOccupancySensor()); + + delay(50); +} diff --git a/libraries/Matter/examples/MatterOccupancySensor/ci.json b/libraries/Matter/examples/MatterOccupancySensor/ci.json new file mode 100644 index 00000000000..556a8a9ee6b --- /dev/null +++ b/libraries/Matter/examples/MatterOccupancySensor/ci.json @@ -0,0 +1,7 @@ +{ + "fqbn_append": "PartitionScheme=huge_app", + "requires": [ + "CONFIG_SOC_WIFI_SUPPORTED=y", + "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y" + ] +} diff --git a/libraries/Matter/keywords.txt b/libraries/Matter/keywords.txt index d75e9888afd..1daf65974ed 100644 --- a/libraries/Matter/keywords.txt +++ b/libraries/Matter/keywords.txt @@ -22,6 +22,7 @@ MatterTemperatureSensor KEYWORD1 MatterHumiditySensor KEYWORD1 MatterContactSensor KEYWORD1 MatterPressureSensor KEYWORD1 +MatterOccupancySensor KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) @@ -74,6 +75,8 @@ setContact KEYWORD2 getContact KEYWORD2 setPressure KEYWORD2 getPressure KEYWORD2 +setOccupancy KEYWORD2 +getOccupancy KEYWORD2 ####################################### # Constants (LITERAL1) diff --git a/libraries/Matter/src/Matter.h b/libraries/Matter/src/Matter.h index 02571dbcf40..bc0a0ec1cc7 100644 --- a/libraries/Matter/src/Matter.h +++ b/libraries/Matter/src/Matter.h @@ -30,6 +30,7 @@ #include #include #include +#include using namespace esp_matter; @@ -66,6 +67,7 @@ class ArduinoMatter { friend class MatterHumiditySensor; friend class MatterContactSensor; friend class MatterPressureSensor; + friend class MatterOccupancySensor; protected: static void _init(); diff --git a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp new file mode 100644 index 00000000000..9efa984431a --- /dev/null +++ b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp @@ -0,0 +1,107 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// 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. + +#include +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL + +#include +#include +#include + +using namespace esp_matter; +using namespace esp_matter::endpoint; +using namespace chip::app::Clusters; + +const uint8_t MatterOccupancySensor::occupancySensorTypeBitmap[4] = { + MatterOccupancySensor::occupancySensorTypePir, + MatterOccupancySensor::occupancySensorTypePir | MatterOccupancySensor::occupancySensorTypeUltrasonic, + MatterOccupancySensor::occupancySensorTypeUltrasonic, + MatterOccupancySensor::occupancySensorTypePhysicalContact +}; + +bool MatterOccupancySensor::attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) { + bool ret = true; + if (!started) { + log_e("Matter Occupancy Sensor device has not begun."); + return false; + } + + log_d("Occupancy Sensor Attr update callback: endpoint: %u, cluster: %u, attribute: %u, val: %u", endpoint_id, cluster_id, attribute_id, val->val.u32); + return ret; +} + +MatterOccupancySensor::MatterOccupancySensor() {} + +MatterOccupancySensor::~MatterOccupancySensor() { + end(); +} + +bool MatterOccupancySensor::begin(bool _occupancyState, OccupancySensorType_t _occupancySensorType) { + ArduinoMatter::_init(); + + occupancy_sensor::config_t occupancy_sensor_config; + occupancy_sensor_config.occupancy_sensing.occupancy = _occupancyState; + occupancy_sensor_config.occupancy_sensing.occupancy_sensor_type = _occupancySensorType; + occupancy_sensor_config.occupancy_sensing.occupancy_sensor_type_bitmap = occupancySensorTypeBitmap[_occupancySensorType]; + + // endpoint handles can be used to add/modify clusters. + endpoint_t *endpoint = occupancy_sensor::create(node::get(), &occupancy_sensor_config, ENDPOINT_FLAG_NONE, (void *)this); + if (endpoint == nullptr) { + log_e("Failed to create Occupancy Sensor endpoint"); + return false; + } + occupancyState = _occupancyState; + setEndPointId(endpoint::get_id(endpoint)); + log_i("Occupancy Sensor created with endpoint_id %d", getEndPointId()); + started = true; + return true; +} + +void MatterOccupancySensor::end() { + started = false; +} + +bool MatterOccupancySensor::setOccupancy(bool _occupancyState) { + if (!started) { + log_e("Matter Occupancy Sensor device has not begun."); + return false; + } + + // avoid processing the a "no-change" + if (occupancyState == _occupancyState) { + return true; + } + + esp_matter_attr_val_t occupancyVal = esp_matter_invalid(NULL); + + if (!getAttributeVal(OccupancySensing::Id, OccupancySensing::Attributes::Occupancy::Id, &occupancyVal)) { + log_e("Failed to get Occupancy Sensor Attribute."); + return false; + } + if (occupancyVal.val.u8 != _occupancyState) { + occupancyVal.val.u8 = _occupancyState; + bool ret; + ret = updateAttributeVal(OccupancySensing::Id, OccupancySensing::Attributes::Occupancy::Id, &occupancyVal); + if (!ret) { + log_e("Failed to update Occupancy Sensor Attribute."); + return false; + } + occupancyState = _occupancyState; + } + log_v("Occupancy Sensor set to %s", _occupancyState ? "Occupied" : "Vacant"); + + return true; +} + +#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */ diff --git a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h new file mode 100644 index 00000000000..30f312a9841 --- /dev/null +++ b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h @@ -0,0 +1,73 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once +#include +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL + +#include +#include +#include + +using namespace chip::app::Clusters::OccupancySensing; + +class MatterOccupancySensor : public MatterEndPoint { +public: + // Different Occupancy Sensor Types + enum OccupancySensorType_t { + OCCUPANCY_SENSOR_TYPE_PIR = (uint8_t)OccupancySensorTypeEnum::kPir, + OCCUPANCY_SENSOR_TYPE_ULTRASONIC = (uint8_t)OccupancySensorTypeEnum::kUltrasonic, + OCCUPANCY_SENSOR_TYPE_PIR_AND_ULTRASONIC = (uint8_t)OccupancySensorTypeEnum::kPIRAndUltrasonic, + OCCUPANCY_SENSOR_TYPE_PHYSICAL_CONTACT = (uint8_t)OccupancySensorTypeEnum::kPhysicalContact + }; + + MatterOccupancySensor(); + ~MatterOccupancySensor(); + // begin Matter Occupancy Sensor endpoint with initial occupancy state and default PIR sensor type + bool begin(bool _occupancyState = false, OccupancySensorType_t _occupancySensorType = OCCUPANCY_SENSOR_TYPE_PIR); + // this will just stop processing Occupancy Sensor Matter events + void end(); + + // set the occupancy state + bool setOccupancy(bool _occupancyState); + // returns the occupancy state + bool getOccupancy() { + return occupancyState; + } + + // bool conversion operator + void operator=(bool _occupancyState) { + setOccupancy(_occupancyState); + } + // bool conversion operator + operator bool() { + return getOccupancy(); + } + + // this function is called by Matter internal event processor. It could be overwritten by the application, if necessary. + bool attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val); + +protected: + // bitmap for Occupancy Sensor Types + static const uint8_t occupancySensorTypePir = 0x01; + static const uint8_t occupancySensorTypeUltrasonic = 0x02; + static const uint8_t occupancySensorTypePhysicalContact = 0x04; + + // bitmap for Occupancy Sensor Type Bitmap mapped array + static const uint8_t occupancySensorTypeBitmap[4]; + + bool started = false; + bool occupancyState = false; +}; +#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */ From 3bf8f23e487676ec3af812004bb4be634afe01c8 Mon Sep 17 00:00:00 2001 From: Rodrigo Garcia Date: Thu, 12 Dec 2024 10:03:45 -0300 Subject: [PATCH 2/5] fix(matter): removed commentary that has no code related --- .../examples/MatterOccupancySensor/MatterOccupancySensor.ino | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino b/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino index 5b4baf23442..7582a423dc0 100644 --- a/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino +++ b/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino @@ -48,7 +48,6 @@ const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s void setup() { // Initialize the USER BUTTON (Boot button) that will be used to decommission the Matter Node - // The button will also be used to manually toggle the Occupancy Sensor state pinMode(buttonPin, INPUT_PULLUP); Serial.begin(115200); From 4cf0f20129fd192935691a59cf24c3e065fb5a19 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Thu, 12 Dec 2024 13:43:48 +0000 Subject: [PATCH 3/5] ci(pre-commit): Apply automatic fixes --- .../Matter/src/MatterEndpoints/MatterOccupancySensor.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp index 9efa984431a..2477038bf28 100644 --- a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp +++ b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp @@ -24,10 +24,8 @@ using namespace esp_matter::endpoint; using namespace chip::app::Clusters; const uint8_t MatterOccupancySensor::occupancySensorTypeBitmap[4] = { - MatterOccupancySensor::occupancySensorTypePir, - MatterOccupancySensor::occupancySensorTypePir | MatterOccupancySensor::occupancySensorTypeUltrasonic, - MatterOccupancySensor::occupancySensorTypeUltrasonic, - MatterOccupancySensor::occupancySensorTypePhysicalContact + MatterOccupancySensor::occupancySensorTypePir, MatterOccupancySensor::occupancySensorTypePir | MatterOccupancySensor::occupancySensorTypeUltrasonic, + MatterOccupancySensor::occupancySensorTypeUltrasonic, MatterOccupancySensor::occupancySensorTypePhysicalContact }; bool MatterOccupancySensor::attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) { From c310c1ade4c0e9e0d27b137da5f1575fdc70ab57 Mon Sep 17 00:00:00 2001 From: Rodrigo Garcia Date: Thu, 12 Dec 2024 13:05:35 -0300 Subject: [PATCH 4/5] feat(matter): adds matter on off plugin endpoint --- CMakeLists.txt | 1 + .../MatterOnOffPlugin/MatterOnOffPlugin.ino | 142 ++++++++++++++++++ .../Matter/examples/MatterOnOffPlugin/ci.json | 7 + libraries/Matter/keywords.txt | 1 + libraries/Matter/src/Matter.h | 2 + .../src/MatterEndpoints/MatterOnOffPlugin.cpp | 136 +++++++++++++++++ .../src/MatterEndpoints/MatterOnOffPlugin.h | 56 +++++++ 7 files changed, 345 insertions(+) create mode 100644 libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino create mode 100644 libraries/Matter/examples/MatterOnOffPlugin/ci.json create mode 100644 libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp create mode 100644 libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 322824f11ab..6f89f3b8715 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,6 +180,7 @@ set(ARDUINO_LIBRARY_Matter_SRCS libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp + libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp libraries/Matter/src/Matter.cpp) set(ARDUINO_LIBRARY_PPP_SRCS diff --git a/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino b/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino new file mode 100644 index 00000000000..04cf8bff31a --- /dev/null +++ b/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino @@ -0,0 +1,142 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// 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. + +// Matter Manager +#include +#include +#include + +// List of Matter Endpoints for this Node +// On/Off Plugin Endpoint +MatterOnOffPlugin OnOffPlugin; + +// it will keep last OnOff state stored, using Preferences +Preferences matterPref; +const char *onOffPrefKey = "OnOff"; + +// set your board Power Relay pin here - this example uses the built-in LED for easy visualization +#ifdef LED_BUILTIN +const uint8_t onoffPin = LED_BUILTIN; +#else +const uint8_t onoffPin = 2; // Set your pin here - usually a power relay +#warning "Do not forget to set the Power Relay pin" +#endif + +// board USER BUTTON pin necessary for Decommissioning +const uint8_t buttonPin = BOOT_PIN; // Set your pin here. Using BOOT Button. + +// Button control +uint32_t button_time_stamp = 0; // debouncing control +bool button_state = false; // false = released | true = pressed +const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s, or longer, to decommission + +// WiFi is manually set and started +const char *ssid = "your-ssid"; // Change this to your WiFi SSID +const char *password = "your-password"; // Change this to your WiFi password + +// Matter Protocol Endpoint Callback +bool setPluginOnOff(bool state) { + Serial.printf("User Callback :: New Plugin State = %s\r\n", state ? "ON" : "OFF"); + if (state) { + digitalWrite(onoffPin, HIGH); + } else { + digitalWrite(onoffPin, LOW); + } + // store last OnOff state for when the Plugin is restarted / power goes off + matterPref.putBool(onOffPrefKey, state); + // This callback must return the success state to Matter core + return true; +} + +void setup() { + // Initialize the USER BUTTON + pinMode(buttonPin, INPUT_PULLUP); + // Initialize the Power Relay (plugin) GPIO + pinMode(onoffPin, OUTPUT); + + Serial.begin(115200); + + // We start by connecting to a WiFi network + Serial.print("Connecting to "); + Serial.println(ssid); + WiFi.begin(ssid, password); + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println("\r\nWiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + delay(500); + + // Initialize Matter EndPoint + matterPref.begin("MatterPrefs", false); + bool lastOnOffState = matterPref.getBool(onOffPrefKey, false); + OnOffPlugin.begin(lastOnOffState); + OnOffPlugin.onChange(setPluginOnOff); + + // Matter beginning - Last step, after all EndPoints are initialized + Matter.begin(); + // This may be a restart of a already commissioned Matter accessory + if (Matter.isDeviceCommissioned()) { + Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); + Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF"); + OnOffPlugin.updateAccessory(); // configure the Plugin based on initial state + } +} + +void loop() { + // Check Matter Plugin Commissioning state, which may change during execution of loop() + if (!Matter.isDeviceCommissioned()) { + Serial.println(""); + Serial.println("Matter Node is not commissioned yet."); + Serial.println("Initiate the device discovery in your Matter environment."); + Serial.println("Commission it to your Matter hub with the manual pairing code or QR code"); + Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str()); + Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str()); + // waits for Matter Plugin Commissioning. + uint32_t timeCount = 0; + while (!Matter.isDeviceCommissioned()) { + delay(100); + if ((timeCount++ % 50) == 0) { // 50*100ms = 5 sec + Serial.println("Matter Node not commissioned yet. Waiting for commissioning."); + } + } + Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF"); + OnOffPlugin.updateAccessory(); // configure the Plugin based on initial state + Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); + } + + // Check if the button has been pressed + if (digitalRead(buttonPin) == LOW && !button_state) { + // deals with button debouncing + button_time_stamp = millis(); // record the time while the button is pressed. + button_state = true; // pressed. + } + + // Onboard User Button is used to decommission the Matter Node + if (button_state && digitalRead(buttonPin) == HIGH) { + button_state = false; // released + } + + // Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node + uint32_t time_diff = millis() - button_time_stamp; + if (button_state && time_diff > decommissioningTimeout) { + Serial.println("Decommissioning the Plugin Matter Accessory. It shall be commissioned again."); + OnOffPlugin.setOnOff(false); // turn the plugin off + Matter.decommission(); + button_time_stamp = millis(); // avoid running decommissining again, reboot takes a second or so + } +} diff --git a/libraries/Matter/examples/MatterOnOffPlugin/ci.json b/libraries/Matter/examples/MatterOnOffPlugin/ci.json new file mode 100644 index 00000000000..556a8a9ee6b --- /dev/null +++ b/libraries/Matter/examples/MatterOnOffPlugin/ci.json @@ -0,0 +1,7 @@ +{ + "fqbn_append": "PartitionScheme=huge_app", + "requires": [ + "CONFIG_SOC_WIFI_SUPPORTED=y", + "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y" + ] +} diff --git a/libraries/Matter/keywords.txt b/libraries/Matter/keywords.txt index 1daf65974ed..3f40e598ada 100644 --- a/libraries/Matter/keywords.txt +++ b/libraries/Matter/keywords.txt @@ -23,6 +23,7 @@ MatterHumiditySensor KEYWORD1 MatterContactSensor KEYWORD1 MatterPressureSensor KEYWORD1 MatterOccupancySensor KEYWORD1 +MatterOnOffPlugin KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) diff --git a/libraries/Matter/src/Matter.h b/libraries/Matter/src/Matter.h index bc0a0ec1cc7..7fcab363f11 100644 --- a/libraries/Matter/src/Matter.h +++ b/libraries/Matter/src/Matter.h @@ -31,6 +31,7 @@ #include #include #include +#include using namespace esp_matter; @@ -68,6 +69,7 @@ class ArduinoMatter { friend class MatterContactSensor; friend class MatterPressureSensor; friend class MatterOccupancySensor; + friend class MatterOnOffPlugin; protected: static void _init(); diff --git a/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp new file mode 100644 index 00000000000..6b5e5e630e0 --- /dev/null +++ b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp @@ -0,0 +1,136 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// 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. + +#include +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL + +#include +#include +#include + +using namespace esp_matter; +using namespace esp_matter::endpoint; +using namespace chip::app::Clusters; + +bool MatterOnOffPlugin::attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) { + bool ret = true; + if (!started) { + log_e("Matter On-Off Plugin device has not begun."); + return false; + } + + log_d("OnOff Attr update callback: endpoint: %u, cluster: %u, attribute: %u, val: %u", endpoint_id, cluster_id, attribute_id, val->val.u32); + + if (endpoint_id == getEndPointId()) { + log_d("OnOffPlugin state changed to %d", val->val.b); + if (cluster_id == OnOff::Id) { + if (attribute_id == OnOff::Attributes::OnOff::Id) { + if (_onChangeOnOffCB != NULL) { + ret &= _onChangeOnOffCB(val->val.b); + } + if (_onChangeCB != NULL) { + ret &= _onChangeCB(val->val.b); + } + if (ret == true) { + onOffState = val->val.b; + } + } + } + } + return ret; +} + +MatterOnOffPlugin::MatterOnOffPlugin() {} + +MatterOnOffPlugin::~MatterOnOffPlugin() { + end(); +} + +bool MatterOnOffPlugin::begin(bool initialState) { + ArduinoMatter::_init(); + on_off_plugin_unit::config_t plugin_config; + + plugin_config.on_off.on_off = initialState; + plugin_config.on_off.lighting.start_up_on_off = nullptr; + + // endpoint handles can be used to add/modify clusters. + endpoint_t *endpoint = on_off_plugin_unit::create(node::get(), &plugin_config, ENDPOINT_FLAG_NONE, (void *)this); + if (endpoint == nullptr) { + log_e("Failed to create on-off plugin endpoint"); + return false; + } + onOffState = initialState; + setEndPointId(endpoint::get_id(endpoint)); + log_i("On-Off Plugin created with endpoint_id %d", getEndPointId()); + started = true; + return true; +} + +void MatterOnOffPlugin::end() { + started = false; +} + +void MatterOnOffPlugin::updateAccessory() { + if (_onChangeCB != NULL) { + _onChangeCB(onOffState); + } +} + +bool MatterOnOffPlugin::setOnOff(bool newState) { + if (!started) { + log_e("Matter On-Off Plugin device has not begun."); + return false; + } + + // avoid processing the a "no-change" + if (onOffState == newState) { + return true; + } + + esp_matter_attr_val_t onoffVal = esp_matter_invalid(NULL); + + if (!getAttributeVal(OnOff::Id, OnOff::Attributes::OnOff::Id, &onoffVal)) { + log_e("Failed to get Pressure Sensor Attribute."); + return false; + } + if (onoffVal.val.b != newState) { + onoffVal.val.b = newState; + bool ret; + ret = updateAttributeVal(OnOff::Id, OnOff::Attributes::OnOff::Id, &onoffVal); + if (!ret) { + log_e("Failed to update Pressure Sensor Measurement Attribute."); + return false; + } + onOffState = newState; + } + log_v("Plugin OnOff state set to %s", newState ? "ON" : "OFF"); + return true; +} + +bool MatterOnOffPlugin::getOnOff() { + return onOffState; +} + +bool MatterOnOffPlugin::toggle() { + return setOnOff(!onOffState); +} + +MatterOnOffPlugin::operator bool() { + return getOnOff(); +} + +void MatterOnOffPlugin::operator=(bool newState) { + setOnOff(newState); +} +#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */ diff --git a/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h new file mode 100644 index 00000000000..241726a3a46 --- /dev/null +++ b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h @@ -0,0 +1,56 @@ +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once +#include +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL + +#include +#include + +class MatterOnOffPlugin : public MatterEndPoint { +public: + MatterOnOffPlugin(); + ~MatterOnOffPlugin(); + virtual bool begin(bool initialState = false); // default initial state is off + void end(); // this will just stop processing Plugin Matter events + + bool setOnOff(bool newState); // returns true if successful + bool getOnOff(); // returns current plugin state + bool toggle(); // returns true if successful + + // used to update the state of the plugin using the current Matter Plugin internal state + // It is necessary to set a user callback function using onChange() to handle the physical plugin state + void updateAccessory(); + + operator bool(); // returns current plugin state + void operator=(bool state); // turns plugin on or off + // this function is called by Matter internal event processor. It could be overwritten by the application, if necessary. + bool attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val); + // User Callback for whenever the Plugin state is changed by the Matter Controller + using EndPointCB = std::function; + void onChange(EndPointCB onChangeCB) { + _onChangeCB = onChangeCB; + } + void onChangeOnOff(EndPointCB onChangeCB) { + _onChangeOnOffCB = onChangeCB; + } + +protected: + bool started = false; + bool onOffState = false; // default initial state is off, but it can be changed by begin(bool) + EndPointCB _onChangeCB = NULL; + EndPointCB _onChangeOnOffCB = NULL; +}; +#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */ From faed83229864601272690f2cdda55a12d0417133 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 14:34:24 +0000 Subject: [PATCH 5/5] ci(pre-commit): Apply automatic fixes --- .../MatterOnOffPlugin/MatterOnOffPlugin.ino | 284 +++++++++--------- 1 file changed, 142 insertions(+), 142 deletions(-) diff --git a/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino b/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino index 04cf8bff31a..1950b5bb9f3 100644 --- a/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino +++ b/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino @@ -1,142 +1,142 @@ -// Copyright 2024 Espressif Systems (Shanghai) PTE LTD -// -// 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. - -// Matter Manager -#include -#include -#include - -// List of Matter Endpoints for this Node -// On/Off Plugin Endpoint -MatterOnOffPlugin OnOffPlugin; - -// it will keep last OnOff state stored, using Preferences -Preferences matterPref; -const char *onOffPrefKey = "OnOff"; - -// set your board Power Relay pin here - this example uses the built-in LED for easy visualization -#ifdef LED_BUILTIN -const uint8_t onoffPin = LED_BUILTIN; -#else -const uint8_t onoffPin = 2; // Set your pin here - usually a power relay -#warning "Do not forget to set the Power Relay pin" -#endif - -// board USER BUTTON pin necessary for Decommissioning -const uint8_t buttonPin = BOOT_PIN; // Set your pin here. Using BOOT Button. - -// Button control -uint32_t button_time_stamp = 0; // debouncing control -bool button_state = false; // false = released | true = pressed -const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s, or longer, to decommission - -// WiFi is manually set and started -const char *ssid = "your-ssid"; // Change this to your WiFi SSID -const char *password = "your-password"; // Change this to your WiFi password - -// Matter Protocol Endpoint Callback -bool setPluginOnOff(bool state) { - Serial.printf("User Callback :: New Plugin State = %s\r\n", state ? "ON" : "OFF"); - if (state) { - digitalWrite(onoffPin, HIGH); - } else { - digitalWrite(onoffPin, LOW); - } - // store last OnOff state for when the Plugin is restarted / power goes off - matterPref.putBool(onOffPrefKey, state); - // This callback must return the success state to Matter core - return true; -} - -void setup() { - // Initialize the USER BUTTON - pinMode(buttonPin, INPUT_PULLUP); - // Initialize the Power Relay (plugin) GPIO - pinMode(onoffPin, OUTPUT); - - Serial.begin(115200); - - // We start by connecting to a WiFi network - Serial.print("Connecting to "); - Serial.println(ssid); - WiFi.begin(ssid, password); - // Wait for connection - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println("\r\nWiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - delay(500); - - // Initialize Matter EndPoint - matterPref.begin("MatterPrefs", false); - bool lastOnOffState = matterPref.getBool(onOffPrefKey, false); - OnOffPlugin.begin(lastOnOffState); - OnOffPlugin.onChange(setPluginOnOff); - - // Matter beginning - Last step, after all EndPoints are initialized - Matter.begin(); - // This may be a restart of a already commissioned Matter accessory - if (Matter.isDeviceCommissioned()) { - Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); - Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF"); - OnOffPlugin.updateAccessory(); // configure the Plugin based on initial state - } -} - -void loop() { - // Check Matter Plugin Commissioning state, which may change during execution of loop() - if (!Matter.isDeviceCommissioned()) { - Serial.println(""); - Serial.println("Matter Node is not commissioned yet."); - Serial.println("Initiate the device discovery in your Matter environment."); - Serial.println("Commission it to your Matter hub with the manual pairing code or QR code"); - Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str()); - Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str()); - // waits for Matter Plugin Commissioning. - uint32_t timeCount = 0; - while (!Matter.isDeviceCommissioned()) { - delay(100); - if ((timeCount++ % 50) == 0) { // 50*100ms = 5 sec - Serial.println("Matter Node not commissioned yet. Waiting for commissioning."); - } - } - Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF"); - OnOffPlugin.updateAccessory(); // configure the Plugin based on initial state - Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); - } - - // Check if the button has been pressed - if (digitalRead(buttonPin) == LOW && !button_state) { - // deals with button debouncing - button_time_stamp = millis(); // record the time while the button is pressed. - button_state = true; // pressed. - } - - // Onboard User Button is used to decommission the Matter Node - if (button_state && digitalRead(buttonPin) == HIGH) { - button_state = false; // released - } - - // Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node - uint32_t time_diff = millis() - button_time_stamp; - if (button_state && time_diff > decommissioningTimeout) { - Serial.println("Decommissioning the Plugin Matter Accessory. It shall be commissioned again."); - OnOffPlugin.setOnOff(false); // turn the plugin off - Matter.decommission(); - button_time_stamp = millis(); // avoid running decommissining again, reboot takes a second or so - } -} +// Copyright 2024 Espressif Systems (Shanghai) PTE LTD +// +// 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. + +// Matter Manager +#include +#include +#include + +// List of Matter Endpoints for this Node +// On/Off Plugin Endpoint +MatterOnOffPlugin OnOffPlugin; + +// it will keep last OnOff state stored, using Preferences +Preferences matterPref; +const char *onOffPrefKey = "OnOff"; + +// set your board Power Relay pin here - this example uses the built-in LED for easy visualization +#ifdef LED_BUILTIN +const uint8_t onoffPin = LED_BUILTIN; +#else +const uint8_t onoffPin = 2; // Set your pin here - usually a power relay +#warning "Do not forget to set the Power Relay pin" +#endif + +// board USER BUTTON pin necessary for Decommissioning +const uint8_t buttonPin = BOOT_PIN; // Set your pin here. Using BOOT Button. + +// Button control +uint32_t button_time_stamp = 0; // debouncing control +bool button_state = false; // false = released | true = pressed +const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s, or longer, to decommission + +// WiFi is manually set and started +const char *ssid = "your-ssid"; // Change this to your WiFi SSID +const char *password = "your-password"; // Change this to your WiFi password + +// Matter Protocol Endpoint Callback +bool setPluginOnOff(bool state) { + Serial.printf("User Callback :: New Plugin State = %s\r\n", state ? "ON" : "OFF"); + if (state) { + digitalWrite(onoffPin, HIGH); + } else { + digitalWrite(onoffPin, LOW); + } + // store last OnOff state for when the Plugin is restarted / power goes off + matterPref.putBool(onOffPrefKey, state); + // This callback must return the success state to Matter core + return true; +} + +void setup() { + // Initialize the USER BUTTON + pinMode(buttonPin, INPUT_PULLUP); + // Initialize the Power Relay (plugin) GPIO + pinMode(onoffPin, OUTPUT); + + Serial.begin(115200); + + // We start by connecting to a WiFi network + Serial.print("Connecting to "); + Serial.println(ssid); + WiFi.begin(ssid, password); + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println("\r\nWiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + delay(500); + + // Initialize Matter EndPoint + matterPref.begin("MatterPrefs", false); + bool lastOnOffState = matterPref.getBool(onOffPrefKey, false); + OnOffPlugin.begin(lastOnOffState); + OnOffPlugin.onChange(setPluginOnOff); + + // Matter beginning - Last step, after all EndPoints are initialized + Matter.begin(); + // This may be a restart of a already commissioned Matter accessory + if (Matter.isDeviceCommissioned()) { + Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); + Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF"); + OnOffPlugin.updateAccessory(); // configure the Plugin based on initial state + } +} + +void loop() { + // Check Matter Plugin Commissioning state, which may change during execution of loop() + if (!Matter.isDeviceCommissioned()) { + Serial.println(""); + Serial.println("Matter Node is not commissioned yet."); + Serial.println("Initiate the device discovery in your Matter environment."); + Serial.println("Commission it to your Matter hub with the manual pairing code or QR code"); + Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str()); + Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str()); + // waits for Matter Plugin Commissioning. + uint32_t timeCount = 0; + while (!Matter.isDeviceCommissioned()) { + delay(100); + if ((timeCount++ % 50) == 0) { // 50*100ms = 5 sec + Serial.println("Matter Node not commissioned yet. Waiting for commissioning."); + } + } + Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF"); + OnOffPlugin.updateAccessory(); // configure the Plugin based on initial state + Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use."); + } + + // Check if the button has been pressed + if (digitalRead(buttonPin) == LOW && !button_state) { + // deals with button debouncing + button_time_stamp = millis(); // record the time while the button is pressed. + button_state = true; // pressed. + } + + // Onboard User Button is used to decommission the Matter Node + if (button_state && digitalRead(buttonPin) == HIGH) { + button_state = false; // released + } + + // Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node + uint32_t time_diff = millis() - button_time_stamp; + if (button_state && time_diff > decommissioningTimeout) { + Serial.println("Decommissioning the Plugin Matter Accessory. It shall be commissioned again."); + OnOffPlugin.setOnOff(false); // turn the plugin off + Matter.decommission(); + button_time_stamp = millis(); // avoid running decommissining again, reboot takes a second or so + } +}