Skip to content

Commit d55160c

Browse files
authored
Merge pull request #10712 from SuGlider/matter_contact_sensor
feat(matter): creates a Matter Contact Sensor Endpoint
2 parents 83165f3 + 2bd1ec4 commit d55160c

File tree

7 files changed

+317
-0
lines changed

7 files changed

+317
-0
lines changed

CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ set(ARDUINO_LIBRARY_Matter_SRCS
177177
libraries/Matter/src/MatterEndpoints/MatterFan.cpp
178178
libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.cpp
179179
libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.cpp
180+
libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp
180181
libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp
181182
libraries/Matter/src/Matter.cpp)
182183

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/*
16+
* This example is an example code that will create a Matter Device which can be
17+
* commissioned and controlled from a Matter Environment APP.
18+
* Additionally the ESP32 will send debug messages indicating the Matter activity.
19+
* Turning DEBUG Level ON may be useful to following Matter Accessory and Controller messages.
20+
*
21+
* The example will create a Matter Contact Sensor Device.
22+
* The Contact Sensor state can be toggled by pressing the onboard button.
23+
* The Contact Sensor state will be indicated by the onboard LED.
24+
* The Contact Sensor state will be simulated to change every 20 seconds.
25+
*
26+
* The onboard button can be kept pressed for 5 seconds to decommission the Matter Node.
27+
* The example will also show the manual commissioning code and QR code to be used in the Matter environment.
28+
*
29+
*/
30+
31+
// Matter Manager
32+
#include <Matter.h>
33+
#include <WiFi.h>
34+
35+
// List of Matter Endpoints for this Node
36+
// Matter Contact Sensor Endpoint
37+
MatterContactSensor ContactSensor;
38+
39+
// LED will be used to indicate the Contact Sensor state
40+
// set your board RGB LED pin here
41+
#ifdef RGB_BUILTIN
42+
const uint8_t ledPin = RGB_BUILTIN;
43+
#else
44+
const uint8_t ledPin = 2; // Set your pin here if your board has not defined LED_BUILTIN
45+
#warning "Do not forget to set the RGB LED pin"
46+
#endif
47+
48+
// set your board USER BUTTON pin here - decommissioning and Manual Contact Sensor toggle button
49+
const uint8_t buttonPin = BOOT_PIN; // Set your pin here. Using BOOT Button.
50+
51+
// WiFi is manually set and started
52+
const char *ssid = "your-ssid"; // Change this to your WiFi SSID
53+
const char *password = "your-password"; // Change this to your WiFi password
54+
55+
// Button control
56+
uint32_t button_time_stamp = 0; // debouncing control
57+
bool button_state = false; // false = released | true = pressed
58+
const uint32_t debouceTime = 250; // button debouncing time (ms)
59+
const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s, or longer, to decommission
60+
61+
void setup() {
62+
// Initialize the USER BUTTON (Boot button) that will be used to decommission the Matter Node
63+
// The button will also be used to manually toggle the Contact Sensor state
64+
pinMode(buttonPin, INPUT_PULLUP);
65+
// Initialize the LED (light) GPIO and Matter End Point
66+
pinMode(ledPin, OUTPUT);
67+
68+
Serial.begin(115200);
69+
70+
// Manually connect to WiFi
71+
WiFi.begin(ssid, password);
72+
// Wait for connection
73+
while (WiFi.status() != WL_CONNECTED) {
74+
delay(500);
75+
Serial.print(".");
76+
}
77+
Serial.println();
78+
79+
// set initial contact sensor state as false (default)
80+
ContactSensor.begin();
81+
digitalWrite(ledPin, LOW); // LED OFF
82+
83+
// Matter beginning - Last step, after all EndPoints are initialized
84+
Matter.begin();
85+
86+
// Check Matter Accessory Commissioning state, which may change during execution of loop()
87+
if (!Matter.isDeviceCommissioned()) {
88+
Serial.println("");
89+
Serial.println("Matter Node is not commissioned yet.");
90+
Serial.println("Initiate the device discovery in your Matter environment.");
91+
Serial.println("Commission it to your Matter hub with the manual pairing code or QR code");
92+
Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str());
93+
Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str());
94+
// waits for Matter Contact Sensor Commissioning.
95+
uint32_t timeCount = 0;
96+
while (!Matter.isDeviceCommissioned()) {
97+
delay(100);
98+
if ((timeCount++ % 50) == 0) { // 50*100ms = 5 sec
99+
Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
100+
}
101+
}
102+
Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
103+
}
104+
}
105+
106+
bool simulatedHWContactSensor() {
107+
// Simulated Contact Sensor
108+
static bool contactState = false;
109+
static uint32_t lastTime = 0;
110+
111+
// Simulate a Contact Sensor state change every 20 seconds
112+
if (millis() - lastTime > 20000) {
113+
contactState = !contactState;
114+
lastTime = millis();
115+
}
116+
return contactState;
117+
}
118+
119+
void loop() {
120+
// Check if the button has been pressed
121+
if (digitalRead(buttonPin) == LOW && !button_state) {
122+
// deals with button debouncing
123+
button_time_stamp = millis(); // record the time while the button is pressed.
124+
button_state = true; // pressed.
125+
}
126+
127+
uint32_t time_diff = millis() - button_time_stamp;
128+
if (button_state && time_diff > debouceTime && digitalRead(buttonPin) == HIGH) {
129+
button_state = false; // released
130+
// button is released - toggle Contact State (Open/Closed)
131+
ContactSensor.setContact(!ContactSensor.getContact()); // same as ContactSensor = !ContactSensor;
132+
Serial.printf("User button released. Setting the Contact Sensor to %s.\r\n", ContactSensor ? "Closed" : "Open");
133+
// LED will indicate the Contact Sensor state
134+
if (ContactSensor) {
135+
digitalWrite(ledPin, HIGH); // LED ON
136+
} else {
137+
digitalWrite(ledPin, LOW); // LED OFF
138+
}
139+
}
140+
141+
// Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node
142+
if (button_state && time_diff > decommissioningTimeout) {
143+
Serial.println("Decommissioning the Generic Switch Matter Accessory. It shall be commissioned again.");
144+
Matter.decommission();
145+
button_time_stamp = millis(); // avoid running decommissining again, reboot takes a second or so
146+
}
147+
148+
// Simulated Contact Sensor
149+
ContactSensor.setContact(simulatedHWContactSensor());
150+
151+
delay(50);
152+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"fqbn_append": "PartitionScheme=huge_app",
3+
"requires": [
4+
"CONFIG_SOC_WIFI_SUPPORTED=y",
5+
"CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
6+
]
7+
}

libraries/Matter/keywords.txt

+3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ FanMode_t KEYWORD1
2020
FanModeSequence_t KEYWORD1
2121
MatterTemperatureSensor KEYWORD1
2222
MatterHumiditySensor KEYWORD1
23+
MatterContactSensor KEYWORD1
2324
MatterPressureSensor KEYWORD1
2425

2526
#######################################
@@ -69,6 +70,8 @@ setTemperature KEYWORD2
6970
getTemperature KEYWORD2
7071
setHumidity KEYWORD2
7172
getHumidity KEYWORD2
73+
setContact KEYWORD2
74+
getContact KEYWORD2
7275
setPressure KEYWORD2
7376
getPressure KEYWORD2
7477

libraries/Matter/src/Matter.h

+2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include <MatterEndpoints/MatterFan.h>
2929
#include <MatterEndpoints/MatterTemperatureSensor.h>
3030
#include <MatterEndpoints/MatterHumiditySensor.h>
31+
#include <MatterEndpoints/MatterContactSensor.h>
3132
#include <MatterEndpoints/MatterPressureSensor.h>
3233

3334
using namespace esp_matter;
@@ -63,6 +64,7 @@ class ArduinoMatter {
6364
friend class MatterFan;
6465
friend class MatterTemperatureSensor;
6566
friend class MatterHumiditySensor;
67+
friend class MatterContactSensor;
6668
friend class MatterPressureSensor;
6769

6870
protected:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#include <sdkconfig.h>
16+
#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
17+
18+
#include <Matter.h>
19+
#include <app/server/Server.h>
20+
#include <MatterEndpoints/MatterContactSensor.h>
21+
22+
using namespace esp_matter;
23+
using namespace esp_matter::endpoint;
24+
using namespace chip::app::Clusters;
25+
26+
bool MatterContactSensor::attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) {
27+
bool ret = true;
28+
if (!started) {
29+
log_e("Matter Contact Sensor device has not begun.");
30+
return false;
31+
}
32+
33+
log_d("Contact Sensor Attr update callback: endpoint: %u, cluster: %u, attribute: %u, val: %u", endpoint_id, cluster_id, attribute_id, val->val.u32);
34+
return ret;
35+
}
36+
37+
MatterContactSensor::MatterContactSensor() {}
38+
39+
MatterContactSensor::~MatterContactSensor() {
40+
end();
41+
}
42+
43+
bool MatterContactSensor::begin(bool _contactState) {
44+
ArduinoMatter::_init();
45+
46+
contact_sensor::config_t contact_sensor_config;
47+
contact_sensor_config.boolean_state.state_value = _contactState;
48+
49+
// endpoint handles can be used to add/modify clusters.
50+
endpoint_t *endpoint = contact_sensor::create(node::get(), &contact_sensor_config, ENDPOINT_FLAG_NONE, (void *)this);
51+
if (endpoint == nullptr) {
52+
log_e("Failed to create Contact Sensor endpoint");
53+
return false;
54+
}
55+
contactState = _contactState;
56+
setEndPointId(endpoint::get_id(endpoint));
57+
log_i("Contact Sensor created with endpoint_id %d", getEndPointId());
58+
started = true;
59+
return true;
60+
}
61+
62+
void MatterContactSensor::end() {
63+
started = false;
64+
}
65+
66+
bool MatterContactSensor::setContact(bool _contactState) {
67+
if (!started) {
68+
log_e("Matter Contact Sensor device has not begun.");
69+
return false;
70+
}
71+
72+
// avoid processing the a "no-change"
73+
if (contactState == _contactState) {
74+
return true;
75+
}
76+
77+
esp_matter_attr_val_t contactVal = esp_matter_invalid(NULL);
78+
79+
if (!getAttributeVal(BooleanState::Id, BooleanState::Attributes::StateValue::Id, &contactVal)) {
80+
log_e("Failed to get Contact Sensor Attribute.");
81+
return false;
82+
}
83+
if (contactVal.val.u8 != _contactState) {
84+
contactVal.val.u8 = _contactState;
85+
bool ret;
86+
ret = updateAttributeVal(BooleanState::Id, BooleanState::Attributes::StateValue::Id, &contactVal);
87+
if (!ret) {
88+
log_e("Failed to update Contact Sensor Attribute.");
89+
return false;
90+
}
91+
contactState = _contactState;
92+
}
93+
log_v("Contact Sensor set to %s", _contactState ? "Closed" : "Open");
94+
95+
return true;
96+
}
97+
98+
#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#pragma once
16+
#include <sdkconfig.h>
17+
#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
18+
19+
#include <Matter.h>
20+
#include <MatterEndPoint.h>
21+
22+
class MatterContactSensor : public MatterEndPoint {
23+
public:
24+
MatterContactSensor();
25+
~MatterContactSensor();
26+
// begin Matter Contact Sensor endpoint with initial contact state
27+
bool begin(bool _contactState = false);
28+
// this will just stop processing Contact Sensor Matter events
29+
void end();
30+
31+
// set the contact state
32+
bool setContact(bool _contactState);
33+
// returns the contact state
34+
bool getContact() {
35+
return contactState;
36+
}
37+
38+
// bool conversion operator
39+
void operator=(bool _contactState) {
40+
setContact(_contactState);
41+
}
42+
// bool conversion operator
43+
operator bool() {
44+
return getContact();
45+
}
46+
47+
// this function is called by Matter internal event processor. It could be overwritten by the application, if necessary.
48+
bool attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val);
49+
50+
protected:
51+
bool started = false;
52+
bool contactState = false;
53+
};
54+
#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */

0 commit comments

Comments
 (0)