-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathesp_matter_core.cpp
1956 lines (1704 loc) · 79.3 KB
/
esp_matter_core.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 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 <esp_check.h>
#include <esp_log.h>
#include <esp_matter.h>
#include <esp_matter_core.h>
#include <nvs.h>
#include <app/clusters/general-diagnostics-server/general-diagnostics-server.h>
#include <app/clusters/identify-server/identify-server.h>
#include <app/server/Dnssd.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <app/util/endpoint-config-api.h>
#include <credentials/DeviceAttestationCredsProvider.h>
#include <credentials/FabricTable.h>
#include <credentials/GroupDataProviderImpl.h>
#include <data-model-providers/codegen/Instance.h>
#include <lib/core/DataModelTypes.h>
#include <platform/CHIPDeviceLayer.h>
#include <platform/DeviceInfoProvider.h>
#include <platform/DiagnosticDataProvider.h>
#include <platform/ESP32/ESP32Utils.h>
#include <esp_matter_ota.h>
#include <esp_matter_mem.h>
#include <esp_matter_providers.h>
#include <esp_matter_nvs.h>
#include <singly_linked_list.h>
using chip::CommandId;
using chip::DataVersion;
using chip::EventId;
using chip::kInvalidAttributeId;
using chip::kInvalidCommandId;
using chip::kInvalidClusterId;
using chip::kInvalidEndpointId;
using chip::Credentials::SetDeviceAttestationCredentialsProvider;
using chip::DeviceLayer::ChipDeviceEvent;
using chip::DeviceLayer::ConfigurationMgr;
using chip::DeviceLayer::ConnectivityManager;
using chip::DeviceLayer::ConnectivityMgr;
using chip::DeviceLayer::PlatformMgr;
using chip::DeviceLayer::DiagnosticDataProvider;
using chip::DeviceLayer::GetDiagnosticDataProvider;
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
using chip::DeviceLayer::ThreadStackMgr;
#endif
#define ESP_MATTER_NVS_PART_NAME CONFIG_ESP_MATTER_NVS_PART_NAME
#define ESP_MATTER_MAX_DEVICE_TYPE_COUNT CONFIG_ESP_MATTER_MAX_DEVICE_TYPE_COUNT
#define MAX_GROUPS_PER_FABRIC_PER_ENDPOINT CONFIG_MAX_GROUPS_PER_FABRIC_PER_ENDPOINT
static const char *TAG = "esp_matter_core";
static bool esp_matter_started = false;
#ifndef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
// If Matter Server is disabled, these functions are required by InteractionModelEngine but not linked
// as they are defined in other files. They will be never used if server is not enable. Define empty
// functions in esp_matter_core.cpp to make sure that they are linked
void InitDataModelHandler() {}
namespace chip {
namespace app {
void DispatchSingleClusterCommand(const ConcreteCommandPath &command_path, TLVReader &tlv_data,
CommandHandler *command_obj) {}
} // namespace app
} // namespace chip
bool emberAfContainsAttribute(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId)
{
return false;
}
#endif // !CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
namespace esp_matter {
namespace {
void PostEvent(uint16_t eventType)
{
chip::DeviceLayer::ChipDeviceEvent event;
event.Type = eventType;
CHIP_ERROR error = chip::DeviceLayer::PlatformMgr().PostEvent(&event);
VerifyOrReturn(error == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to post event for event type:%" PRIu16 ", err:%" CHIP_ERROR_FORMAT, eventType, error.Format()));
}
class AppDelegateImpl : public AppDelegate
{
public:
void OnCommissioningSessionStarted()
{
PostEvent(chip::DeviceLayer::DeviceEventType::kCommissioningSessionStarted);
}
void OnCommissioningSessionStopped()
{
PostEvent(chip::DeviceLayer::DeviceEventType::kCommissioningSessionStopped);
}
void OnCommissioningWindowOpened()
{
PostEvent(chip::DeviceLayer::DeviceEventType::kCommissioningWindowOpened);
}
void OnCommissioningWindowClosed()
{
PostEvent(chip::DeviceLayer::DeviceEventType::kCommissioningWindowClosed);
}
};
class FabricDelegateImpl : public chip::FabricTable::Delegate
{
public:
void FabricWillBeRemoved(const chip::FabricTable & fabricTable,chip::FabricIndex fabricIndex)
{
PostEvent(chip::DeviceLayer::DeviceEventType::kFabricWillBeRemoved);
}
void OnFabricRemoved(const chip::FabricTable & fabricTable,chip::FabricIndex fabricIndex)
{
PostEvent(chip::DeviceLayer::DeviceEventType::kFabricRemoved);
}
void OnFabricCommitted(const chip::FabricTable & fabricTable, chip::FabricIndex fabricIndex)
{
PostEvent(chip::DeviceLayer::DeviceEventType::kFabricCommitted);
}
void OnFabricUpdated(const chip::FabricTable & fabricTable, chip::FabricIndex fabricIndex)
{
PostEvent(chip::DeviceLayer::DeviceEventType::kFabricUpdated);
}
};
AppDelegateImpl s_app_delegate;
FabricDelegateImpl s_fabric_delegate;
} // namespace
struct _attribute_base_t {
uint16_t flags; // This struct is for attributes managed internally.
uint16_t index;
uint32_t attribute_id;
struct _attribute_base_t *next;
};
struct _attribute_t : public _attribute_base_t {
uint32_t cluster_id; // This struct is for attributes not managed internally.
esp_matter_attr_val_t val;
attribute::callback_t override_callback;
uint16_t endpoint_id;
};
typedef struct _command {
uint32_t command_id;
uint16_t flags;
command::callback_t callback;
command::callback_t user_callback;
struct _command *next;
} _command_t;
typedef struct _event {
uint32_t event_id;
struct _event *next;
} _event_t;
typedef struct _cluster {
uint8_t index;
uint16_t endpoint_id;
cluster::plugin_server_init_callback_t plugin_server_init_callback;
cluster::delegate_init_callback_t delegate_init_callback;
void * delegate_pointer;
cluster::add_bounds_callback_t add_bounds_callback;
_attribute_base_t *attribute_list; /* If attribute is managed internally, the actual pointer type is _internal_attribute_t.
When operating attribute_list, do check the flags first! */
EmberAfAttributeMetadata *matter_attributes;
_command_t *command_list;
_event_t *event_list;
struct _cluster *next;
} _cluster_t;
typedef struct _endpoint {
uint16_t endpoint_id;
uint8_t device_type_count;
uint8_t cluster_count;
uint8_t device_type_versions[ESP_MATTER_MAX_DEVICE_TYPE_COUNT];
uint32_t device_type_ids[ESP_MATTER_MAX_DEVICE_TYPE_COUNT];
uint16_t flags;
uint16_t parent_endpoint_id;
_cluster_t *cluster_list;
EmberAfEndpointType *endpoint_type;
DataVersion *data_versions_ptr;
EmberAfDeviceType *device_types_ptr;
void *priv_data;
Identify *identify;
struct _endpoint *next;
} _endpoint_t;
typedef struct _node {
_endpoint_t *endpoint_list;
uint16_t min_unused_endpoint_id;
} _node_t;
namespace node {
static _node_t *node = NULL;
#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL)
// If Matter server or ESP-Matter data model is not enabled. we will never use minimum unused endpoint id.
static esp_err_t store_min_unused_endpoint_id()
{
VerifyOrReturnError((node && esp_matter_started), ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node does not exist or esp_matter does not start"));
nvs_handle_t handle;
esp_err_t err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE,
NVS_READWRITE, &handle);
VerifyOrReturnError(err == ESP_OK, err, ESP_LOGE(TAG, "Failed to open the node nvs_namespace"));
err = nvs_set_u16(handle, "min_uu_ep_id", node->min_unused_endpoint_id);
nvs_commit(handle);
nvs_close(handle);
return err;
}
static esp_err_t read_min_unused_endpoint_id()
{
VerifyOrReturnError((node && esp_matter_started), ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node does not exist or esp_matter does not start"));
nvs_handle_t handle;
esp_err_t err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE,
NVS_READONLY, &handle);
if (err == ESP_OK) {
err = nvs_get_u16(handle, "min_uu_ep_id", &node->min_unused_endpoint_id);
nvs_close(handle);
}
if (err == ESP_ERR_NVS_NOT_FOUND) {
ESP_LOGI(TAG, "Cannot find minimum unused endpoint_id, try to find in the previous namespace");
// Try to read the minimum unused endpoint_id from the previous node namespace.
err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, "node", NVS_READONLY, &handle);
VerifyOrReturnError(err == ESP_OK, err, ESP_LOGI(TAG, "Failed to open node namespace"));
err = nvs_get_u16(handle, "min_uu_ep_id", &node->min_unused_endpoint_id);
nvs_close(handle);
if (err == ESP_OK) {
// If the minimum unused endpoint_id is got, we will erase it from the previous namespace
// and store it to the new namespace.
if (nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, "node", NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_erase_key(handle, "min_uu_ep_id") != ESP_OK) {
ESP_LOGE(TAG, "Failed to erase minimum unused endpoint_id");
} else {
nvs_commit(handle);
}
nvs_close(handle);
}
return store_min_unused_endpoint_id();
}
} else if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to get minimum unused endpoint_id in the %s nvs_namespace", ESP_MATTER_KVS_NAMESPACE);
}
return err;
}
#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL)
} /* node */
namespace command {
#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL)
command_entry_t *get_cluster_accepted_command_list(uint32_t cluster_id);
size_t get_cluster_accepted_command_count(uint32_t cluster_id);
command_entry_t *get_cluster_generated_command_list(uint32_t cluster_id);
size_t get_cluster_generated_command_count(uint32_t cluster_id);
#else
command_entry_t *get_cluster_accepted_command_list(uint32_t cluster_id) { return nullptr; }
size_t get_cluster_accepted_command_count(uint32_t cluster_id) { return 0; }
command_entry_t *get_cluster_generated_command_list(uint32_t cluster_id) { return nullptr; }
size_t get_cluster_generated_command_count(uint32_t cluster_id) {return 0; }
#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL)
} /* command */
namespace attribute {
esp_err_t get_data_from_attr_val(esp_matter_attr_val_t *val, EmberAfAttributeType *attribute_type,
uint16_t *attribute_size, uint8_t *value);
esp_err_t get_attr_val_from_data(esp_matter_attr_val_t *val, EmberAfAttributeType attribute_type,
uint16_t attribute_size, uint8_t *value,
const EmberAfAttributeMetadata * attribute_metadata);
static EmberAfAttributeMetadata *get_external_attribute_metadata(_attribute_t * attribute)
{
if (NULL == attribute || (attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) {
return NULL;
}
_cluster_t *cluster = (_cluster_t *)cluster::get(attribute->endpoint_id, attribute->cluster_id);
if (NULL == cluster) {
return NULL;
}
return &cluster->matter_attributes[attribute->index];
}
static esp_err_t free_default_value(attribute_t *attribute)
{
VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL"));
_attribute_t *current_attribute = (_attribute_t *)attribute;
EmberAfAttributeMetadata *matter_attribute = get_external_attribute_metadata(current_attribute);
if (!matter_attribute) {
ESP_LOGE(TAG, "Attribute Metadata is not found");
return ESP_ERR_NOT_FOUND;
}
/* Free value if data is more than 2 bytes or if it is min max attribute */
if (current_attribute->flags & ATTRIBUTE_FLAG_MIN_MAX) {
if (matter_attribute->size > 2) {
esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->defaultValue.ptrToDefaultValue);
esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->minValue.ptrToDefaultValue);
esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.ptrToDefaultValue);
}
esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue);
} else if (matter_attribute->size > 2) {
esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToDefaultValue);
}
return ESP_OK;
}
static EmberAfDefaultAttributeValue get_default_value_from_data(esp_matter_attr_val_t *val,
EmberAfAttributeType attribute_type,
uint16_t attribute_size)
{
EmberAfDefaultAttributeValue default_value = (uint16_t)0;
uint8_t *value = (uint8_t *)esp_matter_mem_calloc(1, attribute_size);
VerifyOrReturnValue(value, default_value, ESP_LOGE(TAG, "Could not allocate value buffer for default value"));
get_data_from_attr_val(val, &attribute_type, &attribute_size, value);
if (attribute_size > 2) {
/* Directly set the pointer */
default_value = value;
} else {
/* This data is 2 bytes or less. This should be represented as uint16. Copy the bytes appropriately
for 0 or 1 or 2 bytes to be converted to uint16. Then free the allocated buffer. */
uint16_t int_value = 0;
if (attribute_size == 2) {
memcpy(&int_value, value, attribute_size);
} else if (attribute_size == 1) {
int_value = (uint16_t)*value;
}
default_value = int_value;
esp_matter_mem_free(value);
}
return default_value;
}
static esp_err_t set_default_value_from_current_val(attribute_t *attribute, esp_matter_attr_val_t *min, esp_matter_attr_val_t *max)
{
VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL"));
_attribute_t *current_attribute = (_attribute_t *)attribute;
EmberAfAttributeMetadata *matter_attribute = get_external_attribute_metadata(current_attribute);
if (!matter_attribute) {
ESP_LOGE(TAG, "Attribute Metadata is not found");
return ESP_ERR_NOT_FOUND;
}
esp_matter_attr_val_t *val = ¤t_attribute->val;
/* Get size */
EmberAfAttributeType attribute_type = 0;
uint16_t attribute_size = 0;
get_data_from_attr_val(val, &attribute_type, &attribute_size, NULL);
/* Get and set value */
if (current_attribute->flags & ATTRIBUTE_FLAG_MIN_MAX) {
EmberAfAttributeMinMaxValue *temp_value = (EmberAfAttributeMinMaxValue *)esp_matter_mem_calloc(1,
sizeof(EmberAfAttributeMinMaxValue));
VerifyOrReturnError(temp_value, ESP_FAIL, ESP_LOGE(TAG, "Could not allocate ptrToMinMaxValue for default value"));
temp_value->defaultValue = get_default_value_from_data(val, attribute_type, attribute_size);
temp_value->minValue = get_default_value_from_data(min, attribute_type, attribute_size);
temp_value->maxValue = get_default_value_from_data(max, attribute_type, attribute_size);
matter_attribute->defaultValue.ptrToMinMaxValue = temp_value;
} else if (attribute_size > 2) {
EmberAfDefaultAttributeValue temp_value = get_default_value_from_data(val, attribute_type, attribute_size);
matter_attribute->defaultValue.ptrToDefaultValue = temp_value.ptrToDefaultValue;
} else {
EmberAfDefaultAttributeValue temp_value = get_default_value_from_data(val, attribute_type, attribute_size);
matter_attribute->defaultValue.defaultValue = temp_value.defaultValue;
}
return ESP_OK;
}
} /* attribute */
namespace endpoint {
static int get_next_index()
{
uint16_t endpoint_id = 0;
for (int index = 0; index < MAX_ENDPOINT_COUNT; index++) {
endpoint_id = emberAfEndpointFromIndex(index);
if (endpoint_id == kInvalidEndpointId) {
return index;
}
}
return 0xFFFF;
}
static esp_err_t disable(endpoint_t *endpoint)
{
/* Take lock if not already taken */
lock::status_t lock_status = lock::chip_stack_lock(portMAX_DELAY);
VerifyOrReturnError(lock_status != lock::FAILED, ESP_FAIL, ESP_LOGE(TAG, "Could not get task context"));
/* Remove endpoint */
_endpoint_t *current_endpoint = (_endpoint_t *)endpoint;
int endpoint_index = emberAfGetDynamicIndexFromEndpoint(current_endpoint->endpoint_id);
if (endpoint_index == 0xFFFF) {
ESP_LOGE(TAG, "Could not find endpoint index");
if (lock_status == lock::SUCCESS) {
lock::chip_stack_unlock();
}
return ESP_FAIL;
}
emberAfClearDynamicEndpoint(endpoint_index);
if (lock_status == lock::SUCCESS) {
lock::chip_stack_unlock();
}
/* Delete identify */
if (current_endpoint->identify) {
chip::Platform::Delete(current_endpoint->identify);
current_endpoint->identify = NULL;
}
return ESP_OK;
}
esp_err_t enable(endpoint_t *endpoint)
{
VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint cannot be NULL"));
_endpoint_t *current_endpoint = (_endpoint_t *)endpoint;
/* Device types */
EmberAfDeviceType *device_types_ptr = (EmberAfDeviceType *)esp_matter_mem_calloc(current_endpoint->device_type_count, sizeof(EmberAfDeviceType));
if (!device_types_ptr) {
ESP_LOGE(TAG, "Couldn't allocate device_types");
/* goto cleanup is not used here to avoid 'crosses initialization' of device_types below */
return ESP_ERR_NO_MEM;
}
for (size_t i = 0; i < current_endpoint->device_type_count; ++i) {
device_types_ptr[i].deviceId = current_endpoint->device_type_ids[i];
device_types_ptr[i].deviceVersion = current_endpoint->device_type_versions[i];
}
chip::Span<EmberAfDeviceType> device_types(device_types_ptr, current_endpoint->device_type_count);
current_endpoint->device_types_ptr = device_types_ptr;
/* Clusters */
_cluster_t *cluster = current_endpoint->cluster_list;
int cluster_count = SinglyLinkedList<_cluster_t>::count(cluster);
int cluster_index = 0;
DataVersion *data_versions_ptr = (DataVersion *)esp_matter_mem_calloc(1, cluster_count * sizeof(DataVersion));
if (!data_versions_ptr) {
ESP_LOGE(TAG, "Couldn't allocate data_versions");
esp_matter_mem_free(device_types_ptr);
current_endpoint->device_types_ptr = NULL;
/* goto cleanup is not used here to avoid 'crosses initialization' of data_versions below */
return ESP_ERR_NO_MEM;
}
chip::Span<chip::DataVersion> data_versions(data_versions_ptr, cluster_count);
current_endpoint->data_versions_ptr = data_versions_ptr;
/* Variables */
/* This is needed to avoid 'crosses initialization' errors because of goto */
esp_err_t err = ESP_OK;
lock::status_t lock_status = lock::FAILED;
CHIP_ERROR status = CHIP_NO_ERROR;
CommandId *accepted_command_ids = NULL;
CommandId *generated_command_ids = NULL;
_command_t *command = NULL;
command_entry_t *command_list = NULL;
uint32_t cluster_id = kInvalidClusterId;
int command_count = 0;
int command_index = 0;
int command_flag = COMMAND_FLAG_NONE;
EventId *event_ids = NULL;
_event_t *event = NULL;
int event_count = 0;
int event_index = 0;
int endpoint_index = 0;
while (cluster) {
/* Attributes */
/* Handled in attribute::create() */
/* Commands */
command = NULL;
command_count = 0;
command_index = 0;
command_flag = COMMAND_FLAG_NONE;
accepted_command_ids = NULL;
generated_command_ids = NULL;
cluster_id = cluster::get_id((cluster_t*)cluster);
/* Client Generated Commands */
command_flag = COMMAND_FLAG_ACCEPTED;
command = cluster->command_list;
command_count = SinglyLinkedList<_command_t>::count_with_flag(command, command_flag);
command_count += command::get_cluster_accepted_command_count(cluster_id);
if (command_count > 0) {
command_index = 0;
accepted_command_ids = (CommandId *)esp_matter_mem_calloc(1, (command_count + 1) * sizeof(CommandId));
if (!accepted_command_ids) {
ESP_LOGE(TAG, "Couldn't allocate accepted_command_ids");
err = ESP_ERR_NO_MEM;
break;
}
while (command) {
if (command->flags & command_flag) {
accepted_command_ids[command_index] = command->command_id;
command_index++;
}
command = command->next;
}
command_list = command::get_cluster_accepted_command_list(cluster_id);
for(size_t index = 0; command_index < command_count && command_list; index++) {
accepted_command_ids[command_index] = command_list[index].command_id;
command_index++;
}
accepted_command_ids[command_index] = kInvalidCommandId;
}
/* Server Generated Commands */
command_flag = COMMAND_FLAG_GENERATED;
command = cluster->command_list;
command_count = SinglyLinkedList<_command_t>::count_with_flag(command, command_flag);
command_count += command::get_cluster_generated_command_count(cluster_id);
if (command_count > 0) {
command_index = 0;
generated_command_ids = (CommandId *)esp_matter_mem_calloc(1, (command_count + 1) * sizeof(CommandId));
if (!generated_command_ids) {
ESP_LOGE(TAG, "Couldn't allocate generated_command_ids");
err = ESP_ERR_NO_MEM;
break;
}
while (command) {
if (command->flags & command_flag) {
generated_command_ids[command_index] = command->command_id;
command_index++;
}
command = command->next;
}
command_list = command::get_cluster_generated_command_list(cluster_id);
for(size_t index = 0; command_index < command_count && command_list; index++) {
generated_command_ids[command_index] = command_list[index].command_id;
command_index++;
}
generated_command_ids[command_index] = kInvalidCommandId;
}
/* Event */
event = cluster->event_list;
event_count = SinglyLinkedList<_event_t>::count(event);
if (event_count > 0) {
event_index = 0;
event_ids = (EventId *)esp_matter_mem_calloc(1, (event_count + 1) * sizeof(EventId));
if (!event_ids) {
ESP_LOGE(TAG, "Couldn't allocate event_ids");
err = ESP_ERR_NO_MEM;
break;
}
while (event) {
event_ids[event_index] = event->event_id;
event_index++;
event = event->next;
}
event_ids[event_index] = chip::kInvalidEventId;
}
/* Fill up the cluster */
EmberAfCluster *matter_clusters = (EmberAfCluster *)(¤t_endpoint->endpoint_type->cluster[cluster_index]);
matter_clusters->attributes = cluster->matter_attributes;
matter_clusters->acceptedCommandList = accepted_command_ids;
matter_clusters->generatedCommandList = generated_command_ids;
matter_clusters->eventList = event_ids;
matter_clusters->eventCount = event_count;
/* Get next cluster */
current_endpoint->endpoint_type->endpointSize += matter_clusters->clusterSize;
cluster = cluster->next;
cluster_index++;
/* This is to avoid double free in case of errors */
accepted_command_ids = NULL;
generated_command_ids = NULL;
event_ids = NULL;
}
if (err != ESP_OK) {
goto cleanup;
}
current_endpoint->endpoint_type->clusterCount = cluster_count;
/* Take lock if not already taken */
lock_status = lock::chip_stack_lock(portMAX_DELAY);
if (lock_status == lock::FAILED) {
ESP_LOGE(TAG, "Could not get task context");
goto cleanup;
}
/* Add Endpoint */
endpoint_index = endpoint::get_next_index();
status = emberAfSetDynamicEndpoint(endpoint_index, current_endpoint->endpoint_id, current_endpoint->endpoint_type, data_versions,
device_types, current_endpoint->parent_endpoint_id);
if (status != CHIP_NO_ERROR) {
ESP_LOGE(TAG, "Error adding dynamic endpoint %" PRIu16 ": %" CHIP_ERROR_FORMAT, current_endpoint->endpoint_id, status.Format());
err = ESP_FAIL;
if (lock_status == lock::SUCCESS) {
lock::chip_stack_unlock();
}
goto cleanup;
}
if (lock_status == lock::SUCCESS) {
lock::chip_stack_unlock();
}
ESP_LOGI(TAG, "Dynamic endpoint %" PRIu16 " added", current_endpoint->endpoint_id);
return err;
cleanup:
esp_matter_mem_free(generated_command_ids);
esp_matter_mem_free(accepted_command_ids);
esp_matter_mem_free(event_ids);
if (current_endpoint->endpoint_type->cluster) {
for (int cluster_index = 0; cluster_index < cluster_count; cluster_index++) {
/* Free attributes */
esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].attributes);
/* Free commands */
esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].acceptedCommandList);
esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].generatedCommandList);
/* Free events */
esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].eventList);
}
}
esp_matter_mem_free(data_versions_ptr);
current_endpoint->data_versions_ptr = NULL;
esp_matter_mem_free(device_types_ptr);
current_endpoint->device_types_ptr = NULL;
return err;
}
static esp_err_t enable_all()
{
node_t *node = node::get();
/* Not returning error, since the node will not be initialized for application using the data model from zap */
VerifyOrReturnError(node, ESP_OK);
endpoint_t *endpoint = get_first(node);
while (endpoint) {
enable(endpoint);
endpoint = get_next(endpoint);
}
return ESP_OK;
}
} /* endpoint */
namespace lock {
#define DEFAULT_TICKS (500 / portTICK_PERIOD_MS) /* 500 ms in ticks */
status_t chip_stack_lock(uint32_t ticks_to_wait)
{
#if CHIP_STACK_LOCK_TRACKING_ENABLED
VerifyOrReturnValue(!PlatformMgr().IsChipStackLockedByCurrentThread(), ALREADY_TAKEN);
#endif
VerifyOrReturnValue(ticks_to_wait != portMAX_DELAY, SUCCESS, PlatformMgr().LockChipStack());
uint32_t ticks_remaining = ticks_to_wait;
uint32_t ticks = DEFAULT_TICKS;
while (ticks_remaining > 0) {
VerifyOrReturnValue(!PlatformMgr().TryLockChipStack(), SUCCESS);
ticks = ticks_remaining < DEFAULT_TICKS ? ticks_remaining : DEFAULT_TICKS;
ticks_remaining -= ticks;
ESP_LOGI(TAG, "Did not get lock yet. Retrying...");
vTaskDelay(ticks);
}
ESP_LOGE(TAG, "Could not get lock");
return FAILED;
}
esp_err_t chip_stack_unlock()
{
PlatformMgr().UnlockChipStack();
return ESP_OK;
}
} /* lock */
#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
static void deinit_ble_if_commissioned(intptr_t unused)
{
#if CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING
if(chip::Server::GetInstance().GetFabricTable().FabricCount() > 0) {
chip::DeviceLayer::Internal::BLEMgr().Shutdown();
}
#endif /* CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING */
}
static void esp_matter_chip_init_task(intptr_t context)
{
TaskHandle_t task_to_notify = reinterpret_cast<TaskHandle_t>(context);
static chip::CommonCaseDeviceServerInitParams initParams;
initParams.InitializeStaticResourcesBeforeServerInit();
initParams.appDelegate = &s_app_delegate;
initParams.dataModelProvider = chip::app::CodegenDataModelProviderInstance(initParams.persistentStorageDelegate);
#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
// Group data provider injection for dynamic data model
{
uint8_t groups_server_cluster_count = cluster::groups::get_server_cluster_count();
uint16_t max_groups_per_fabric = groups_server_cluster_count * MAX_GROUPS_PER_FABRIC_PER_ENDPOINT;
// since groupDataProvider is a static variable, it won't be released.
static chip::Credentials::GroupDataProviderImpl groupDataProvider(max_groups_per_fabric, CHIP_CONFIG_MAX_GROUP_KEYS_PER_FABRIC);
groupDataProvider.SetStorageDelegate(initParams.persistentStorageDelegate);
groupDataProvider.SetSessionKeystore(initParams.sessionKeystore);
groupDataProvider.Init();
initParams.groupDataProvider = &groupDataProvider;
}
#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
CHIP_ERROR ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(&s_fabric_delegate);
if (ret != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Failed to add fabric delegate, err:%" CHIP_ERROR_FORMAT, ret.Format());
}
chip::Server::GetInstance().Init(initParams);
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#ifdef CONFIG_ESP_MATTER_ENABLE_OPENTHREAD
VerifyOrReturn(ThreadStackMgr().InitThreadStack() == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to initialize Thread stack"));
#if CHIP_CONFIG_ENABLE_ICD_SERVER
VerifyOrReturn(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice) == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to set the Thread device type"));
#elif CHIP_DEVICE_CONFIG_THREAD_FTD
VerifyOrReturn(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router) == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to set the Thread device type"));
#else
VerifyOrReturn(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice) == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to set the Thread device type"));
#endif
VerifyOrReturn(ThreadStackMgr().StartThreadTask() == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to launch Thread task"));
// If Thread is Provisioned, publish the dns service
if (chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned() &&
(chip::Server::GetInstance().GetFabricTable().FabricCount() != 0)) {
chip::app::DnssdServer::Instance().StartServer();
}
#endif // CONFIG_ESP_MATTER_ENABLE_OPENTHREAD
#endif
if (endpoint::enable_all() != ESP_OK) {
ESP_LOGE(TAG, "Enable all endpoints failure");
}
// The following two events can't be recorded when we start the server because the endpoints are not enabled.
// TODO: Find a better way to record the events which should be recorded in matter server init
// Record start up event in basic information cluster.
PlatformMgr().HandleServerStarted();
// Record boot reason evnet in general diagnostics cluster.
chip::app::Clusters::GeneralDiagnostics::BootReasonEnum bootReason;
if (GetDiagnosticDataProvider().GetBootReason(bootReason) == CHIP_NO_ERROR) {
chip::app::Clusters::GeneralDiagnosticsServer::Instance().OnDeviceReboot(bootReason);
}
PlatformMgr().ScheduleWork(deinit_ble_if_commissioned, reinterpret_cast<intptr_t>(nullptr));
xTaskNotifyGive(task_to_notify);
}
#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
static void device_callback_internal(const ChipDeviceEvent * event, intptr_t arg)
{
switch (event->Type)
{
case chip::DeviceLayer::DeviceEventType::kInterfaceIpAddressChanged:
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET
if (event->InterfaceIpAddressChanged.Type == chip::DeviceLayer::InterfaceIpChangeType::kIpV6_Assigned ||
event->InterfaceIpAddressChanged.Type == chip::DeviceLayer::InterfaceIpChangeType::kIpV4_Assigned) {
chip::app::DnssdServer::Instance().StartServer();
}
#endif
break;
#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
case chip::DeviceLayer::DeviceEventType::kDnssdInitialized:
esp_matter_ota_requestor_start();
/* Initialize binding manager */
client::binding_manager_init();
break;
case chip::DeviceLayer::DeviceEventType::kCommissioningComplete:
ESP_LOGI(TAG, "Commissioning Complete");
PlatformMgr().ScheduleWork(deinit_ble_if_commissioned, reinterpret_cast<intptr_t>(nullptr));
break;
case chip::DeviceLayer::DeviceEventType::kCHIPoBLEConnectionClosed:
ESP_LOGI(TAG, "BLE Disconnected");
break;
#endif
default:
break;
}
}
static esp_err_t chip_init(event_callback_t callback, intptr_t callback_arg)
{
VerifyOrReturnError(chip::Platform::MemoryInit() == CHIP_NO_ERROR, ESP_ERR_NO_MEM, ESP_LOGE(TAG, "Failed to initialize CHIP memory pool"));
VerifyOrReturnError(PlatformMgr().InitChipStack() == CHIP_NO_ERROR, ESP_FAIL, ESP_LOGE(TAG, "Failed to initialize CHIP stack"));
setup_providers();
// ConnectivityMgr().SetWiFiAPMode(ConnectivityManager::kWiFiAPMode_Enabled);
if (PlatformMgr().StartEventLoopTask() != CHIP_NO_ERROR) {
chip::Platform::MemoryShutdown();
ESP_LOGE(TAG, "Failed to launch Matter main task");
return ESP_FAIL;
}
PlatformMgr().AddEventHandler(device_callback_internal, static_cast<intptr_t>(NULL));
if(callback) {
PlatformMgr().AddEventHandler(callback, callback_arg);
}
#if CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
// Add bounds to all attributes
esp_matter::cluster::add_bounds_callback_common();
PlatformMgr().ScheduleWork(esp_matter_chip_init_task, reinterpret_cast<intptr_t>(xTaskGetCurrentTaskHandle()));
// Wait for the matter stack to be initialized
xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
// Initialise clusters which have delegate implemented
esp_matter::cluster::delegate_init_callback_common();
#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER
return ESP_OK;
}
esp_err_t start(event_callback_t callback, intptr_t callback_arg)
{
VerifyOrReturnError(!esp_matter_started, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "esp_matter has started"));
esp_err_t err = esp_event_loop_create_default();
// In case create event loop returns ESP_ERR_INVALID_STATE it is not necessary to fail startup
// as of it means that default event loop is already initialized and no additional actions should be done.
VerifyOrReturnError((err == ESP_OK || err == ESP_ERR_INVALID_STATE), err, ESP_LOGE(TAG, "Error create default event loop"));
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
VerifyOrReturnError(chip::DeviceLayer::Internal::ESP32Utils::InitWiFiStack() == CHIP_NO_ERROR, ESP_FAIL, ESP_LOGE(TAG, "Error initializing Wi-Fi stack"));
#endif
esp_matter_ota_requestor_init();
err = chip_init(callback, callback_arg);
VerifyOrReturnError(err == ESP_OK, err, ESP_LOGE(TAG, "Error initializing matter"));
esp_matter_started = true;
#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL)
err = node::read_min_unused_endpoint_id();
// If the min_unused_endpoint_id is not found, we will write the current min_unused_endpoint_id in nvs.
if (err == ESP_ERR_NVS_NOT_FOUND) {
err = node::store_min_unused_endpoint_id();
}
#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL)
return err;
}
esp_err_t factory_reset()
{
esp_err_t err = ESP_OK;
node_t *node = node::get();
if (node) {
/* ESP Matter data model is used. Erase all the data that we have added in nvs. */
nvs_handle_t handle;
err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE, NVS_READWRITE, &handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to open esp_matter nvs partition ");
} else {
err = nvs_erase_all(handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to erase esp_matter nvs namespace");
} else {
nvs_commit(handle);
}
nvs_close(handle);
}
}
/* Submodule factory reset. This also restarts after completion. */
ConfigurationMgr().InitiateFactoryReset();
return err;
}
namespace attribute {
attribute_t *create(cluster_t *cluster, uint32_t attribute_id, uint16_t flags, esp_matter_attr_val_t val,
uint16_t max_val_size)
{
/* Find */
VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL."));
_cluster_t *current_cluster = (_cluster_t *)cluster;
attribute_t *existing_attribute = get(cluster, attribute_id);
if (existing_attribute) {
ESP_LOGW(TAG, "Attribute 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", attribute_id,
cluster::get_id(cluster));
return existing_attribute;
}
endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id);
_endpoint_t *current_endpoint = (_endpoint_t *)endpoint;
/* Matter attributes */
EmberAfCluster *matter_clusters = (EmberAfCluster *)(¤t_endpoint->endpoint_type->cluster[current_cluster->index]);
matter_clusters->attributeCount++;
int attribute_count = matter_clusters->attributeCount;
if (current_cluster->matter_attributes) {
current_cluster->matter_attributes = (EmberAfAttributeMetadata *)esp_matter_mem_realloc(current_cluster->matter_attributes, attribute_count * sizeof(EmberAfAttributeMetadata));
} else {
current_cluster->matter_attributes = (EmberAfAttributeMetadata *)esp_matter_mem_calloc(1, attribute_count * sizeof(EmberAfAttributeMetadata));
}
if (!current_cluster->matter_attributes) {
ESP_LOGE(TAG, "Couldn't allocate matter_attributes");
return NULL;
}
/* Set */
EmberAfAttributeMetadata *matter_attribute = ¤t_cluster->matter_attributes[attribute_count - 1];
matter_attribute->attributeId = attribute_id;
/* esp-matter uses uint16_t as the flags for the extras, EmberAfAttributeMetadata uses uint8_t as the mask.
The conversion from uint16 to uint8 is as expected for that the extra flags are only used in esp-matter. */
matter_attribute->mask = static_cast<uint8_t>(flags);
if (!(flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) {
matter_attribute->mask |= ATTRIBUTE_FLAG_EXTERNAL_STORAGE;
}
matter_attribute->attributeType = 0;
matter_attribute->size = 0;
_attribute_t *attribute = NULL;
if (!(flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) {
/* Allocate */
attribute = (_attribute_t *)esp_matter_mem_calloc(1, sizeof(_attribute_t));
if (!attribute) {
ESP_LOGE(TAG, "Couldn't allocate _attribute_t");
return NULL;
}
attribute->index = attribute_count - 1;
attribute->attribute_id = attribute_id;
attribute->cluster_id = matter_clusters->clusterId;
attribute->endpoint_id = current_cluster->endpoint_id;
attribute->flags = flags;
attribute->flags |= ATTRIBUTE_FLAG_EXTERNAL_STORAGE;
// After reboot, string and array are treated as Invalid. So need to store val.type and size of attribute value.
attribute->val.type = val.type;
if (val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING ||
val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING ||
val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING ||
val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING ||
val.type == ESP_MATTER_VAL_TYPE_ARRAY) {
attribute->val.val.a.s = val.val.a.s;
attribute->val.val.a.n = val.val.a.n;
attribute->val.val.a.t = val.val.a.t;
}
bool attribute_updated = false;
if (flags & ATTRIBUTE_FLAG_NONVOLATILE) {
// Lets directly read into attribute->val so that we don't have to set the attribute value again.
esp_err_t err = get_val_from_nvs(attribute->endpoint_id, attribute->cluster_id, attribute_id,
attribute->val);
if (err == ESP_OK) {
attribute_updated = true;
}
}
if (!attribute_updated) {
set_val((attribute_t *)attribute, &val);
}
set_default_value_from_current_val((attribute_t *)attribute, NULL, NULL);
attribute::get_data_from_attr_val(&attribute->val, &matter_attribute->attributeType,
&matter_attribute->size, NULL);
if (attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING ||
attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING) {
uint16_t size_for_storing_str_len = attribute->val.val.a.t - attribute->val.val.a.s;
matter_attribute->size = max_val_size + size_for_storing_str_len;
}
matter_clusters->clusterSize += matter_attribute->size;
} else {
attribute = (_attribute_t *)esp_matter_mem_calloc(1, sizeof(_attribute_base_t));
attribute->attribute_id = attribute_id;
attribute->index = attribute_count - 1;
attribute->flags = flags;
}
/* Add */
SinglyLinkedList<_attribute_base_t>::append(¤t_cluster->attribute_list, attribute);
return (attribute_t *)attribute;
}