From 3fb4b86f76b26fe9f163205d9e7c9c8b87b0a651 Mon Sep 17 00:00:00 2001 From: Cecille Freeman Date: Sun, 20 Aug 2023 11:56:39 -0400 Subject: [PATCH] I fail at git --- admin_storage.json | 50 - kvs1 | 25 - kvs2 | 29 - scripts/py_matter_idl/BUILD.gn | 70 - .../build/lib/matter_idl/__init__.py | 0 .../lib/matter_idl/generators/__init__.py | 181 - .../lib/matter_idl/generators/cpp/__init__.py | 0 .../cpp/application/CallbackStubSource.jinja | 30 - .../PluginApplicationCallbacksHeader.jinja | 13 - .../generators/cpp/application/__init__.py | 62 - .../lib/matter_idl/generators/filters.py | 72 - .../generators/java/ChipClustersCpp.jinja | 216 - .../generators/java/ChipClustersRead.jinja | 54 - .../matter_idl/generators/java/__init__.py | 693 --- .../lib/matter_idl/generators/registry.py | 69 - .../build/lib/matter_idl/generators/types.py | 414 -- .../build/lib/matter_idl/lint/__init__.py | 17 - .../matter_idl/lint/lint_rules_grammar.lark | 34 - .../lib/matter_idl/lint/lint_rules_parser.py | 377 -- .../build/lib/matter_idl/lint/types.py | 347 -- .../build/lib/matter_idl/matter_grammar.lark | 113 - .../build/lib/matter_idl/matter_idl_parser.py | 574 -- .../build/lib/matter_idl/matter_idl_types.py | 270 - .../build/lib/matter_idl/test_generators.py | 177 - .../lib/matter_idl/test_matter_idl_parser.py | 601 -- .../build/lib/matter_idl/test_xml_parser.py | 382 -- .../build/lib/matter_idl/xml_parser.py | 76 - .../build/lib/matter_idl/zapxml/__init__.py | 122 - .../matter_idl/zapxml/handlers/__init__.py | 36 - .../lib/matter_idl/zapxml/handlers/base.py | 63 - .../lib/matter_idl/zapxml/handlers/context.py | 147 - .../matter_idl/zapxml/handlers/handlers.py | 661 --- .../lib/matter_idl/zapxml/handlers/parsing.py | 96 - scripts/py_matter_idl/examples/README.md | 25 - .../examples/matter_idl_plugin/__init__.py | 247 - .../matter_cluster_proto.jinja | 94 - scripts/py_matter_idl/files.gni | 51 - scripts/py_matter_idl/matter_idl/README.md | 239 - scripts/py_matter_idl/matter_idl/__init__.py | 0 .../matter_idl/generators/__init__.py | 181 - .../matter_idl/generators/cpp/__init__.py | 0 .../cpp/application/CallbackStubSource.jinja | 30 - .../PluginApplicationCallbacksHeader.jinja | 13 - .../generators/cpp/application/__init__.py | 62 - .../cpp/tlvmeta/TLVMetaData_cpp.jinja | 44 - .../cpp/tlvmeta/TLVMetaData_h.jinja | 12 - .../generators/cpp/tlvmeta/__init__.py | 315 -- .../matter_idl/generators/filters.py | 72 - .../generators/java/CHIPCallbackTypes.jinja | 40 - .../java/CHIPGlobalCallbacks_cpp.jinja | 76 - .../generators/java/CHIPReadCallbacks_h.jinja | 81 - .../generators/java/ChipClustersCpp.jinja | 216 - .../generators/java/ChipClustersRead.jinja | 54 - .../generators/java/ChipEventStructs.jinja | 153 - .../generators/java/ChipStructs.jinja | 153 - .../generators/java/ClusterIDMapping.jinja | 173 - .../generators/java/ClusterReadMapping.jinja | 59 - .../generators/java/ClusterWriteMapping.jinja | 67 - .../matter_idl/generators/java/__init__.py | 831 --- .../matter_idl/generators/registry.py | 74 - .../matter_idl/generators/types.py | 440 -- .../py_matter_idl/matter_idl/lint/__init__.py | 17 - .../matter_idl/lint/lint_rules_grammar.lark | 34 - .../matter_idl/lint/lint_rules_parser.py | 377 -- .../py_matter_idl/matter_idl/lint/types.py | 347 -- .../matter_idl/matter_grammar.lark | 113 - .../matter_idl/matter_idl_parser.py | 574 -- .../matter_idl/matter_idl_types.py | 275 - .../matter_idl/test_generators.py | 181 - .../matter_idl/test_matter_idl_parser.py | 601 -- .../matter_idl/test_xml_parser.py | 399 -- .../matter_idl/tests/available_tests.yaml | 88 - .../inputs/cluster_struct_attribute.matter | 11 - .../tests/inputs/cluster_with_commands.matter | 43 - .../inputs/global_struct_attribute.matter | 9 - .../inputs/large_all_clusters_app.matter | 4865 ----------------- .../tests/inputs/large_lighting_app.matter | 2065 ------- .../tests/inputs/optional_argument.matter | 7 - .../tests/inputs/several_clusters.matter | 52 - .../tests/inputs/simple_attribute.matter | 4 - .../cpp-tlvmeta/clusters_meta.cpp | 48 - .../cpp-tlvmeta/clusters_meta.h | 12 - .../jni/CHIPCallbackTypes.h | 28 - .../jni/CHIPReadReadCallbacks.h | 393 -- .../DemoClusterClient-InvokeSubscribeImpl.cpp | 58 - .../jni/DemoClusterClient-ReadImpl.cpp | 38 - .../cpp-tlvmeta/clusters_meta.cpp | 79 - .../cpp-tlvmeta/clusters_meta.h | 12 - .../jni/CHIPCallbackTypes.h | 28 - .../jni/CHIPReadReadCallbacks.h | 393 -- .../DemoClusterClient-InvokeSubscribeImpl.cpp | 58 - .../jni/DemoClusterClient-ReadImpl.cpp | 38 - .../cpp-app/PluginApplicationCallbacks.h | 130 - .../cpp-app/callback-stub.cpp | 529 -- .../cpp-app/PluginApplicationCallbacks.h | 56 - .../cpp-app/callback-stub.cpp | 233 - .../optional_argument/jni/CHIPCallbackTypes.h | 26 - .../jni/CHIPReadReadCallbacks.h | 341 -- .../MyClusterClient-InvokeSubscribeImpl.cpp | 81 - .../jni/MyClusterClient-ReadImpl.cpp | 14 - .../tests/outputs/proto/first_cluster.proto | 29 - ...ota_software_update_provider_cluster.proto | 107 - .../tests/outputs/proto/second_cluster.proto | 54 - .../tests/outputs/proto/third_cluster.proto | 54 - .../cpp-app/PluginApplicationCallbacks.h | 6 - .../cpp-app/callback-stub.cpp | 41 - .../java/ClusterIDMapping.java | 327 -- .../java/ClusterReadMapping.java | 104 - .../java/ClusterWriteMapping.java | 102 - .../SecondClusterFabricDescriptorStruct.kt | 82 - .../several_clusters/jni/CHIPCallbackTypes.h | 31 - .../jni/CHIPReadReadCallbacks.h | 423 -- .../jni/FirstClient-InvokeSubscribeImpl.cpp | 58 - .../jni/FirstClient-ReadImpl.cpp | 38 - .../jni/SecondClient-InvokeSubscribeImpl.cpp | 79 - .../jni/SecondClient-ReadImpl.cpp | 62 - .../jni/ThirdClient-InvokeSubscribeImpl.cpp | 79 - .../jni/ThirdClient-ReadImpl.cpp | 62 - .../shared/jni/CHIPGlobalCallbacks.cpp | 603 -- .../simple_attribute/jni/CHIPCallbackTypes.h | 27 - .../jni/CHIPReadReadCallbacks.h | 341 -- .../MyClusterClient-InvokeSubscribeImpl.cpp | 58 - .../jni/MyClusterClient-ReadImpl.cpp | 38 - .../py_matter_idl/matter_idl/xml_parser.py | 76 - .../matter_idl/zapxml/__init__.py | 122 - .../matter_idl/zapxml/handlers/__init__.py | 36 - .../matter_idl/zapxml/handlers/base.py | 63 - .../matter_idl/zapxml/handlers/context.py | 147 - .../matter_idl/zapxml/handlers/handlers.py | 661 --- .../matter_idl/zapxml/handlers/parsing.py | 114 - scripts/py_matter_idl/pyproject.toml | 17 - scripts/py_matter_idl/setup.cfg | 43 - scripts/py_matter_idl/setup.py | 20 - 133 files changed, 26634 deletions(-) delete mode 100644 admin_storage.json delete mode 100644 kvs1 delete mode 100644 kvs2 delete mode 100644 scripts/py_matter_idl/BUILD.gn delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/CallbackStubSource.jinja delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/filters.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersCpp.jinja delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersRead.jinja delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/java/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/registry.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/generators/types.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/lint/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_grammar.lark delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_parser.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/lint/types.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/matter_grammar.lark delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/matter_idl_parser.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/matter_idl_types.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/test_generators.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/test_matter_idl_parser.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/test_xml_parser.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/xml_parser.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/zapxml/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/__init__.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/base.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/context.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/handlers.py delete mode 100644 scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/parsing.py delete mode 100644 scripts/py_matter_idl/examples/README.md delete mode 100644 scripts/py_matter_idl/examples/matter_idl_plugin/__init__.py delete mode 100644 scripts/py_matter_idl/examples/matter_idl_plugin/matter_cluster_proto.jinja delete mode 100644 scripts/py_matter_idl/files.gni delete mode 100644 scripts/py_matter_idl/matter_idl/README.md delete mode 100644 scripts/py_matter_idl/matter_idl/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_cpp.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_h.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/filters.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/CHIPCallbackTypes.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/CHIPGlobalCallbacks_cpp.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/CHIPReadCallbacks_h.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ChipEventStructs.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ChipStructs.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ClusterIDMapping.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ClusterReadMapping.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/ClusterWriteMapping.jinja delete mode 100644 scripts/py_matter_idl/matter_idl/generators/java/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/registry.py delete mode 100644 scripts/py_matter_idl/matter_idl/generators/types.py delete mode 100644 scripts/py_matter_idl/matter_idl/lint/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/lint/lint_rules_grammar.lark delete mode 100755 scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py delete mode 100644 scripts/py_matter_idl/matter_idl/lint/types.py delete mode 100644 scripts/py_matter_idl/matter_idl/matter_grammar.lark delete mode 100755 scripts/py_matter_idl/matter_idl/matter_idl_parser.py delete mode 100644 scripts/py_matter_idl/matter_idl/matter_idl_types.py delete mode 100755 scripts/py_matter_idl/matter_idl/test_generators.py delete mode 100755 scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py delete mode 100755 scripts/py_matter_idl/matter_idl/test_xml_parser.py delete mode 100644 scripts/py_matter_idl/matter_idl/tests/available_tests.yaml delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/cluster_with_commands.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPCallbackTypes.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPReadReadCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPCallbackTypes.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPReadReadCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPCallbackTypes.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPReadReadCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/proto/first_cluster.proto delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/proto/ota_software_update_provider_cluster.proto delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/proto/second_cluster.proto delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/proto/third_cluster.proto delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterIDMapping.java delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterReadMapping.java delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterWriteMapping.java delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPCallbackTypes.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPReadReadCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/shared/jni/CHIPGlobalCallbacks.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPCallbackTypes.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPReadReadCallbacks.h delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp delete mode 100644 scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp delete mode 100755 scripts/py_matter_idl/matter_idl/xml_parser.py delete mode 100644 scripts/py_matter_idl/matter_idl/zapxml/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py delete mode 100644 scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py delete mode 100644 scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py delete mode 100644 scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py delete mode 100644 scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py delete mode 100644 scripts/py_matter_idl/pyproject.toml delete mode 100644 scripts/py_matter_idl/setup.cfg delete mode 100644 scripts/py_matter_idl/setup.py diff --git a/admin_storage.json b/admin_storage.json deleted file mode 100644 index 73009d341923a6..00000000000000 --- a/admin_storage.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "sdk-config": { - "g/lkgt": "FSYA6wRuLBg=", - "g/gcc": "zKMRCw==", - "g/gdc": "i8UCBQ==", - "ExampleOpCredsCAKey1": "BLILuwIzTEIvZ4YvGfU0T7K0mm3RPN5PR5aTGBFB7rBtrmMdt8oYBhP2uOViUMfwpi9aSk4zo+XwLEaqhrpTEQIwPToXMvctk6AZ1f5X0Fn2gChAYm70rw1TcqrkArBEYA==", - "ExampleOpCredsICAKey1": "BFrNLMeoK7hxO04zSI9+xu8XvnQc49gYdU7m7SN8kJmQZpUS3OyHt+pIRdjJAuYcLZCynKTwTOeazQbFofQ5MO9ecVlqsMNfhf60sgAVu39WOfnP4TUbad5mv9QE5Ozlsw==", - "ExampleCARootCert1": "MIIBlTCCATygAwIBAgIBATAKBggqhkjOPQQDAjAiMSAwHgYKKwYBBAGConwBBAwQMDAwMDAwMDAwMDAwMDAwMTAeFw0yMTAxMDEwMDAwMDBaFw0zMDEyMzAwMDAwMDBaMCIxIDAeBgorBgEEAYKifAEEDBAwMDAwMDAwMDAwMDAwMDAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEsgu7AjNMQi9nhi8Z9TRPsrSabdE83k9HlpMYEUHusG2uYx23yhgGE/a45WJQx/CmL1pKTjOj5fAsRqqGulMRAqNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPKgEJvK3AEoCNerSzusnmOM1TI1MB8GA1UdIwQYMBaAFPKgEJvK3AEoCNerSzusnmOM1TI1MAoGCCqGSM49BAMCA0cAMEQCIBTss+NThC2Kek+925BmqlSBB2A0Lqh7CN/DeIhvpWKqAiAQXTXvN3013W+Hx1pgj/dcSPGcToESpxvoSKcs+/mpPw==", - "ExampleCAIntermediateCert1": "MIIBlzCCATygAwIBAgIBATAKBggqhkjOPQQDAjAiMSAwHgYKKwYBBAGConwBBAwQMDAwMDAwMDAwMDAwMDAwMTAeFw0yMTAxMDEwMDAwMDBaFw0zMDEyMzAwMDAwMDBaMCIxIDAeBgorBgEEAYKifAEDDBAwMDAwMDAwMDAwMDAwMDAyMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWs0sx6gruHE7TjNIj37G7xe+dBzj2Bh1TubtI3yQmZBmlRLc7Ie36khF2MkC5hwtkLKcpPBM55rNBsWh9Dkw76NjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFCoJ280J0PvYypFO0cjczrUVN49sMB8GA1UdIwQYMBaAFPKgEJvK3AEoCNerSzusnmOM1TI1MAoGCCqGSM49BAMCA0kAMEYCIQCHS1XDAsmv8L3cVmSy1zkkOuDYQGDSiVlGhksFw5vRvgIhAIIibODFmVx/l89YSlKn+6feFrZRFTJOvKyLyZiNdeAY", - "f/1/m": "FSUA8f8sAQAY", - "f/1/n": "FTABAQEkAgE3AyQTAhgmBIAigScmBYAlTTo3BiQVASYRabYBABgkBwEkCAEwCUEEyEWG+TLNzevNiX9eTYbfJw2U++IQnwFIkWR+dmyLQ1tUQIEK3T1JUmzY3RP05+GHi5V9WhFFLfQKvR/T0ZiX8jcKNQEoARgkAgE2AwQCBAEYMAQU4TYFBLei+lhzAVzj3orWlixIKKswBRQqCdvNCdD72MqRTtHI3M61FTePbBgwC0Aow3mbMAveGe8pq+pvq92Qd0oqcve2Cl93QZuqnjkaj1Uv4uaQqxzfTurSKHXZxzpTYAO3DvxPOTEQuFIwtp4BGA==", - "f/1/i": "FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQTAhgkBwEkCAEwCUEEWs0sx6gruHE7TjNIj37G7xe+dBzj2Bh1TubtI3yQmZBmlRLc7Ie36khF2MkC5hwtkLKcpPBM55rNBsWh9Dkw7zcKNQEpARgkAmAwBBQqCdvNCdD72MqRTtHI3M61FTePbDAFFPKgEJvK3AEoCNerSzusnmOM1TI1GDALQIdLVcMCya/wvdxWZLLXOSQ64NhAYNKJWUaGSwXDm9G+giJs4MWZXH+Xz1hKUqf7p94WtlEVMk68rIvJmI114BgY", - "f/1/r": "FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQUARgkBwEkCAEwCUEEsgu7AjNMQi9nhi8Z9TRPsrSabdE83k9HlpMYEUHusG2uYx23yhgGE/a45WJQx/CmL1pKTjOj5fAsRqqGulMRAjcKNQEpARgkAmAwBBTyoBCbytwBKAjXq0s7rJ5jjNUyNTAFFPKgEJvK3AEoCNerSzusnmOM1TI1GDALQBTss+NThC2Kek+925BmqlSBB2A0Lqh7CN/DeIhvpWKqEF017zd9Nd1vh8daYI/3XEjxnE6BEqcb6EinLPv5qT8Y", - "g/fidx": "FSQAAzYBBAEEAhgY", - "f/1/k/0": "FSQBACQCATYDFSQEACUF7zswBhBtLszUzSX/5krCMGQgmsdjGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBglB///GA==", - "g/gfl": "FSQBAiQCAhg=", - "f/1/g": "FSQBACQCACQDACQEACQFACQGASQHABg=", - "f/1/s/0000000012344321": "FTADEH8QPxfJBiHiyEn8hJNnhDwwBCACIr1A1aHzeLlUvXDKMyFcPcZgfHZMsZOc/JZZvO4zXjAFDAAAAAAAAAAAAAAAABg=", - "g/s/fxA/F8kGIeLISfyEk2eEPA==": "FSQBASYCIUM0Ehg=", - "g/sri": "FhUkAQEmAiFDNBIYFSQBAiYCIUM0EhgY", - "ExampleOpCredsCAKey2": "BFftTdzRAgRiLY0sbefIilxMBrsaMsbjG56Vyv2pAZgbsuGIBbpKBivFrHwN0hzM3GXW2wlHKzowbob6yBHHstSyQ4teZLHd3NkennHU5MyOi6gyqiFX2LACZ59Ywee1vQ==", - "ExampleOpCredsICAKey2": "BIaugVjKJHTNVWQxmyY3dlomVTpvb67741iqAa0o7UdaB1WzQFF+YT771i9bmq1VYH37Da7jjU2tdEaEn3W4VALMV7jW2kl79X+/eZGQVqSNXdk/1PMWe0x0VrDTpNFn6Q==", - "ExampleCARootCert2": "MIIBljCCATygAwIBAgIBATAKBggqhkjOPQQDAjAiMSAwHgYKKwYBBAGConwBBAwQMDAwMDAwMDAwMDAwMDAwMTAeFw0yMTAxMDEwMDAwMDBaFw0zMDEyMzAwMDAwMDBaMCIxIDAeBgorBgEEAYKifAEEDBAwMDAwMDAwMDAwMDAwMDAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV+1N3NECBGItjSxt58iKXEwGuxoyxuMbnpXK/akBmBuy4YgFukoGK8WsfA3SHMzcZdbbCUcrOjBuhvrIEcey1KNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFGZsuuofq+hxCRoEoTG16yQ977ZVMB8GA1UdIwQYMBaAFGZsuuofq+hxCRoEoTG16yQ977ZVMAoGCCqGSM49BAMCA0gAMEUCIQC5Eslpy2Ytp1B9fLkWEFSQ16wQRicplYGN/yWqae8TDAIgUh/uPagY0WmB0FwYwhWVfrU+TprUyQxVqyAy2TgdWdU=", - "ExampleCAIntermediateCert2": "MIIBljCCATygAwIBAgIBATAKBggqhkjOPQQDAjAiMSAwHgYKKwYBBAGConwBBAwQMDAwMDAwMDAwMDAwMDAwMTAeFw0yMTAxMDEwMDAwMDBaFw0zMDEyMzAwMDAwMDBaMCIxIDAeBgorBgEEAYKifAEDDBAwMDAwMDAwMDAwMDAwMDAyMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhq6BWMokdM1VZDGbJjd2WiZVOm9vrvvjWKoBrSjtR1oHVbNAUX5hPvvWL1uarVVgffsNruONTa10RoSfdbhUAqNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFAKuj54vFLkiWLTmpcUFq+WH5gdrMB8GA1UdIwQYMBaAFGZsuuofq+hxCRoEoTG16yQ977ZVMAoGCCqGSM49BAMCA0gAMEUCIAcOlUv9gU78mn//q1X2nf7lQ11iYmbKD1AORbdG7GGKAiEAyTofIY+7I3lC15IDrpEIT4nwr+oWKQnubdcfQoAJJzY=", - "f/2/m": "FSUA8f8sAQAY", - "f/2/n": "FTABAQEkAgE3AyQTAhgmBIAigScmBYAlTTo3BiQVAiYRabYBABgkBwEkCAEwCUEErSFLH1IErGG/4utwMOmOQZ1NsK37XE1lo8QUl8/qEHCHRJVQeYw5yogid/XOHDIHWkN/WpSvbbfv1zNGLezhNjcKNQEoARgkAgE2AwQCBAEYMAQUhhmxbAJHkHE21NdhGCFvz0lwzr0wBRQCro+eLxS5Ili05qXFBavlh+YHaxgwC0AWqfekv23CkahvXa9rY0kEXnziys2iaWo3cNgrMTAP0YEfgxpX0FTdVtq5r0wIz+l66193SaE9YwYGS2ytlhDyGA==", - "f/2/i": "FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQTAhgkBwEkCAEwCUEEhq6BWMokdM1VZDGbJjd2WiZVOm9vrvvjWKoBrSjtR1oHVbNAUX5hPvvWL1uarVVgffsNruONTa10RoSfdbhUAjcKNQEpARgkAmAwBBQCro+eLxS5Ili05qXFBavlh+YHazAFFGZsuuofq+hxCRoEoTG16yQ977ZVGDALQAcOlUv9gU78mn//q1X2nf7lQ11iYmbKD1AORbdG7GGKyTofIY+7I3lC15IDrpEIT4nwr+oWKQnubdcfQoAJJzYY", - "f/2/r": "FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQUARgkBwEkCAEwCUEEV+1N3NECBGItjSxt58iKXEwGuxoyxuMbnpXK/akBmBuy4YgFukoGK8WsfA3SHMzcZdbbCUcrOjBuhvrIEcey1DcKNQEpARgkAmAwBBRmbLrqH6vocQkaBKExteskPe+2VTAFFGZsuuofq+hxCRoEoTG16yQ977ZVGDALQLkSyWnLZi2nUH18uRYQVJDXrBBGJymVgY3/Japp7xMMUh/uPagY0WmB0FwYwhWVfrU+TprUyQxVqyAy2TgdWdUY", - "f/2/k/0": "FSQBACQCATYDFSQEACUF8MwwBhA7CLIRXSRLIYlpCPIt50JrGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBglB///GA==", - "f/2/g": "FSQBACQCACQDACQEACQFACQGASQHARg=", - "f/2/s/0000000012344321": "FTADEOBABZv+2IJ+NG9zd+yvEPEwBCBJDqSrEWo9U/ZR8y3nn/hiyO9m93NQDtyqI+wO3iD0xDAFDAAAAAAAAAAAAAAAABg=", - "g/s/4EAFm/7Ygn40b3N37K8Q8Q==": "FSQBAiYCIUM0Ehg=" - }, - "repl-config": { - "caList": { - "1": [ - { - "fabricId": 1, - "vendorId": 65521 - } - ], - "2": [ - { - "fabricId": 2, - "vendorId": 65521 - } - ] - } - } -} \ No newline at end of file diff --git a/kvs1 b/kvs1 deleted file mode 100644 index a1f1c4dc3e67a9..00000000000000 --- a/kvs1 +++ /dev/null @@ -1,25 +0,0 @@ -[DEFAULT] -f/1/ac/0/0=FSQBBSQCAjYDBmm2AQAYNAQY -f/1/g=FSQBACQCACQDACQEACQFACQGASQHABg= -f/1/i=FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQTAhgkBwEkCAEwCUEEWs0sx6gruHE7TjNIj37G7xe+dBzj2Bh1TubtI3yQmZBmlRLc7Ie36khF2MkC5hwtkLKcpPBM55rNBsWh9Dkw7zcKNQEpARgkAmAwBBQqCdvNCdD72MqRTtHI3M61FTePbDAFFPKgEJvK3AEoCNerSzusnmOM1TI1GDALQIdLVcMCya/wvdxWZLLXOSQ64NhAYNKJWUaGSwXDm9G+giJs4MWZXH+Xz1hKUqf7p94WtlEVMk68rIvJmI114BgY -f/1/k/0=FSQBACQCATYDFSQEACUF7zswBhBtLszUzSX/5krCMGQgmsdjGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBglB///GA== -f/1/m=FSUA8f8sAQAY -f/1/n=FTABAQEkAgE3AyQTAhgmBIAigScmBYAlTTo3BiQVASYRIUM0EhgkBwEkCAEwCUEENm83n7plam5nfDdISoGPDtUDHJVnU+GybxGxUwoHQsGxmQHkeUkvO8h2fJAZEPU3vvdfsVrnaFa1X6qXK/qvtDcKNQEoARgkAgE2AwQCBAEYMAQUdfGm+y/WKUHF3ipj6LjAaVtA8w8wBRQqCdvNCdD72MqRTtHI3M61FTePbBgwC0Dls/4C/r3+KPMWKUN1DjXqepFbHZgLi7dm2qaiIFnfdNBKfbS38vhIva7bM916SWDpShrCVMz6RFbMhz1E4jYCGA== -f/1/o=FSQAATABYQQ2bzefumVqbmd8N0hKgY8O1QMclWdT4bJvEbFTCgdCwbGZAeR5SS87yHZ8kBkQ9Te+91+xWudoVrVfqpcr+q+0kcBpda0R4R7hfiswC80kGI09LyPO/ZVoolj4wA9/vd4Y -f/1/r=FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQUARgkBwEkCAEwCUEEsgu7AjNMQi9nhi8Z9TRPsrSabdE83k9HlpMYEUHusG2uYx23yhgGE/a45WJQx/CmL1pKTjOj5fAsRqqGulMRAjcKNQEpARgkAmAwBBTyoBCbytwBKAjXq0s7rJ5jjNUyNTAFFPKgEJvK3AEoCNerSzusnmOM1TI1GDALQBTss+NThC2Kek+925BmqlSBB2A0Lqh7CN/DeIhvpWKqEF017zd9Nd1vh8daYI/3XEjxnE6BEqcb6EinLPv5qT8Y -f/1/s/000000000001B669=FTADEH8QPxfJBiHiyEn8hJNnhDwwBCACIr1A1aHzeLlUvXDKMyFcPcZgfHZMsZOc/JZZvO4zXjAFDAAAAAAAAAAAAAAAABg= -g/a/0/2b/0=BWVuLVVT -g/a/1/102/7=Gw== -g/a/1/300/4001=Ag== -g/a/1/300/7=AAA= -g/a/1/8/0=/g== -g/fidx=FSQAAzYBBAEYGA== -g/gcc=AFGJAg== -g/gdc=KMsmCA== -g/gfl=FSQBASQCARg= -g/im/ec=AAABAAAAAAA= -g/lkgt=FSYAnD1uLBg= -g/s/fxA/F8kGIeLISfyEk2eEPA\x3d\x3d=FSQBASYCabYBABg= -g/sri=FhUkAQEmAmm2AQAYGA== -g/ts/tz=FhUgAAAkAQAsAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBg= - diff --git a/kvs2 b/kvs2 deleted file mode 100644 index 0e9267ea8657fc..00000000000000 --- a/kvs2 +++ /dev/null @@ -1,29 +0,0 @@ -[DEFAULT] -f/1/ac/0/0=FSQBBSQCAjYDBmm2AQAYNAQY -f/1/ac/0/1=FSQBASQCAjQDNgQVJAA4NAE0AhgYGA== -f/1/g=FSQBACQCACQDACQEACQFACQGASQHABg= -f/1/i=FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQTAhgkBwEkCAEwCUEE1tZ3ROPBAMzuKgPjv/9bXzCYMY/uoFkaia08jvZvJsZJCF8gDKX0dDuC97c6ag8LOOQJHUf61Bm1k/TpOpo9tjcKNQEpARgkAmAwBBQPYfF+Mww5+UXP2bgVUxbFTh1byzAFFMZ7Re3COvtoXAQNSIMsKFyWcp3qGDALQNU4+EPIUjfIPQH9PER2EAV9dmFZOVrNdSItkFC0tbPInaNwtNFkx3wGMj4Nu+v6WFAmTxpqaKC52MYbQKAYwxcY -f/1/k/0=FSQBACQCATYDFSQEBCUFkiEwBhBZKUYmJRitdSk8ZzJLc0sCGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBUkBAAkBQAwBhAAAAAAAAAAAAAAAAAAAAAAGBglB///GA== -f/1/m=FSUA8f8sAQAY -f/1/n=FTABAQEkAgE3AyQTAhgmBIAigScmBYAlTTo3BiQVASQRAhgkBwEkCAEwCUEEfE2/fiHDnJrMDbtGLKkIlqIqljUCf3s42FTTQyQocN8QI4xmnS8x/72VOR/n5gRj3p4PioWo8hnoHEpuK8yCYjcKNQEoARgkAgE2AwQCBAEYMAQUsgBhA0TLbZ6G0R9A0Wj+RiZJkF8wBRQPYfF+Mww5+UXP2bgVUxbFTh1byxgwC0CBwTXVdwHqGzil2IWsOUq+sLfGs2eRf4nqVPwbk2TbNNB273/6H798DKhkYg9vBjyy64fO1tQ8Re7OQz6JaJ8bGA== -f/1/o=FSQAATABYQR8Tb9+IcOcmswNu0YsqQiWoiqWNQJ/ezjYVNNDJChw3xAjjGadLzH/vZU5H+fmBGPeng+KhajyGegcSm4rzIJiaus2N1vmR23elcMED8aGc1yQNqZFK0RFb24Aj3b2izsY -f/1/r=FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQUARgkBwEkCAEwCUEE7f3SMyZPhdLN6Fde9/o/HKCHPCvW02JeFYXSVwtwbsIFUTs/cYusvS/H44A0glmFQmjyqwgeEuo8Z3aHkvyvUTcKNQEpARgkAmAwBBTGe0Xtwjr7aFwEDUiDLChclnKd6jAFFMZ7Re3COvtoXAQNSIMsKFyWcp3qGDALQPc19W5RHSUShnMn3GRu4+Vgb1aBsO2Dz5q75uvY1OZzp+pZGZXhVAIfMuF+Wl90McQQWbC48XUIo/65Snmd6WUY -f/1/s/000000000001B669=FTADEFAE6AocFq5HdYBIGLpgZ88wBCDe50dbFOzydA0jG1cVXJwe89EB2UOp+ZptqKV9q02q+TAFDAAAAAAAAAAAAAAAABg= -f/1/s/0000000012344321=FTADED7wy+4jO1tzmgg8/2aB6rowBCBNWMhriIBL8hZakYxSxEFj403yBH3CuLyYBkiVy/QvAzAFDAAAAAAAAAAAAAAAABg= -g/a/0/2b/0=BWVuLVVT -g/a/1/102/7=Gw== -g/a/1/300/4001=Ag== -g/a/1/300/7=AAA= -g/a/1/8/0=/g== -g/fidx=FSQAAjYBBAEYGA== -g/gcc=fCnaBw== -g/gdc=hLveBw== -g/gfl=FSQBASQCARg= -g/im/ec=AAACAAAAAAA= -g/lkgt=FSYASBJpLBg= -g/s/PvDL7iM7W3OaCDz/ZoHqug\x3d\x3d=FSQBASYCIUM0Ehg= -g/s/UAToChwWrkd1gEgYumBnzw\x3d\x3d=FSQBASYCabYBABg= -g/sri=FhUkAQEmAmm2AQAYFSQBASYCIUM0EhgY -g/sum=MAA= -g/ts/tz=FhUgAAAkAQAsAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBg= - diff --git a/scripts/py_matter_idl/BUILD.gn b/scripts/py_matter_idl/BUILD.gn deleted file mode 100644 index bd1975afe3b4c0..00000000000000 --- a/scripts/py_matter_idl/BUILD.gn +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build_overrides/build.gni") -import("//build_overrides/chip.gni") - -import("//build_overrides/pigweed.gni") -import("$dir_pw_build/python.gni") - -import("${chip_root}/scripts/py_matter_idl/files.gni") - -pw_python_package("matter_idl") { - setup = [ - "setup.py", - "setup.cfg", - "pyproject.toml", - ] - inputs = matter_idl_generator_templates - inputs += [ - # Dependency grammar - "matter_idl/matter_grammar.lark", - - # Unit test data - "matter_idl/tests/available_tests.yaml", - "matter_idl/tests/inputs/cluster_struct_attribute.matter", - "matter_idl/tests/inputs/global_struct_attribute.matter", - "matter_idl/tests/inputs/optional_argument.matter", - "matter_idl/tests/inputs/several_clusters.matter", - "matter_idl/tests/inputs/simple_attribute.matter", - "matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp", - "matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp", - "matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp", - "matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp", - "matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp", - "matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp", - "matter_idl/tests/outputs/several_clusters/java/ClusterIDMapping.java", - "matter_idl/tests/outputs/several_clusters/java/ClusterWriteMapping.java", - "matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp", - "matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp", - "matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp", - "matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp", - "matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp", - "matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp", - "matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp", - "matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp", - ] - - sources = matter_idl_generator_sources - - tests = [ - "matter_idl/test_matter_idl_parser.py", - "matter_idl/test_generators.py", - "matter_idl/test_xml_parser.py", - ] - - # TODO: at a future time consider enabling all (* or missing) here to get - # pylint checking these files - static_analysis = [] -} diff --git a/scripts/py_matter_idl/build/lib/matter_idl/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/__init__.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/__init__.py deleted file mode 100644 index 131d8e38ccbeba..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/__init__.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import os -from typing import Dict, Optional - -import jinja2 -from matter_idl.matter_idl_types import Idl - -from .filters import RegisterCommonFilters - - -class GeneratorStorage: - """ - Handles file operations for generator output. Specifically can create - required files for output. - - Is overriden for unit tests. - """ - - def __init__(self): - self._generated_paths = set() - - @property - def generated_paths(self): - return self._generated_paths - - def report_output_file(self, relative_path: str): - self._generated_paths.add(relative_path) - - def get_existing_data(self, relative_path: str): - """Gets the existing data at the given path. - If such data does not exist, will return None. - """ - raise NotImplementedError() - - def write_new_data(self, relative_path: str, content: str): - """Write new data to the given path.""" - raise NotImplementedError() - - -class FileSystemGeneratorStorage(GeneratorStorage): - """ - A storage generator which will physically write files to disk into - a given output folder. - """ - - def __init__(self, output_dir: str): - super().__init__() - self.output_dir = output_dir - - def get_existing_data(self, relative_path: str): - """Gets the existing data at the given path. - If such data does not exist, will return None. - """ - target = os.path.join(self.output_dir, relative_path) - - if not os.path.exists(target): - return None - - logging.info("Checking existing data in %s" % target) - with open(target, 'rt') as existing: - return existing.read() - - def write_new_data(self, relative_path: str, content: str): - """Write new data to the given path.""" - - target = os.path.join(self.output_dir, relative_path) - target_dir = os.path.dirname(target) - if not os.path.exists(target_dir): - logging.info("Creating output directory: %s" % target_dir) - os.makedirs(target_dir) - - logging.info("Writing new data to: %s" % target) - with open(target, "wt") as out: - out.write(content) - - -class CodeGenerator: - """ - Defines the general interface for things that can generate code output. - - A CodeGenerator takes a AST as input (a `Idl` type) and generates files - as output (like java/cpp/mm/other). - - Its public interface surface is reasonably small: - 'storage' init argument specifies where generated code goes - 'idl' is the input AST to generate - 'render' will perform a rendering of all files. - - As special optimizations, CodeGenerators generally will try to read - existing data and will not re-write content if not changed (so that - write time of files do not change and rebuilds are not triggered). - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, loader: Optional[jinja2.BaseLoader] = None, fs_loader_searchpath: Optional[str] = None): - """ - A code generator will render a parsed IDL (a AST) into a given storage. - - Args: - storage: Storage to use to read/save data - loader: if given, use a custom loader for templates - fs_loader_searchpath: if a loader is NOT given, this controls the search path - of a default FileSystemLoader that will be used - """ - if not loader: - if not fs_loader_searchpath: - fs_loader_searchpath = os.path.dirname(__file__) - loader = jinja2.FileSystemLoader(searchpath=fs_loader_searchpath) - - self.storage = storage - self.idl = idl - self.jinja_env = jinja2.Environment( - loader=loader, keep_trailing_newline=True) - self.dry_run = False - - RegisterCommonFilters(self.jinja_env.filters) - - def render(self, dry_run=False): - """ - Renders all required files given the idl contained in the code generator. - Reset the list of generated outputs. - - Args: - dry_run: if true, outputs are not actually written to disk. - if false, outputs are actually written to disk. - """ - self.dry_run = dry_run - self.internal_render_all() - - def internal_render_all(self): - """This method is to be implemented by subclasses to run all generation - as needed. - """ - raise NotImplementedError("Method should be implemented by subclasses") - - def internal_render_one_output(self, template_path: str, output_file_name: str, vars: Dict): - """ - Method to be called by subclasses to mark that a template is to be generated. - - File will either actually do a jinja2 generation or just log things - if dry-run was requested during `render`. - - NOTE: to make this method suitable for rebuilds, this file will NOT alter - the timestamp of the output file if the file content would not - change (i.e. no write will be invoked in that case.) - - Args: - template_path - the path to the template to be loaded for file generation. - Template MUST be a jinja2 template. - output_file_name - File name that the template is to be generated to. - vars - variables used for template generation - """ - logging.info("File to be generated: %s" % output_file_name) - if self.dry_run: - return - - rendered = self.jinja_env.get_template(template_path).render(vars) - - # Report regardless if it has changed or not. This is because even if - # files are unchanged, validation of what the correct output is should - # still be done. - self.storage.report_output_file(output_file_name) - - if rendered == self.storage.get_existing_data(output_file_name): - logging.info("File content not changed") - else: - self.storage.write_new_data(output_file_name, rendered) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/__init__.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/CallbackStubSource.jinja b/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/CallbackStubSource.jinja deleted file mode 100644 index cd800400dc4d10..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/CallbackStubSource.jinja +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include -#include -#include - -using namespace chip; - -// Cluster Init Functions -void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) -{ - switch (clusterId) - { - {%- for name in clusters | sort(attribute='name') | map(attribute='name') | unique %} - case app::Clusters::{{name}}::Id: - emberAf{{name}}ClusterInitCallback(endpoint); - break; - {%- endfor %} - default: - // Unrecognized cluster ID - break; - } -} - -{%- for name in clusters | sort(attribute='name') | map(attribute='name') | unique %} -void __attribute__((weak)) emberAf{{name}}ClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -{%- endfor %} diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja b/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja deleted file mode 100644 index 2e31426b3d05fc..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -{%- for cluster in clusters | serverClustersOnly | sort(attribute='name') %} -void Matter{{ cluster.name }}PluginServerInitCallback(); -{%- endfor %} - -#define MATTER_PLUGINS_INIT \ -{%- for cluster in clusters | serverClustersOnly | sort(attribute='name') %} - Matter{{ cluster.name }}PluginServerInitCallback();{{ " \\" if not loop.last else ""}} -{%- else %} - (void)0; /* No server side clusters */ -{%- endfor %} - diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/__init__.py deleted file mode 100644 index 2b9158864d28e4..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/cpp/application/__init__.py +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from typing import List - -from matter_idl.generators import CodeGenerator, GeneratorStorage -from matter_idl.matter_idl_types import Cluster, ClusterSide, Idl - - -def serverClustersOnly(clusters: List[Cluster]) -> List[Cluster]: - return [c for c in clusters if c.side == ClusterSide.SERVER] - - -class CppApplicationGenerator(CodeGenerator): - """ - Generation of cpp code for application implementation for matter. - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, **kargs): - """ - Inintialization is specific for java generation and will add - filters as required by the java .jinja templates to function. - """ - super().__init__(storage, idl, fs_loader_searchpath=os.path.dirname(__file__)) - - self.jinja_env.filters['serverClustersOnly'] = serverClustersOnly - - def internal_render_all(self): - """ - Renders the cpp and header files required for applications - """ - - # Header containing a macro to initialize all cluster plugins - self.internal_render_one_output( - template_path="PluginApplicationCallbacksHeader.jinja", - output_file_name="app/PluginApplicationCallbacks.h", - vars={ - 'clusters': self.idl.clusters, - } - ) - - # Source for __attribute__(weak) implementations of all cluster - # initialization methods - self.internal_render_one_output( - template_path="CallbackStubSource.jinja", - output_file_name="app/callback-stub.cpp", - vars={ - 'clusters': self.idl.clusters, - } - ) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/filters.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/filters.py deleted file mode 100644 index b1ea94a7cd36c6..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/filters.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import stringcase - - -def normalize_acronyms(s: str) -> str: - """Replaces variations of acronyms when converting various words. - - Specifically when considering how to generate a CONST_CASE constant, - strings such as WiFi should not be WI_FI but rather WIFI - """ - return s.replace('WiFi', 'Wifi').replace('WI_FI', 'WIFI') - - -def lowfirst(s: str) -> str: - """Make the first letter lowercase. """ - return s[0].lower() + s[1:] - - -def upfirst(s: str) -> str: - """Make the first letter uppercase """ - return s[0].upper() + s[1:] - - -def lowfirst_except_acronym(s: str) -> str: - """Make the first letter lowercase assuming the string is already in - CamelCase. - - Differs from lowfirst because it checks the string for starting with - several uppercase, which is the case for acronyms (HVAC, ACL, WIFI), - in which case it will NOT lowercase first - """ - if len(s) >= 2: - if s[1].isupper(): - return s - - return lowfirst(s) - - -def RegisterCommonFilters(filtermap): - """ - Register filters that are NOT considered platform-generator specific. - - Codegen often needs standardized names, like "method names are CamelCase" - or "command names need-to-be-spinal-case" so these filters are often - generally registered on all generators. - """ - - # General casing for output naming - filtermap['camelcase'] = stringcase.camelcase - filtermap['capitalcase'] = stringcase.capitalcase - filtermap['constcase'] = stringcase.constcase - filtermap['pascalcase'] = stringcase.pascalcase - filtermap['snakecase'] = stringcase.snakecase - filtermap['spinalcase'] = stringcase.spinalcase - - filtermap['normalize_acronyms'] = normalize_acronyms - filtermap['lowfirst'] = lowfirst - filtermap['lowfirst_except_acronym'] = lowfirst_except_acronym - filtermap['upfirst'] = upfirst diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersCpp.jinja b/scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersCpp.jinja deleted file mode 100644 index 22812797373cdf..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersCpp.jinja +++ /dev/null @@ -1,216 +0,0 @@ -{%- macro encode_optional(target, source, depth, encodable) -%} - { - jobject optionalValue_{{depth}} = nullptr; - chip::JniReferences::GetInstance().GetOptionalValue({{source}}, optionalValue_{{depth}}); - if (optionalValue_{{depth}}) { - auto & definedValue_{{depth}} = {{target}}.Emplace(); - {{ encode_value( - "definedValue_{}".format(depth), - "optionalValue_{}".format(depth), - depth+1, - encodable.without_optional() - )}} - } - } -{%- endmacro %} - -{%- macro encode_nullable(target, source, depth, encodable) -%} - if ({{source}} == nullptr) { - {{target}}.SetNull(); - } else { - auto & nonNullValue_{{depth}} = {{target}}.SetNonNull(); - {{encode_value("nonNullValue_{}".format(depth), source, depth+1, encodable.without_nullable())}} - } -{%- endmacro %} - -{%- macro encode_list(target, source, depth, encodable) -%} - { - using ListType_{{depth}} = std::remove_reference_t; - using ListMemberType_{{depth}} = ListMemberTypeGetter::Type; - jint {{source}}Size; - chip::JniReferences::GetInstance().GetListSize({{source}}, {{source}}Size); - if ({{source}}Size != 0) { - auto * listHolder_{{depth}} = new ListHolder({{source}}Size); - listFreer.add(listHolder_{{depth}}); - - for (jint i_{{depth}} = 0; i_{{depth}} < {{source}}Size; ++i_{{depth}}) { - jobject element_{{depth}}; - chip::JniReferences::GetInstance().GetListItem({{source}}, i_{{depth}}, element_{{depth}}); - {{encode_value( - "listHolder_{}->mList[static_cast(i_{})]".format(depth, depth), - "element_{}".format(depth), - depth+1, encodable.without_list() - )}} - } - {{target}} = ListType_{{depth}}(listHolder_{{depth}}->mList, {{source}}Size); - } else { - {{target}} = ListType_{{depth}}(); - } - } -{%- endmacro %} - -{%- macro encode_value(target, source, depth, encodable) -%} - {%- if encodable.is_optional -%} - {{encode_optional(target, source, depth, encodable)}} - {%- elif encodable.is_nullable -%} - {{encode_nullable(target, source, depth, encodable)}} - {%- elif encodable.is_list -%} - {{encode_list(target, source, depth, encodable)}} - {%- elif encodable.is_octet_string -%} - cleanupByteArrays.push_back(chip::Platform::MakeUnique(env, static_cast({{source}}))); - {{target}} = cleanupByteArrays.back()->byteSpan(); - {%- elif encodable.is_char_string -%} - cleanupStrings.push_back(chip::Platform::MakeUnique(env, static_cast({{source}}))); - {{target}} = cleanupStrings.back()->charSpan(); - {%- elif encodable.is_struct -%} - {% set struct = encodable.get_underlying_struct() -%} - {% for field in struct.fields %} - {% set fieldEncodable = field | asEncodable(encodable.context) -%} - jobject {{source}}_{{field.name}}Item_{{depth}}; - chip::JniReferences::GetInstance().GetObjectField({{source}}, "{{field.name}}", "{{fieldEncodable.boxed_java_signature}}", {{source}}_{{field.name}}Item_{{depth}}); - {{ encode_value( - "{}.{}".format(target, field.name | lowercaseFirst), - "{}_{}Item_{}".format(source, field.name, depth), - depth + 1, - fieldEncodable - )}} - {%- endfor -%} - {%- elif encodable.is_enum -%} - {{target}} = static_cast>(chip::JniReferences::GetInstance().IntegerToPrimitive({{source}})); - {%- elif encodable.is_untyped_bitmap -%} - {{target}} = static_cast>(chip::JniReferences::GetInstance().{{encodable.boxed_java_type}}ToPrimitive({{source}})); - {%- elif encodable.is_bitmap -%} - {{target}}.SetRaw(static_cast::IntegerType>(chip::JniReferences::GetInstance().{{encodable.boxed_java_type}}ToPrimitive({{source}}))); - {% else -%} - {{target}} = static_cast>(chip::JniReferences::GetInstance().{{encodable.boxed_java_type}}ToPrimitive({{source}})); - {% endif -%} -{% endmacro -%} - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, {{cluster.name | capitalcase}}Cluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -{% for command in cluster.commands -%} - -JNI_METHOD(void, {{cluster.name | capitalcase}}Cluster, - {{command.name | lowercaseFirst}})(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, - {%- if command.input_param -%} - {%- for field in (cluster.structs | named(command.input_param)).fields -%} - {{ field | toBoxedJavaType }} {{field.name}}, - {%- endfor -%} - {%- endif -%} - jobject timedInvokeTimeoutMs) -{ - chip::DeviceLayer::StackLock lock; - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster; - - ListFreer listFreer; - chip::app::Clusters::{{cluster.name | capitalcase}}::Commands::{{command.name | capitalcase}}::Type request; - - std::vector> cleanupByteArrays; - std::vector> cleanupStrings; - {%- if command.input_param -%} - {%- for field in (cluster.structs | named(command.input_param)).fields -%} - {{ encode_value( - "request." + (field.name | lowercaseFirst), - (field.name | lowercaseFirst), - 0, - field | asEncodable(typeLookup) - )}} - {%- endfor -%} - {% endif %} - - {% set callbackName = command | commandCallbackName(cluster) %} - std::unique_ptr onSuccess( - Platform::New(callback), Platform::Delete); - std::unique_ptr onFailure(Platform::New(callback), Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native callback", CHIP_ERROR_NO_MEMORY)); - VerifyOrReturn(onFailure.get() != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native callback", CHIP_ERROR_NO_MEMORY)); - - cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error getting native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - {% if command.is_timed_invoke -%} - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall, chip::JniReferences::GetInstance().IntegerToPrimitive(timedInvokeTimeoutMs)); - {%- else -%} - if (timedInvokeTimeoutMs == nullptr) { - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall); - } else { - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall, chip::JniReferences::GetInstance().IntegerToPrimitive(timedInvokeTimeoutMs)); - } - {%- endif %} - VerifyOrReturn(err == CHIP_NO_ERROR, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error invoking command", CHIP_ERROR_INCORRECT_STATE)); - - onSuccess.release(); - onFailure.release(); -} -{% endfor %} - -{%- for attr in cluster.attributes if attr.is_subscribable -%} -{%- if attr | canGenerateSubscribe(typeLookup) -%} - -JNI_METHOD(void, {{cluster.name}}Cluster, subscribe{{attr.definition.name | capitalcase}}Attribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock; - - {%- set callbackName = attr | callbackName(typeLookup) -%} - - std::unique_ptr<{{callbackName}}, void (*)({{callbackName}} *)> onSuccess(Platform::New<{{callbackName}}>(callback, true), chip::Platform::Delete<{{callbackName}}>); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::{{cluster.name}}::Attributes::{{attr.definition.name | capitalcase}}::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), {{callbackName}}::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - -{%- endif -%} -{% endfor %} diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersRead.jinja b/scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersRead.jinja deleted file mode 100644 index 96572922054095..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/java/ChipClustersRead.jinja +++ /dev/null @@ -1,54 +0,0 @@ -{# Copyright (c) 2022 Project CHIP Authors - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - #} -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -{%- for attr in cluster.attributes | attributesWithCallback(typeLookup) %} -JNI_METHOD(void, {{cluster.name | capitalcase}}Cluster, read{{attr.definition.name | capitalcase}}Attribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::{{cluster.name | capitalcase}}::Attributes::{{attr.definition.name | capitalcase}}::TypeInfo; - {%- set callbackName = attr | callbackName(typeLookup) %} - std::unique_ptr<{{callbackName}}, void (*)({{callbackName}} *)> onSuccess(chip::Platform::New<{{callbackName}}>(callback, false), chip::Platform::Delete<{{callbackName}}>); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - -{% endfor %} diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/java/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/java/__init__.py deleted file mode 100644 index 8f376704c4bd3b..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/java/__init__.py +++ /dev/null @@ -1,693 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import dataclasses -import enum -import logging -import os -from typing import List, Optional, Set - -from matter_idl.generators import CodeGenerator, GeneratorStorage -from matter_idl.generators.types import (BasicInteger, BasicString, FundamentalType, IdlBitmapType, IdlEnumType, IdlType, - ParseDataType, TypeLookupContext) -from matter_idl.matter_idl_types import (Attribute, Cluster, ClusterSide, Command, DataType, Field, FieldQuality, Idl, Struct, - StructTag) -from stringcase import capitalcase - - -@dataclasses.dataclass -class GenerateTarget: - template: str - output_name: str - - -@dataclasses.dataclass -class GlobalType: - name: str # java name - cpp_type: str # underlying type - - -# types that java should see globally -_GLOBAL_TYPES = [ - GlobalType("Boolean", "bool"), - GlobalType("CharString", "const chip::CharSpan"), - GlobalType("Double", "double"), - GlobalType("Float", "float"), - GlobalType("Int8s", "int8_t"), - GlobalType("Int8u", "uint8_t"), - GlobalType("Int16s", "int16_t"), - GlobalType("Int16u", "uint16_t"), - GlobalType("Int32s", "int32_t"), - GlobalType("Int32u", "uint32_t"), - GlobalType("Int64s", "int64_t"), - GlobalType("Int64u", "uint64_t"), - GlobalType("OctetString", "const chip::ByteSpan"), -] - - -def _UnderlyingType(field: Field, context: TypeLookupContext) -> Optional[str]: - actual = ParseDataType(field.data_type, context) - if isinstance(actual, (IdlEnumType, IdlBitmapType)): - actual = actual.base_type - - if isinstance(actual, BasicString): - if actual.is_binary: - return 'OctetString' - else: - return 'CharString' - elif isinstance(actual, BasicInteger): - if actual.is_signed: - return "Int{}s".format(actual.power_of_two_bits) - else: - return "Int{}u".format(actual.power_of_two_bits) - elif isinstance(actual, FundamentalType): - if actual == FundamentalType.BOOL: - return 'Boolean' - elif actual == FundamentalType.FLOAT: - return 'Float' - elif actual == FundamentalType.DOUBLE: - return 'Double' - else: - logging.warn('Unknown fundamental type: %r' % actual) - - return None - - -def FieldToGlobalName(field: Field, context: TypeLookupContext) -> Optional[str]: - """Global names are used for generic callbacks shared across - all clusters (e.g. for bool/float/uint32 and similar) - """ - if field.is_list: - return None # lists are always specific per cluster - - if FieldQuality.NULLABLE & field.qualities: - return None - - return _UnderlyingType(field, context) - - -# Based on atomicType in ZAP: -# src-electron/generator/matter/app/zap-templates/common/override.js -_KNOWN_DECODABLE_TYPES = { - 'action_id': 'chip::ActionId', - 'attrib_id': 'chip::AttributeId', - 'cluster_id': 'chip::ClusterId', - 'command_id': 'chip::CommandId', - 'data_ver': 'chip::DataVersion', - 'devtype_id': 'chip::DeviceTypeId', - 'endpoint_no': 'chip::EndpointId', - 'eui64': 'chip::NodeId', - 'event_id': 'chip::EventId', - 'event_no': 'chip::EventNumber', - 'fabric_id': 'chip::FabricId', - 'fabric_idx': 'chip::FabricIndex', - 'fabric_idx': 'chip::FabricIndex', - 'field_id': 'chip::FieldId', - 'group_id': 'chip::GroupId', - 'node_id': 'chip::NodeId', - 'percent': 'chip::Percent', - 'percent100ths': 'chip::Percent100ths', - 'transaction_id': 'chip::TransactionId', - 'vendor_id': 'chip::VendorId', - - # non-named enums - 'enum8': 'uint8_t', - 'enum16': 'uint16_t', - 'enum32': 'uint32_t', - 'enum64': 'uint64_t', -} - - -def _CppType(field: Field, context: TypeLookupContext) -> str: - if field.data_type.name.lower() in _KNOWN_DECODABLE_TYPES: - return _KNOWN_DECODABLE_TYPES[field.data_type.name.lower()] - - actual = ParseDataType(field.data_type, context) - if isinstance(actual, BasicString): - if actual.is_binary: - return 'chip::ByteSpan' - else: - return 'chip::CharSpan' - elif isinstance(actual, BasicInteger): - if actual.is_signed: - return "int{}_t".format(actual.power_of_two_bits) - else: - return "uint{}_t".format(actual.power_of_two_bits) - elif isinstance(actual, FundamentalType): - if actual == FundamentalType.BOOL: - return 'bool' - elif actual == FundamentalType.FLOAT: - return 'float' - elif actual == FundamentalType.DOUBLE: - return 'double' - else: - logging.warn('Unknown fundamental type: %r' % actual) - elif isinstance(actual, IdlType): - return f"chip::app::Clusters::{context.cluster.name}::Structs::{field.data_type.name}::DecodableType" - elif isinstance(actual, IdlBitmapType): - return f"chip::BitMask" - - # Handles IdlEnumType - return f"chip::app::Clusters::{context.cluster.name}::{field.data_type.name}" - - -def DecodableJniType(field: Field, context: TypeLookupContext) -> str: - actual = _CppType(field, context) - - needsConstRef = False - if field.is_list: - needsConstRef = True - actual = f"chip::app::DataModel::DecodableList<{actual}>" - - if field.is_nullable: - needsConstRef = True - actual = f"chip::app::DataModel::Nullable<{actual}>" - - if needsConstRef: - actual = f"const {actual} &" - - return actual - - -def GlobalNameToJavaName(name: str) -> str: - if name in {'Int8u', 'Int8s', 'Int16u', 'Int16s'}: - return 'Integer' - - if name.startswith('Int'): - return 'Long' - - # Double/Float/Booleans/CharString/OctetString - return name - - -def DelegatedCallbackName(attr: Attribute, context: TypeLookupContext) -> str: - """ - Figure out what callback name to use for delegate callback construction. - """ - global_name = FieldToGlobalName(attr.definition, context) - - if global_name: - return 'Delegated{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - - return 'Delegated{}Cluster{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) - - -def ChipClustersCallbackName(attr: Attribute, context: TypeLookupContext) -> str: - """ - Figure out what callback name to use when building a ChipCluster.*AttributeCallback - in java codegen. - """ - global_name = FieldToGlobalName(attr.definition, context) - - if global_name: - return 'ChipClusters.{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - - return 'ChipClusters.{}Cluster.{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) - - -def CallbackName(attr: Attribute, context: TypeLookupContext) -> str: - """ - Figure out what callback name to use when a variable requires a read callback. - - These are split into native types, like Boolean/Float/Double/CharString, where - one callback type can support anything. - - For specific types (e.g. A struct) codegen will generate its own callback name - specific to that type. - """ - global_name = FieldToGlobalName(attr.definition, context) - - if global_name: - return 'CHIP{}AttributeCallback'.format(capitalcase(global_name)) - - return 'CHIP{}{}AttributeCallback'.format( - capitalcase(context.cluster.name), - capitalcase(attr.definition.name) - ) - - -def CommandCallbackName(command: Command, cluster: Cluster): - if command.output_param.lower() == 'defaultsuccess': - return 'DefaultSuccess' - return '{}Cluster{}'.format(cluster.name, command.output_param) - - -def attributesWithSupportedCallback(attrs, context: TypeLookupContext): - for attr in attrs: - # Attributes will be generated for all types - # except non-list structures - if not attr.definition.is_list: - underlying = ParseDataType(attr.definition.data_type, context) - if isinstance(underlying, IdlType): - continue - - yield attr - - -def _IsUsingGlobalCallback(field: Field, context: TypeLookupContext): - """Test to determine if the data type of a field can use one of - the global callbacks (i.e. it is a basic double/integer/bool etc.) - """ - if field.is_list: - return False - - if field.is_nullable: - return False - - return field.data_type.name in { - "boolean", - "single", - "double", - "int8s", - "int8u", - "int16s", - "int16u", - "int24s", - "int24u", - "int32s", - "int32u", - "int40s", - "int40u", - "int48s", - "int48u", - "int56s", - "int56u", - "int64s", - "int64u", - "enum8", - "enum16", - "enum32", - "enum64", - "bitmap8", - "bitmap16", - "bitmap32", - "bitmap64", - "char_string", - "long_char_string", - "octet_string", - "long_octet_string", - } - - -def NamedFilter(choices: List, name: str): - for choice in choices: - if choice.name == name: - return choice - raise Exception("No item named %s in %r" % (name, choices)) - - -def ToBoxedJavaType(field: Field): - if field.is_optional: - return 'jobject' - elif field.data_type.name.lower() in ['octet_string', 'long_octet_string']: - return 'jbyteArray' - elif field.data_type.name.lower() in ['char_string', 'long_char_string']: - return 'jstring' - else: - return 'jobject' - - -def LowercaseFirst(name: str) -> str: - """ - Change the first letter of a string to lowercase as long as the 2nd - letter is not uppercase. - - Can be used for variable naming, eg insider structures, codegen will - call things "Foo foo" (notice variable name is lowercase). - """ - if len(name) > 1 and name[1].lower() != name[1]: - # Odd workaround: PAKEVerifier should not become pAKEVerifier - return name - return name[0].lower() + name[1:] - - -class EncodableValueAttr(enum.Enum): - LIST = enum.auto() - NULLABLE = enum.auto() - OPTIONAL = enum.auto() - - -class EncodableValue: - """ - Contains helpers for encoding values, specifically lookups - for optionality, lists and recursive data type lookups within - the IDL and cluster - - Intended use is to be able to: - - derive types (see clone and without_* methods) such that codegen - can implement things like 'if x != null { treat non-null x}' - - Java specific conversions: get boxed types and JNI string signautes - for the underlying types. - """ - - def __init__(self, context: TypeLookupContext, data_type: DataType, attrs: Set[EncodableValueAttr]): - self.context = context - self.data_type = data_type - self.attrs = attrs - - @property - def is_nullable(self): - return EncodableValueAttr.NULLABLE in self.attrs - - @property - def is_optional(self): - return EncodableValueAttr.OPTIONAL in self.attrs - - @property - def is_list(self): - return EncodableValueAttr.LIST in self.attrs - - @property - def is_octet_string(self): - return self.data_type.name.lower() in ['octet_string', 'long_octet_string'] - - @property - def is_char_string(self): - return self.data_type.name.lower() in ['char_string', 'long_char_string'] - - @property - def is_struct(self): - return self.context.is_struct_type(self.data_type.name) - - @property - def is_enum(self): - return self.context.is_enum_type(self.data_type.name) - - @property - def is_bitmap(self): - return self.context.is_bitmap_type(self.data_type.name) - - @property - def is_untyped_bitmap(self): - return self.context.is_untyped_bitmap_type(self.data_type.name) - - def clone(self): - return EncodableValue(self.context, self.data_type, self.attrs) - - def without_nullable(self): - result = self.clone() - result.attrs.remove(EncodableValueAttr.NULLABLE) - return result - - def without_optional(self): - result = self.clone() - result.attrs.remove(EncodableValueAttr.OPTIONAL) - return result - - def without_list(self): - result = self.clone() - result.attrs.remove(EncodableValueAttr.LIST) - return result - - def get_underlying_struct(self): - s = self.context.find_struct(self.data_type.name) - if not s: - raise Exception("Struct %s not found" % self.data_type.name) - return s - - def get_underlying_enum(self): - e = self.context.find_enum(self.data_type.name) - if not e: - raise Exception("Enum %s not found" % self.data_type.name) - return e - - @property - def boxed_java_type(self): - t = ParseDataType(self.data_type, self.context) - - if isinstance(t, FundamentalType): - if t == FundamentalType.BOOL: - return "Boolean" - elif t == FundamentalType.FLOAT: - return "Float" - elif t == FundamentalType.DOUBLE: - return "Double" - else: - raise Exception("Unknown fundamental type") - elif isinstance(t, BasicInteger): - # the >= 3 will include int24_t to be considered "long" - if t.byte_count >= 3: - return "Long" - else: - return "Integer" - elif isinstance(t, BasicString): - if t.is_binary: - return "byte[]" - else: - return "String" - elif isinstance(t, IdlEnumType): - if t.base_type.byte_count >= 3: - return "Long" - else: - return "Integer" - elif isinstance(t, IdlBitmapType): - if t.base_type.byte_count >= 3: - return "Long" - else: - return "Integer" - else: - return "Object" - - @property - def boxed_java_signature(self): - # Optional takes precedence over list - Optional compiles down to just java.util.Optional. - if self.is_optional: - return "Ljava/util/Optional;" - - if self.is_list: - return "Ljava/util/ArrayList;" - - t = ParseDataType(self.data_type, self.context) - - if isinstance(t, FundamentalType): - if t == FundamentalType.BOOL: - return "Ljava/lang/Boolean;" - elif t == FundamentalType.FLOAT: - return "Ljava/lang/Float;" - elif t == FundamentalType.DOUBLE: - return "Ljava/lang/Double;" - else: - raise Exception("Unknown fundamental type") - elif isinstance(t, BasicInteger): - if t.byte_count >= 3: - return "Ljava/lang/Long;" - else: - return "Ljava/lang/Integer;" - elif isinstance(t, BasicString): - if t.is_binary: - return "[B" - else: - return "Ljava/lang/String;" - elif isinstance(t, IdlEnumType): - if t.base_type.byte_count >= 3: - return "Ljava/lang/Long;" - else: - return "Ljava/lang/Integer;" - elif isinstance(t, IdlBitmapType): - if t.base_type.byte_count >= 3: - return "Ljava/lang/Long;" - else: - return "Ljava/lang/Integer;" - else: - return "Lchip/devicecontroller/ChipStructs${}Cluster{};".format(self.context.cluster.name, self.data_type.name) - - -def EncodableValueFrom(field: Field, context: TypeLookupContext) -> EncodableValue: - """ - Filter to convert a standard field to an EncodableValue. - - This converts the AST information (field name/info + lookup context) into - a java-generator specific wrapper that can be manipulated and - queried for properties like java native name or JNI string signature. - """ - attrs = set() - - if field.is_optional: - attrs.add(EncodableValueAttr.OPTIONAL) - - if field.is_nullable: - attrs.add(EncodableValueAttr.NULLABLE) - - if field.is_list: - attrs.add(EncodableValueAttr.LIST) - - return EncodableValue(context, field.data_type, attrs) - - -def CreateLookupContext(idl: Idl, cluster: Cluster) -> TypeLookupContext: - """ - A filter to mark a lookup context to be within a specific cluster. - - This is used to specify how structure/enum/other names are looked up. - Generally one looks up within the specific cluster then if cluster does - not contain a definition, we loop at global namespacing. - """ - return TypeLookupContext(idl, cluster) - - -def CanGenerateSubscribe(attr: Attribute, lookup: TypeLookupContext) -> bool: - """ - Filter that returns if an attribute can be subscribed to. - - Uses the given attribute and the lookupContext to figure out the attribute - type. - """ - # For backwards compatibility, we do not subscribe to structs - # (although list of structs is ok ...) - if attr.definition.is_list: - return True - - return not lookup.is_struct_type(attr.definition.data_type.name) - - -def IsResponseStruct(s: Struct) -> bool: - return s.tag == StructTag.RESPONSE - - -class __JavaCodeGenerator(CodeGenerator): - """ - Code generation for java-specific files. - - Registers filters used by all java generators. - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, **kargs): - """ - Inintialization is specific for java generation and will add - filters as required by the java .jinja templates to function. - """ - super().__init__(storage, idl, fs_loader_searchpath=os.path.dirname(__file__)) - - self.jinja_env.filters['attributesWithCallback'] = attributesWithSupportedCallback - self.jinja_env.filters['callbackName'] = CallbackName - self.jinja_env.filters['chipClustersCallbackName'] = ChipClustersCallbackName - self.jinja_env.filters['delegatedCallbackName'] = DelegatedCallbackName - self.jinja_env.filters['commandCallbackName'] = CommandCallbackName - self.jinja_env.filters['named'] = NamedFilter - self.jinja_env.filters['toBoxedJavaType'] = ToBoxedJavaType - self.jinja_env.filters['lowercaseFirst'] = LowercaseFirst - self.jinja_env.filters['asEncodable'] = EncodableValueFrom - self.jinja_env.filters['createLookupContext'] = CreateLookupContext - self.jinja_env.filters['canGenerateSubscribe'] = CanGenerateSubscribe - self.jinja_env.filters['decodableJniType'] = DecodableJniType - - self.jinja_env.tests['is_response_struct'] = IsResponseStruct - self.jinja_env.tests['is_using_global_callback'] = _IsUsingGlobalCallback - - -class JavaJNIGenerator(__JavaCodeGenerator): - """Generates JNI java files (i.e. C++ source/headers).""" - - def __init__(self, *args, **kargs): - super().__init__(*args, **kargs) - - def internal_render_all(self): - """ - Renders .CPP files required for JNI support. - """ - - large_targets = [ - GenerateTarget(template="CHIPCallbackTypes.jinja", - output_name="jni/CHIPCallbackTypes.h"), - GenerateTarget(template="CHIPReadCallbacks_h.jinja", - output_name="jni/CHIPReadCallbacks.h") - ] - - for target in large_targets: - self.internal_render_one_output( - template_path=target.template, - output_file_name=target.output_name, - vars={ - 'idl': self.idl, - 'clientClusters': [c for c in self.idl.clusters if c.side == ClusterSide.CLIENT], - 'globalTypes': _GLOBAL_TYPES, - } - ) - - cluster_targets = [ - GenerateTarget(template="ChipClustersRead.jinja", - output_name="jni/{cluster_name}Client-ReadImpl.cpp"), - GenerateTarget(template="ChipClustersCpp.jinja", - output_name="jni/{cluster_name}Client-InvokeSubscribeImpl.cpp"), - ] - - self.internal_render_one_output( - template_path="CHIPCallbackTypes.jinja", - output_file_name="jni/CHIPCallbackTypes.h", - vars={ - 'idl': self.idl, - 'clientClusters': [c for c in self.idl.clusters if c.side == ClusterSide.CLIENT], - } - ) - - # Every cluster has its own impl, to avoid - # very large compilations (running out of RAM) - for cluster in self.idl.clusters: - if cluster.side != ClusterSide.CLIENT: - continue - - for target in cluster_targets: - self.internal_render_one_output( - template_path=target.template, - output_file_name=target.output_name.format( - cluster_name=cluster.name), - vars={ - 'cluster': cluster, - 'typeLookup': TypeLookupContext(self.idl, cluster), - 'globalTypes': _GLOBAL_TYPES, - } - ) - - -class JavaClassGenerator(__JavaCodeGenerator): - """Generates .java files """ - - def __init__(self, *args, **kargs): - super().__init__(*args, **kargs) - - def internal_render_all(self): - """ - Renders .java files required for java matter support - """ - - clientClusters = [ - c for c in self.idl.clusters if c.side == ClusterSide.CLIENT] - - self.internal_render_one_output( - template_path="ClusterReadMapping.jinja", - output_file_name="java/chip/devicecontroller/ClusterReadMapping.java", - vars={ - 'idl': self.idl, - 'clientClusters': clientClusters, - } - ) - - self.internal_render_one_output( - template_path="ClusterWriteMapping.jinja", - output_file_name="java/chip/devicecontroller/ClusterWriteMapping.java", - vars={ - 'idl': self.idl, - 'clientClusters': clientClusters, - } - ) - - self.internal_render_one_output( - template_path="ClusterIDMapping.jinja", - output_file_name="java/chip/devicecontroller/ClusterIDMapping.java", - vars={ - 'idl': self.idl, - 'clientClusters': clientClusters, - } - ) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/registry.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/registry.py deleted file mode 100644 index 7f1e17bc4d05a7..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/registry.py +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum -import importlib - -from matter_idl.generators.cpp.application import CppApplicationGenerator -from matter_idl.generators.java import JavaClassGenerator, JavaJNIGenerator - - -class CodeGenerator(enum.Enum): - """ - Represents every generator type supported by codegen and maps - the simple enum value (user friendly and can be a command line input) - into underlying generators. - """ - JAVA_JNI = enum.auto() - JAVA_CLASS = enum.auto() - CPP_APPLICATION = enum.auto() - CUSTOM = enum.auto() - - def Create(self, *args, **kargs): - if self == CodeGenerator.JAVA_JNI: - return JavaJNIGenerator(*args, **kargs) - elif self == CodeGenerator.JAVA_CLASS: - return JavaClassGenerator(*args, **kargs) - elif self == CodeGenerator.CPP_APPLICATION: - return CppApplicationGenerator(*args, **kargs) - elif self == CodeGenerator.CUSTOM: - # Use a package naming convention to find the custom generator: - # ./matter_idl_plugin/__init__.py defines a subclass of CodeGenerator named CustomGenerator. - # The plugin is expected to be in the path provided via the `--plugin ` cli argument. - # Replaces `from plugin_module import CustomGenerator`` - plugin_module = importlib.import_module(kargs['plugin_module']) - CustomGenerator = plugin_module.CustomGenerator - return CustomGenerator(*args, **kargs) - else: - raise NameError("Unknown code generator type") - - @staticmethod - def FromString(name): - global GENERATORS - - if name.lower() in GENERATORS: - return GENERATORS[name.lower()] - else: - raise NameError("Unknown code generator type '%s'" % name) - - -# Contains all known code generators along with a string -# to uniquely identify them when running command line tools or -# executing tests -GENERATORS = { - 'java-jni': CodeGenerator.JAVA_JNI, - 'java-class': CodeGenerator.JAVA_CLASS, - 'cpp-app': CodeGenerator.CPP_APPLICATION, - 'custom': CodeGenerator.CUSTOM, -} diff --git a/scripts/py_matter_idl/build/lib/matter_idl/generators/types.py b/scripts/py_matter_idl/build/lib/matter_idl/generators/types.py deleted file mode 100644 index 393c444ae46060..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/generators/types.py +++ /dev/null @@ -1,414 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum -import logging -from dataclasses import dataclass -from typing import Optional, Union - -from matter_idl import matter_idl_types # to explicitly say 'Enum' -from matter_idl.matter_idl_types import DataType - - -def ToPowerOfTwo(bits: int) -> int: - """ - Given a number, find the next power of two that is >= to the given value. - - Can be used to figure out a variable size given non-standard bit sizes in - matter: eg. a int24 can be stored in an int32, so ToPortOfTwo(24) == 32. - - """ - # probably bit manipulation can be faster, but this should be ok as well - result = 1 - while result < bits: - result = result * 2 - return result - - -@dataclass -class BasicInteger: - """ - Represents something that is stored as a basic integer. - """ - idl_name: str - byte_count: int # NOTE: may NOT be a power of 2 for odd sized integers - is_signed: bool - - @property - def bits(self): - return self.byte_count * 8 - - @property - def power_of_two_bits(self): - return ToPowerOfTwo(self.bits) - - -@dataclass -class BasicString: - """ - Represents either a string or a binary string (blob). - """ - idl_name: str - is_binary: bool - max_length: Union[int, None] = None - - -class FundamentalType(enum.Enum): - """ - Native types, generally available across C++/ObjC/Java/python/other. - """ - BOOL = enum.auto() - FLOAT = enum.auto() - DOUBLE = enum.auto() - - @property - def idl_name(self): - if self == FundamentalType.BOOL: - return "bool" - elif self == FundamentalType.FLOAT: - return "single" - elif self == FundamentalType.DOUBLE: - return "double" - else: - raise Exception("Type not handled: %r" % self) - - @property - def byte_count(self): - if self == FundamentalType.BOOL: - return 1 - elif self == FundamentalType.FLOAT: - return 4 - elif self == FundamentalType.DOUBLE: - return 8 - else: - raise Exception("Type not handled: %r" % self) - - @property - def bits(self): - return self.byte_count * 8 - - -@dataclass -class IdlEnumType: - """ - An enumeration type. Enumerations are constants with an underlying - base type that is an interger. - """ - idl_name: str - base_type: BasicInteger - - @property - def byte_count(self): - return self.base_type.byte_count - - @property - def bits(self): - return self.base_type.bits - - -@dataclass -class IdlBitmapType: - """ - Bitmaps mark that each bit (or a subset of said bits) have a meaning. - - Examples include "feature maps" where bits represent feature available or not. - """ - idl_name: str - base_type: BasicInteger - - @property - def byte_count(self): - return self.base_type.byte_count - - @property - def bits(self): - return self.base_type.bits - - -class IdlItemType(enum.Enum): - UNKNOWN = enum.auto() - STRUCT = enum.auto() - - -@dataclass -class IdlType: - """ - A type defined within the IDL. - - IDLs would generally only define structures as all other types are - described in other things like enums/bitmaps/basic types etc. - - However since IDL parsing is not yet codegen just syntactically, we allow - the option to have a type that is marked 'unknown' (likely invalid/never - defined). - """ - idl_name: str - item_type: IdlItemType - - @property - def is_struct(self) -> bool: - return self.item_type == IdlItemType.STRUCT - - -# Data types, held by ZAP in chip-types.xml and generally by the spec. -__CHIP_SIZED_TYPES__ = { - "bitmap16": BasicInteger(idl_name="bitmap16", byte_count=2, is_signed=False), - "bitmap24": BasicInteger(idl_name="bitmap24", byte_count=3, is_signed=False), - "bitmap32": BasicInteger(idl_name="bitmap32", byte_count=4, is_signed=False), - "bitmap64": BasicInteger(idl_name="bitmap64", byte_count=8, is_signed=False), - "bitmap8": BasicInteger(idl_name="bitmap8", byte_count=1, is_signed=False), - "enum16": BasicInteger(idl_name="enum16", byte_count=2, is_signed=False), - "enum32": BasicInteger(idl_name="enum32", byte_count=4, is_signed=False), - "enum8": BasicInteger(idl_name="enum8", byte_count=1, is_signed=False), - "int16s": BasicInteger(idl_name="int16s", byte_count=2, is_signed=True), - "int16u": BasicInteger(idl_name="int16u", byte_count=2, is_signed=False), - "int24s": BasicInteger(idl_name="int24s", byte_count=3, is_signed=True), - "int24u": BasicInteger(idl_name="int24u", byte_count=3, is_signed=False), - "int32s": BasicInteger(idl_name="int32s", byte_count=4, is_signed=True), - "int32u": BasicInteger(idl_name="int32u", byte_count=4, is_signed=False), - "int40s": BasicInteger(idl_name="int40s", byte_count=5, is_signed=True), - "int40u": BasicInteger(idl_name="int40u", byte_count=5, is_signed=False), - "int48s": BasicInteger(idl_name="int48s", byte_count=6, is_signed=True), - "int48u": BasicInteger(idl_name="int48u", byte_count=6, is_signed=False), - "int56s": BasicInteger(idl_name="int56s", byte_count=7, is_signed=True), - "int56u": BasicInteger(idl_name="int56u", byte_count=7, is_signed=False), - "int64s": BasicInteger(idl_name="int64s", byte_count=8, is_signed=True), - "int64u": BasicInteger(idl_name="int64u", byte_count=8, is_signed=False), - "int8s": BasicInteger(idl_name="int8s", byte_count=1, is_signed=True), - "int8u": BasicInteger(idl_name="int8u", byte_count=1, is_signed=False), - # Derived types - # Specification describes them in section '7.18.2. Derived Data Types' - "action_id": BasicInteger(idl_name="action_id", byte_count=1, is_signed=False), - "attrib_id": BasicInteger(idl_name="attrib_id", byte_count=4, is_signed=False), - "cluster_id": BasicInteger(idl_name="cluster_id", byte_count=4, is_signed=False), - "command_id": BasicInteger(idl_name="command_id", byte_count=4, is_signed=False), - "data_ver": BasicInteger(idl_name="data_ver", byte_count=4, is_signed=False), - "date": BasicInteger(idl_name="date", byte_count=4, is_signed=False), - "devtype_id": BasicInteger(idl_name="devtype_id", byte_count=4, is_signed=False), - "endpoint_no": BasicInteger(idl_name="endpoint_no", byte_count=2, is_signed=False), - "epoch_s": BasicInteger(idl_name="epoch_s", byte_count=4, is_signed=False), - "epoch_us": BasicInteger(idl_name="epoch_us", byte_count=8, is_signed=False), - "elapsed_s": BasicInteger(idl_name="elapsed_s", byte_count=4, is_signed=False), - "event_id": BasicInteger(idl_name="event_id", byte_count=4, is_signed=False), - "event_no": BasicInteger(idl_name="event_no", byte_count=8, is_signed=False), - "fabric_id": BasicInteger(idl_name="fabric_id", byte_count=8, is_signed=False), - "fabric_idx": BasicInteger(idl_name="fabric_idx", byte_count=1, is_signed=False), - "field_id": BasicInteger(idl_name="field_id", byte_count=4, is_signed=False), - "group_id": BasicInteger(idl_name="group_id", byte_count=2, is_signed=False), - "node_id": BasicInteger(idl_name="node_id", byte_count=8, is_signed=False), - "percent": BasicInteger(idl_name="percent", byte_count=1, is_signed=False), - "percent100ths": BasicInteger(idl_name="percent100ths", byte_count=2, is_signed=False), - "posix_ms": BasicInteger(idl_name="posix_ms", byte_count=8, is_signed=False), - "status": BasicInteger(idl_name="status", byte_count=2, is_signed=False), - "systime_us": BasicInteger(idl_name="systime_us", byte_count=8, is_signed=False), - "systime_ms": BasicInteger(idl_name="systime_ms", byte_count=8, is_signed=False), - "temperature": BasicInteger(idl_name="temperature", byte_count=2, is_signed=True), - "tod": BasicInteger(idl_name="tod", byte_count=4, is_signed=False), - "trans_id": BasicInteger(idl_name="trans_id", byte_count=4, is_signed=False), - "vendor_id": BasicInteger(idl_name="vendor_id", byte_count=2, is_signed=False), -} - - -class TypeLookupContext: - """ - Handles type lookups within a scope. - - Generally when looking for a struct/enum, the lookup will be first done - at a cluster level, then at a global level. - - Example: - - ================ test.matter ============== - enum A {} - - server cluster X { - struct A {} - struct B {} - } - - server cluster Y { - enum C {} - } - =========================================== - - When considering a lookup context of global (i.e. cluster is not set) - "A" is defined as an enum (::A) - "B" is undefined - "C" is undefined - - When considering a lookup context of cluster X - "A" is defined as a struct (X::A) - "B" is defined as a struct (X::B) - "C" is undefined - - When considering a lookup context of cluster Y - "A" is defined as an enum (::A) - "B" is undefined - "C" is defined as an enum (Y::C) - - """ - - def __init__(self, idl: matter_idl_types.Idl, cluster: Optional[matter_idl_types.Cluster]): - self.idl = idl - self.cluster = cluster - - def find_enum(self, name) -> Optional[matter_idl_types.Enum]: - """ - Find the first enumeration matching the given name for the given - lookup rules (searches cluster first, then global). - """ - for e in self.all_enums: - if e.name == name: - return e - - return None - - def find_struct(self, name) -> Optional[matter_idl_types.Struct]: - for s in self.all_structs: - if s.name == name: - return s - - return None - - def find_bitmap(self, name) -> Optional[matter_idl_types.Bitmap]: - for s in self.all_bitmaps: - if s.name == name: - return s - - return None - - @property - def all_enums(self): - """ - All enumerations, ordered by lookup priority. - - If an enum A is defined both in the cluster and globally, this WILL - return both instances, however it will return the cluster version first. - """ - if self.cluster: - for e in self.cluster.enums: - yield e - for e in self.idl.enums: - yield e - - @property - def all_bitmaps(self): - """ - All bitmaps defined within this lookup context. - - bitmaps are only defined at cluster level. If lookup context does not - include a cluster, the bitmal list will be empty. - """ - if self.cluster: - for b in self.cluster.bitmaps: - yield b - - @property - def all_structs(self): - """All structs, ordered by lookup prioroty. - - If a struct A is defined both in the cluster and globally, this WILL - return both instances, however it will return the cluster version first. - """ - if self.cluster: - for e in self.cluster.structs: - yield e - for e in self.idl.structs: - yield e - - def is_enum_type(self, name: str): - """ - Determine if the given type name is an enumeration. - - Handles both standard names (like enum8) as well as enumerations defined - within the current lookup context. - """ - if name.lower() in ["enum8", "enum16", "enum32"]: - return True - return any(map(lambda e: e.name == name, self.all_enums)) - - def is_struct_type(self, name: str): - """ - Determine if the given type name is type that is known to be a struct - """ - return any(map(lambda s: s.name == name, self.all_structs)) - - def is_untyped_bitmap_type(self, name: str): - """Determine if the given type is a untyped bitmap (just an interger size).""" - return name.lower() in {"bitmap8", "bitmap16", "bitmap24", "bitmap32", "bitmap64"} - - def is_bitmap_type(self, name: str): - """ - Determine if the given type name is type that is known to be a bitmap. - - Handles both standard/zcl names (like bitmap32) and types defined within - the current lookup context. - """ - if self.is_untyped_bitmap_type(name): - return True - - return any(map(lambda s: s.name == name, self.all_bitmaps)) - - -def ParseDataType(data_type: DataType, lookup: TypeLookupContext) -> Union[BasicInteger, BasicString, FundamentalType, IdlType, IdlEnumType, IdlBitmapType]: - """ - Given a AST data type and a lookup context, match it to a type that can be later - be used for generation. - - AST parsing is textual, so it does not understand what "foo" means. This method - looks up what "foo" actually means: includes basic types (e.g. bool), - zcl types (like enums or bitmaps) and does lookups to find structs/enums/bitmaps/etc - that are defined in the given lookup context. - """ - - lowercase_name = data_type.name.lower() - - if lowercase_name == 'boolean': - return FundamentalType.BOOL - if lowercase_name == 'single': - return FundamentalType.FLOAT - elif lowercase_name == 'double': - return FundamentalType.DOUBLE - elif lowercase_name in ['char_string', 'long_char_string']: - return BasicString(idl_name=lowercase_name, is_binary=False, max_length=data_type.max_length) - elif lowercase_name in ['octet_string', 'long_octet_string']: - return BasicString(idl_name=lowercase_name, is_binary=True, max_length=data_type.max_length) - elif lowercase_name in ['enum8', 'enum16', 'enum32']: - return IdlEnumType(idl_name=lowercase_name, base_type=__CHIP_SIZED_TYPES__[lowercase_name]) - elif lowercase_name in ['bitmap8', 'bitmap16', 'bitmap24', 'bitmap32']: - return IdlBitmapType(idl_name=lowercase_name, base_type=__CHIP_SIZED_TYPES__[lowercase_name]) - - int_type = __CHIP_SIZED_TYPES__.get(lowercase_name, None) - if int_type is not None: - return int_type - - # All fast checks done, now check against known data types - e = lookup.find_enum(data_type.name) - if e: - # Valid enum found. it MUST be based on a valid data type - return IdlEnumType(idl_name=data_type.name, base_type=__CHIP_SIZED_TYPES__[e.base_type.lower()]) - - b = lookup.find_bitmap(data_type.name) - if b: - # Valid enum found. it MUST be based on a valid data type - return IdlBitmapType(idl_name=data_type.name, base_type=__CHIP_SIZED_TYPES__[b.base_type.lower()]) - - result = IdlType(idl_name=data_type.name, item_type=IdlItemType.UNKNOWN) - if lookup.find_struct(data_type.name): - result.item_type = IdlItemType.STRUCT - else: - logging.warning( - "Data type %s is NOT known, but treating it as a generic IDL type." % data_type) - - return result diff --git a/scripts/py_matter_idl/build/lib/matter_idl/lint/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/lint/__init__.py deleted file mode 100644 index 3ab2b9f7badd25..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/lint/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .lint_rules_parser import CreateParser - -__all__ = [CreateParser] diff --git a/scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_grammar.lark b/scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_grammar.lark deleted file mode 100644 index 90cfd6e8d441f7..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_grammar.lark +++ /dev/null @@ -1,34 +0,0 @@ -start: instruction* - -instruction: load_xml|all_endpoint_rule|specific_endpoint_rule - -load_xml: "load" ESCAPED_STRING ";" - -all_endpoint_rule: "all" "endpoints" "{" required_global_attribute* "}" - -specific_endpoint_rule: "endpoint" integer "{" (required_server_cluster|rejected_server_cluster)* "}" - -required_global_attribute: "require" "global" "attribute" id "=" integer ";" - -required_server_cluster: "require" "server" "cluster" (id|POSITIVE_INTEGER|HEX_INTEGER) ";" - -rejected_server_cluster: "reject" "server" "cluster" (id|POSITIVE_INTEGER|HEX_INTEGER) ";" - -integer: positive_integer | negative_integer - -positive_integer: POSITIVE_INTEGER | HEX_INTEGER -negative_integer: "-" positive_integer - -id: ID - -POSITIVE_INTEGER: /\d+/ -HEX_INTEGER: /0x[A-Fa-f0-9]+/ -ID: /[a-zA-Z_][a-zA-Z0-9_]*/ - -%import common.ESCAPED_STRING -%import common.WS -%import common.C_COMMENT -%import common.CPP_COMMENT -%ignore WS -%ignore C_COMMENT -%ignore CPP_COMMENT diff --git a/scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_parser.py b/scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_parser.py deleted file mode 100644 index 81a6158f13f542..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/lint/lint_rules_parser.py +++ /dev/null @@ -1,377 +0,0 @@ -#!/usr/bin/env python - -import logging -import os -import xml.etree.ElementTree -from dataclasses import dataclass -from enum import Enum, auto -from typing import List, MutableMapping, Tuple, Union - -from lark import Lark -from lark.visitors import Discard, Transformer, v_args - -try: - from .types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, ClusterValidationRule, - RequiredAttributesRule, RequiredCommandsRule) -except ImportError: - import sys - - sys.path.append(os.path.join(os.path.abspath( - os.path.dirname(__file__)), "..", "..")) - from matter_idl.lint.types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, ClusterValidationRule, - RequiredAttributesRule, RequiredCommandsRule) - - -class ElementNotFoundError(Exception): - def __init__(self, name): - super().__init__(f"Could not find {name}") - - -def parseNumberString(n: str) -> int: - if n.startswith('0x'): - return int(n[2:], 16) - else: - return int(n) - - -@dataclass -class RequiredAttribute: - name: str - code: int - - -@dataclass -class RequiredCommand: - name: str - code: int - - -@dataclass -class DecodedCluster: - name: str - code: int - required_attributes: List[RequiredAttribute] - required_commands: List[RequiredCommand] - - -class ClusterActionEnum(Enum): - REQUIRE = auto() - REJECT = auto() - - -@dataclass -class ServerClusterRequirement: - action: ClusterActionEnum - id: Union[str, int] - - -def DecodeClusterFromXml(element: xml.etree.ElementTree.Element): - if element.tag != 'cluster': - logging.error("Not a cluster element: %r" % element) - return None - - # cluster elements contain among other children - # - name (general name for this cluster) - # - code (unique identifier, may be hex or numeric) - # - attribute with side, code and optional attributes - try: - name = element.find('name') - if name is None or not name.text: - raise ElementNotFoundError('name') - - name = name.text.replace(' ', '') - required_attributes = [] - required_commands = [] - - for attr in element.findall('attribute'): - if attr.attrib['side'] != 'server': - continue - - if 'optional' in attr.attrib and attr.attrib['optional'] == 'true': - continue - - # when introducing access controls, the content of attributes may either be: - # myName - # or - # myName... - attr_name = attr.text - description = attr.find('description') - if description is not None: - attr_name = description.text - - required_attributes.append( - RequiredAttribute( - name=attr_name, - code=parseNumberString(attr.attrib['code']) - )) - - for cmd in element.findall('command'): - if cmd.attrib['source'] != 'client': - continue - - if 'optional' in cmd.attrib and cmd.attrib['optional'] == 'true': - continue - - required_commands.append(RequiredCommand( - name=cmd.attrib["name"], code=parseNumberString(cmd.attrib['code']))) - - code = element.find('code') - if code is None: - raise Exception("Failed to find cluster code") - - return DecodedCluster( - name=name, - code=parseNumberString(code.text), - required_attributes=required_attributes, - required_commands=required_commands - ) - except Exception: - logging.exception("Failed to decode cluster %r" % element) - return None - - -def ClustersInXmlFile(path: str): - logging.info("Loading XML from %s" % path) - - # root is expected to be just a "configurator" object - configurator = xml.etree.ElementTree.parse(path).getroot() - for child in configurator: - if child.tag != 'cluster': - continue - yield child - - -class LintRulesContext: - """Represents a context for loadint lint rules. - - Handles: - - loading referenced files (matter xml definitions) - - adding linter rules as data is parsed - - Looking up identifiers for various rules - """ - - def __init__(self): - self._required_attributes_rule = RequiredAttributesRule( - "Required attributes") - self._cluster_validation_rule = ClusterValidationRule( - "Cluster validation") - self._required_commands_rule = RequiredCommandsRule( - "Required commands") - - # Map cluster names to the underlying code - self._cluster_codes: MutableMapping[str, int] = {} - - def GetLinterRules(self): - return [self._required_attributes_rule, self._required_commands_rule, self._cluster_validation_rule] - - def RequireAttribute(self, r: AttributeRequirement): - self._required_attributes_rule.RequireAttribute(r) - - def FindClusterCode(self, name: str) -> Tuple[str, int]: - if name not in self._cluster_codes: - # Name may be a number. If this can be parsed as a number, accept it anyway - try: - return "ID_%s" % name, parseNumberString(name) - except ValueError: - logging.error("UNKNOWN cluster name %s" % name) - logging.error("Known names: %s" % - (",".join(self._cluster_codes.keys()), )) - return None - else: - return name, self._cluster_codes[name] - - def RequireClusterInEndpoint(self, name: str, code: int): - """Mark that a specific cluster is always required in the given endpoint - """ - cluster_info = self.FindClusterCode(name) - if not cluster_info: - return - - name, cluster_code = cluster_info - - self._cluster_validation_rule.RequireClusterInEndpoint(ClusterRequirement( - endpoint_id=code, - cluster_code=cluster_code, - cluster_name=name, - )) - - def RejectClusterInEndpoint(self, name: str, code: int): - """Mark that a specific cluster is always rejected in the given endpoint - """ - cluster_info = self.FindClusterCode(name) - if not cluster_info: - return - - name, cluster_code = cluster_info - - self._cluster_validation_rule.RejectClusterInEndpoint(ClusterRequirement( - endpoint_id=code, - cluster_code=cluster_code, - cluster_name=name, - )) - - def LoadXml(self, path: str): - """Load XML data from the given path and add it to - internal processing. Adds attribute requirement rules - as needed. - """ - for cluster in ClustersInXmlFile(path): - decoded = DecodeClusterFromXml(cluster) - - if not decoded: - continue - - self._cluster_codes[decoded.name] = decoded.code - - for attr in decoded.required_attributes: - self._required_attributes_rule.RequireAttribute(AttributeRequirement( - code=attr.code, name=attr.name, filter_cluster=decoded.code)) - - for cmd in decoded.required_commands: - self._required_commands_rule.RequireCommand( - ClusterCommandRequirement( - cluster_code=decoded.code, - command_code=cmd.code, - command_name=cmd.name - )) - - -class LintRulesTransformer(Transformer): - """ - A transformer capable to transform data parsed by Lark according to - lint_rules_grammar.lark. - """ - - def __init__(self, file_name: str): - self.context = LintRulesContext() - self.file_name = file_name - - def positive_integer(self, tokens): - """Numbers in the grammar are integers or hex numbers. - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - - return parseNumberString(tokens[0].value) - - @v_args(inline=True) - def negative_integer(self, value): - return -value - - @v_args(inline=True) - def integer(self, value): - return value - - def id(self, tokens): - """An id is a string containing an identifier - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - return tokens[0].value - - def ESCAPED_STRING(self, s): - # handle escapes, skip the start and end quotes - return s.value[1:-1].encode('utf-8').decode('unicode-escape') - - def start(self, instructions): - # At this point processing is considered done, return all - # linter rules that were found - return self.context.GetLinterRules() - - def instruction(self, instruction): - return Discard - - def all_endpoint_rule(self, attributes): - for attribute in attributes: - self.context.RequireAttribute(attribute) - - return Discard - - @v_args(inline=True) - def load_xml(self, path): - if not os.path.isabs(path): - path = os.path.abspath(os.path.join( - os.path.dirname(self.file_name), path)) - - self.context.LoadXml(path) - - @v_args(inline=True) - def required_global_attribute(self, name, code): - return AttributeRequirement(code=code, name=name) - - @v_args(inline=True) - def specific_endpoint_rule(self, code, *requirements): - for requirement in requirements: - if requirement.action == ClusterActionEnum.REQUIRE: - self.context.RequireClusterInEndpoint(requirement.id, code) - elif requirement.action == ClusterActionEnum.REJECT: - self.context.RejectClusterInEndpoint(requirement.id, code) - else: - raise Exception("Unexpected requirement action %r" % - requirement.action) - - return Discard - - @v_args(inline=True) - def required_server_cluster(self, id): - return ServerClusterRequirement(ClusterActionEnum.REQUIRE, id) - - @v_args(inline=True) - def rejected_server_cluster(self, id): - return ServerClusterRequirement(ClusterActionEnum.REJECT, id) - - -class Parser: - def __init__(self, parser, file_name: str): - self.parser = parser - self.file_name = file_name - - def parse(self): - data = LintRulesTransformer(self.file_name).transform( - self.parser.parse(open(self.file_name, "rt").read())) - return data - - -def CreateParser(file_name: str): - """ - Generates a parser that will process a ".matter" file into a IDL - """ - return Parser( - Lark.open('lint_rules_grammar.lark', rel_to=__file__, parser='lalr', propagate_positions=True), file_name=file_name) - - -if __name__ == '__main__': - # This Parser is generally not intended to be run as a stand-alone binary. - # The ability to run is for debug and to print out the parsed AST. - import click - - # Supported log levels, mapping string values required for argument - # parsing into logging constants - __LOG_LEVELS__ = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warn': logging.WARN, - 'fatal': logging.FATAL, - } - - @click.command() - @click.option( - '--log-level', - default='INFO', - type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), - help='Determines the verbosity of script output.') - @click.argument('filename') - def main(log_level, filename=None): - logging.basicConfig( - level=__LOG_LEVELS__[log_level], - format='%(asctime)s %(levelname)-7s %(message)s', - ) - - logging.info("Starting to parse ...") - data = CreateParser(filename).parse() - logging.info("Parse completed") - - logging.info("Data:") - logging.info("%r" % data) - - main(auto_envvar_prefix='CHIP') diff --git a/scripts/py_matter_idl/build/lib/matter_idl/lint/types.py b/scripts/py_matter_idl/build/lib/matter_idl/lint/types.py deleted file mode 100644 index 1b148ac430c47a..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/lint/types.py +++ /dev/null @@ -1,347 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from typing import List, MutableMapping, Optional - -from matter_idl.matter_idl_types import ClusterSide, Idl, ParseMetaData - - -class MissingIdlError(Exception): - def __init__(self): - super().__init__("Missing IDL data") - - -@dataclass -class LocationInFile: - file_name: str - line: Optional[int] - column: Optional[int] - - def __init__(self, file_name: str, meta: ParseMetaData): - self.file_name = file_name - self.line = meta.line - self.column = meta.column - - -@dataclass -class LintError: - """Represents a lint error, potentially at a specific location in a file""" - - message: str - location: Optional[LocationInFile] = field(default=None) - - def __init__(self, text: str, location: Optional[LocationInFile] = None): - self.message = text - if location: - self.message += " at %s:%d:%d" % (location.file_name, - location.line, location.column) - - def __str__(self): - return self.message - - -class LintRule(ABC): - """Validates a linter rule on an idl""" - - def __init__(self, name): - self.name = name - - @abstractmethod - def LintIdl(self, idl: Idl) -> List[LintError]: - """Runs the linter on the given IDL and returns back any errors it may find""" - pass - - -@dataclass -class AttributeRequirement: - """Contains information about a required attribute""" - code: int # required attributes are searched by codes - name: str # the name of this attribute. Expect it to be exposed properly - - # Optional filters to apply to specific locations - filter_cluster: Optional[int] = field(default=None) - - -@dataclass -class ClusterRequirement: - endpoint_id: int - cluster_code: int - cluster_name: str - - -class ErrorAccumulatingRule(LintRule): - """Contains a lint error list and helps helpers to add to such a list of rules.""" - - def __init__(self, name): - super(ErrorAccumulatingRule, self).__init__(name) - self._lint_errors = [] - self._idl = None - - def _AddLintError(self, text, location): - self._lint_errors.append( - LintError("%s: %s" % (self.name, text), location)) - - def _ParseLocation(self, meta: Optional[ParseMetaData]) -> Optional[LocationInFile]: - """Create a location in the current file that is being parsed. """ - if not meta or not self._idl or not self._idl.parse_file_name: - return None - return LocationInFile(self._idl.parse_file_name, meta) - - def LintIdl(self, idl: Idl) -> List[LintError]: - self._idl = idl - self._lint_errors = [] - self._LintImpl() - return self._lint_errors - - @abstractmethod - def _LintImpl(self): - """Implements actual linting of the IDL. - - Uses the underlying _idl for validation. - """ - pass - - -class ClusterValidationRule(ErrorAccumulatingRule): - def __init__(self, name): - super().__init__(name) - self._mandatory_clusters: List[ClusterRequirement] = [] - self._rejected_clusters: List[ClusterRequirement] = [] - - def __repr__(self): - result = "ClusterValidationRule{\n" - - if self._mandatory_clusters: - result += " mandatory_clusters:\n" - for cluster in self._mandatory_clusters: - result += " - %r\n" % cluster - - if self._rejected_clusters: - result += " rejected_clusters:\n" - for cluster in self._rejected_clusters: - result += " - %r\n" % cluster - - result += "}" - - return result - - def RequireClusterInEndpoint(self, requirement: ClusterRequirement): - self._mandatory_clusters.append(requirement) - - def RejectClusterInEndpoint(self, requirement: ClusterRequirement): - self._rejected_clusters.append(requirement) - - def _ClusterCode(self, name: str, location: Optional[LocationInFile]): - """Finds the server cluster definition with the given name. - - On error returns None and _lint_errors is updated internlly - """ - if not self._idl: - raise MissingIdlError() - - cluster_definition = [ - c for c in self._idl.clusters if c.name == name and c.side == ClusterSide.SERVER - ] - if not cluster_definition: - self._AddLintError( - "Cluster definition for %s not found" % name, location) - return None - - if len(cluster_definition) > 1: - self._AddLintError( - "Multiple cluster definitions found for %s" % name, location) - return None - - return cluster_definition[0].code - - def _LintImpl(self): - if not self._idl: - raise MissingIdlError() - - for endpoint in self._idl.endpoints: - cluster_codes = set() - for cluster in endpoint.server_clusters: - cluster_code = self._ClusterCode( - cluster.name, self._ParseLocation(cluster.parse_meta)) - if not cluster_code: - continue - - cluster_codes.add(cluster_code) - - for requirement in self._mandatory_clusters: - if requirement.endpoint_id != endpoint.number: - continue - - if requirement.cluster_code not in cluster_codes: - self._AddLintError("Endpoint %d DOES NOT expose cluster %s (%d)" % - (requirement.endpoint_id, requirement.cluster_name, requirement.cluster_code), location=None) - - for requirement in self._rejected_clusters: - if requirement.endpoint_id != endpoint.number: - continue - - if requirement.cluster_code in cluster_codes: - self._AddLintError("Endpoint %d EXPOSES cluster %s (%d)" % - (requirement.endpoint_id, requirement.cluster_name, requirement.cluster_code), location=None) - - -class RequiredAttributesRule(ErrorAccumulatingRule): - def __init__(self, name): - super().__init__(name) - self._mandatory_attributes: List[AttributeRequirement] = [] - - def __repr__(self): - result = "RequiredAttributesRule{\n" - - if self._mandatory_attributes: - result += " mandatory_attributes:\n" - for attr in self._mandatory_attributes: - result += " - %r\n" % attr - - result += "}" - return result - - def RequireAttribute(self, attr: AttributeRequirement): - """Mark an attribute required""" - self._mandatory_attributes.append(attr) - - def _ServerClusterDefinition(self, name: str, location: Optional[LocationInFile]): - """Finds the server cluster definition with the given name. - - On error returns None and _lint_errors is updated internlly - """ - if not self._idl: - raise MissingIdlError() - - cluster_definition = [ - c for c in self._idl.clusters if c.name == name and c.side == ClusterSide.SERVER - ] - if not cluster_definition: - self._AddLintError( - "Cluster definition for %s not found" % name, location) - return None - - if len(cluster_definition) > 1: - self._AddLintError( - "Multiple cluster definitions found for %s" % name, location) - return None - - return cluster_definition[0] - - def _LintImpl(self): - if not self._idl: - raise MissingIdlError() - - for endpoint in self._idl.endpoints: - - cluster_codes = set() - - for cluster in endpoint.server_clusters: - cluster_definition = self._ServerClusterDefinition( - cluster.name, self._ParseLocation(cluster.parse_meta)) - if not cluster_definition: - continue - - cluster_codes.add(cluster_definition.code) - - # Cluster contains enabled attributes by name - # cluster_definition contains the definition of the attributes themseves - # - # Join the two to receive attribute codes - name_to_code_map = {} - for attr in cluster_definition.attributes: - name_to_code_map[attr.definition.name] = attr.definition.code - - attribute_codes = set() - # For all the instantiated attributes, figure out their code - for attr in cluster.attributes: - if attr.name not in name_to_code_map: - self._AddLintError("Could not find attribute defintion (no code) for %s:%s" % - (cluster.name, attr.name), self._ParseLocation(cluster.parse_meta)) - continue - - attribute_codes.add(name_to_code_map[attr.name]) - - # Linting codes now - for check in self._mandatory_attributes: - if check.filter_cluster is not None and check.filter_cluster != cluster_definition.code: - continue - - if check.code not in attribute_codes: - self._AddLintError("EP%d:%s does not expose %s(%d) attribute" % - (endpoint.number, cluster.name, - check.name, check.code), - self._ParseLocation(cluster.parse_meta)) - - -@dataclass -class ClusterCommandRequirement: - cluster_code: int - command_code: int - command_name: str - - -class RequiredCommandsRule(ErrorAccumulatingRule): - def __init__(self, name): - super(RequiredCommandsRule, self).__init__(name) - - # Maps cluster id to mandatory cluster requirement - self._mandatory_commands: MutableMapping[int, - List[ClusterCommandRequirement]] = {} - - def __repr__(self): - result = "RequiredCommandsRule{\n" - - if self._mandatory_commands: - result += " mandatory_commands:\n" - for key, value in self._mandatory_commands.items(): - result += " - cluster %d:\n" % key - for requirement in value: - result += " - %r\n" % requirement - - result += "}" - return result - - def RequireCommand(self, cmd: ClusterCommandRequirement): - """Mark a command required""" - - if cmd.cluster_code in self._mandatory_commands: - self._mandatory_commands[cmd.cluster_code].append(cmd) - else: - self._mandatory_commands[cmd.cluster_code] = [cmd] - - def _LintImpl(self): - if not self._idl: - raise MissingIdlError() - - for cluster in self._idl.clusters: - if cluster.side != ClusterSide.SERVER: - continue # only validate server-side: - - if cluster.code not in self._mandatory_commands: - continue # no known mandatory commands - - defined_commands = set([c.code for c in cluster.commands]) - - for requirement in self._mandatory_commands[cluster.code]: - if requirement.command_code in defined_commands: - continue # command exists - - self._AddLintError( - "Cluster %s does not define mandatory command %s(%d)" % ( - cluster.name, requirement.command_name, requirement.command_code), - self._ParseLocation(cluster.parse_meta) - ) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/matter_grammar.lark b/scripts/py_matter_idl/build/lib/matter_idl/matter_grammar.lark deleted file mode 100644 index 6116e7cbf08071..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/matter_grammar.lark +++ /dev/null @@ -1,113 +0,0 @@ -struct: struct_qualities "struct"i id "{" (struct_field ";")* "}" -struct_quality: "fabric_scoped"i -> struct_fabric_scoped -struct_qualities: struct_quality* - -enum: "enum"i id ":" type "{" constant_entry* "}" -bitmap: "bitmap"i id ":" type "{" constant_entry* "}" - -?access_privilege: "view"i -> view_privilege - | "operate"i -> operate_privilege - | "manage"i -> manage_privilege - | "administer"i -> administer_privilege - -?attribute_access_type: "read"i -> read_access - | "write"i -> write_access - -event_access: "access" "(" ("read" ":" access_privilege)? ")" - -event_with_access: "event" event_access? id - -event: event_qualities event_priority event_with_access "=" positive_integer "{" (struct_field ";")* "}" - -event_quality: "fabric_sensitive" -> event_fabric_sensitive -event_qualities: event_quality* - -?event_priority: "critical"i -> critical_priority - | "info"i -> info_priority - | "debug"i -> debug_priority - -attribute_access_entry: attribute_access_type ":" access_privilege - -attribute_access: "access"i "(" (attribute_access_entry ("," attribute_access_entry)* )? ")" - -attribute_with_access: attribute_access? struct_field - -attribute: attribute_qualities "attribute"i attribute_with_access ";" -attribute_quality: "readonly"i -> attr_readonly - | "nosubscribe"i -> attr_nosubscribe - | "timedwrite"i -> attr_timed -attribute_qualities: attribute_quality* -> attribute_qualities - -request_struct: "request"i struct - -// Response structures must have a response id -response_struct: "response"i "struct"i id "=" positive_integer "{" (struct_field ";") * "}" - -command_quality: "timed"i -> timed_command - | "fabric"i -> fabric_scoped_command -command_qualities: command_quality* - -command_access: "access"i "(" ("invoke"i ":" access_privilege)? ")" - -command_with_access: "command"i command_access? id - -command: command_qualities command_with_access "(" id? ")" ":" id "=" positive_integer ";" - -cluster: cluster_side "cluster"i id "=" positive_integer "{" (enum|bitmap|event|attribute|struct|request_struct|response_struct|command)* "}" -?cluster_side: "server"i -> server_cluster - | "client"i -> client_cluster - -endpoint: "endpoint"i positive_integer "{" endpoint_content* "}" -?endpoint_content: endpoint_cluster_binding | endpoint_server_cluster | endpoint_device_type - -endpoint_device_type: "device" "type" id "=" positive_integer "," "version" positive_integer ";" -endpoint_cluster_binding: "binding"i "cluster"i id ";" -endpoint_server_cluster: "server"i "cluster"i id "{" endpoint_cluster_entry* "}" - - -endpoint_attribute_storage: "ram"i -> ram_attribute - | "persist"i -> persist_attribute - | "callback"i -> callback_attribute - -?endpoint_cluster_entry: endpoint_emitted_event | endpoint_attribute_instantiation - -endpoint_emitted_event: "emits"i "event"i id ";" -endpoint_attribute_instantiation: endpoint_attribute_storage "attribute"i id default_value? ";" - -bool_default: "true"i -> bool_default_true - | "false"i -> bool_default_false -?default_value: "default"i "=" (integer | ESCAPED_STRING | bool_default) - -constant_entry: id "=" positive_integer ";" -positive_integer: POSITIVE_INTEGER | HEX_INTEGER -negative_integer: "-" positive_integer - -integer: positive_integer | negative_integer - -struct_field: member_attribute* field - -member_attribute: "optional"i -> optional - | "nullable"i -> nullable - | "fabric_sensitive"i -> fabric_sensitive - -field: data_type id list_marker? "=" positive_integer -list_marker: "[" "]" - -data_type: type ("<" positive_integer ">")? - -id: ID -type: ID - -POSITIVE_INTEGER: /\d+/ -HEX_INTEGER: /0x[A-Fa-f0-9]+/ -ID: /[a-zA-Z_][a-zA-Z0-9_]*/ - -idl: (struct|enum|cluster|endpoint)* - -%import common.ESCAPED_STRING -%import common.WS -%import common.C_COMMENT -%import common.CPP_COMMENT -%ignore WS -%ignore C_COMMENT -%ignore CPP_COMMENT diff --git a/scripts/py_matter_idl/build/lib/matter_idl/matter_idl_parser.py b/scripts/py_matter_idl/build/lib/matter_idl/matter_idl_parser.py deleted file mode 100644 index f4ba7059bf605d..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/matter_idl_parser.py +++ /dev/null @@ -1,574 +0,0 @@ -#!/usr/bin/env python - -import functools -import logging -from typing import Optional - -from lark import Lark -from lark.lexer import Token -from lark.visitors import Transformer, v_args - -try: - from matter_idl.matter_idl_types import AccessPrivilege -except ModuleNotFoundError: - import os - import sys - sys.path.append(os.path.dirname( - os.path.dirname(os.path.abspath(__file__)))) - - from matter_idl.matter_idl_types import AccessPrivilege - -from matter_idl.matter_idl_types import (Attribute, AttributeInstantiation, AttributeOperation, AttributeQuality, AttributeStorage, - Bitmap, Cluster, ClusterSide, Command, CommandQuality, ConstantEntry, DataType, DeviceType, - Endpoint, Enum, Event, EventPriority, EventQuality, Field, FieldQuality, Idl, - ParseMetaData, ServerClusterInstantiation, Struct, StructQuality, StructTag) - - -def UnionOfAllFlags(flags_list): - if not flags_list: - return None - return functools.reduce(lambda a, b: a | b, flags_list) - - -class PrefixCppDocComment: - def __init__(self, token): - self.start_pos = token.start_pos - # Assume CPP comments: /**...*/ - self.value_len = len(token.value) # includes /***/ AND whitespace - self.value = token.value[3:-2].strip() - - def appply_to_idl(self, idl: Idl, content: str): - if self.start_pos is None: - return - - actual_pos = self.start_pos + self.value_len - while content[actual_pos] in ' \t\n\r': - actual_pos += 1 - - # A doc comment will apply to any supported element assuming it immediately - # preceeds id (skipping whitespace) - for item in self.supported_types(idl): - meta = item.parse_meta - if meta and meta.start_pos == actual_pos: - item.description = self.value - return - - def supported_types(self, idl: Idl): - """List all types supported by doc comments.""" - for cluster in idl.clusters: - yield cluster - - for command in cluster.commands: - yield command - - def __repr__(self): - return ("PREFIXDoc: %r at %r" % (self.value, self.start_pos)) - - -class AddServerClusterToEndpointTransform: - """Provides an 'apply' method that can be run on endpoints - to add a server cluster to the given endpoint. - """ - - def __init__(self, cluster: ServerClusterInstantiation): - self.cluster = cluster - - def apply(self, endpoint): - endpoint.server_clusters.append(self.cluster) - - -class AddBindingToEndpointTransform: - """Provides an 'apply' method that can be run on endpoints - to add a cluster binding to the given endpoint. - """ - - def __init__(self, name): - self.name = name - - def apply(self, endpoint): - endpoint.client_bindings.append(self.name) - - -class AddDeviceTypeToEndpointTransform: - """Provides an 'apply' method that can be run on endpoints - to add a device type to it - """ - - def __init__(self, device_type: DeviceType): - self.device_type = device_type - - def apply(self, endpoint): - endpoint.device_types.append(self.device_type) - - -class MatterIdlTransformer(Transformer): - """ - A transformer capable to transform data parsed by Lark according to - matter_grammar.lark. - - Generally transforms a ".matter" file into an Abstract Syntax Tree (AST). - End result will be a `matter_idl_types.Idl` value that represents the - entire parsed .matter file. - - The content of this file closely resembles the .lark input file and its - purpose is to convert LARK tokens (that ar generally inputted by name) - into underlying python types. - - Some documentation to get started is available at - https://lark-parser.readthedocs.io/en/latest/visitors.html#transformer - - TLDR would be: - When the ".lark" defines a token like `foo: number`, the transformer - has the option to define a method called `foo` which will take the - parsed input (as strings unless transformed) and interpret them. - - Actual parametes to the methods depend on the rules multiplicity and/or - optionally. - """ - - def __init__(self, skip_meta): - self.skip_meta = skip_meta - self.doc_comments = [] - self._cluster_start_pos = None - - def positive_integer(self, tokens): - """Numbers in the grammar are integers or hex numbers. - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - - n = tokens[0].value - if n.startswith('0x'): - return int(n[2:], 16) - else: - return int(n) - - @v_args(inline=True) - def negative_integer(self, value): - return -value - - @v_args(inline=True) - def integer(self, value): - return value - - def bool_default_true(self, _): - return True - - def bool_default_false(self, _): - return False - - def id(self, tokens): - """An id is a string containing an identifier - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - return tokens[0].value - - def type(self, tokens): - """A type is just a string for the type - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - return tokens[0].value - - def data_type(self, tokens): - if len(tokens) == 1: - return DataType(name=tokens[0]) - # Just a string for data type - elif len(tokens) == 2: - return DataType(name=tokens[0], max_length=tokens[1]) - else: - raise Exception("Unexpected size for data type") - - @v_args(inline=True) - def constant_entry(self, id, number): - return ConstantEntry(name=id, code=number) - - @v_args(inline=True) - def enum(self, id, type, *entries): - return Enum(name=id, base_type=type, entries=list(entries)) - - @v_args(inline=True) - def bitmap(self, id, type, *entries): - return Bitmap(name=id, base_type=type, entries=list(entries)) - - def field(self, args): - data_type, name = args[0], args[1] - is_list = (len(args) == 4) - code = args[-1] - - return Field(data_type=data_type, name=name, code=code, is_list=is_list) - - def optional(self, _): - return FieldQuality.OPTIONAL - - def nullable(self, _): - return FieldQuality.NULLABLE - - def fabric_sensitive(self, _): - return FieldQuality.FABRIC_SENSITIVE - - def attr_readonly(self, _): - return AttributeQuality.READABLE - - def attr_nosubscribe(self, _): - return AttributeQuality.NOSUBSCRIBE - - def attr_timed(self, _): - return AttributeQuality.TIMED_WRITE - - def attribute_qualities(self, qualities): - return UnionOfAllFlags(qualities) or AttributeQuality.NONE - - def struct_fabric_scoped(self, _): - return StructQuality.FABRIC_SCOPED - - def struct_qualities(self, qualities): - return UnionOfAllFlags(qualities) or StructQuality.NONE - - def critical_priority(self, _): - return EventPriority.CRITICAL - - def info_priority(self, _): - return EventPriority.INFO - - def debug_priority(self, _): - return EventPriority.DEBUG - - def event_fabric_sensitive(self, _): - return EventQuality.FABRIC_SENSITIVE - - def event_qualities(selt, qualities): - return UnionOfAllFlags(qualities) or EventQuality.NONE - - def timed_command(self, _): - return CommandQuality.TIMED_INVOKE - - def fabric_scoped_command(self, _): - return CommandQuality.FABRIC_SCOPED - - def command_qualities(self, attrs): - return UnionOfAllFlags(attrs) or CommandQuality.NONE - - def struct_field(self, args): - # Last argument is the named_member, the rest - # are qualities - field = args[-1] - field.qualities = UnionOfAllFlags(args[:-1]) or FieldQuality.NONE - return field - - @v_args(meta=True) - def server_cluster(self, meta, unused_args): - self._cluster_start_pos = meta and meta.start_pos - return ClusterSide.SERVER - - @v_args(meta=True, inline=True) - def client_cluster(self, meta, *unused_args): - self._cluster_start_pos = meta and meta.start_pos - return ClusterSide.CLIENT - - def command_access(self, privilege): - return privilege[0] - - def command_with_access(self, args): - # Arguments - # - optional access for invoke - # - event identifier (name) - init_args = { - "name": args[-1] - } - if len(args) > 1: - init_args["invokeacl"] = args[0] - - return init_args - - # NOTE: awkward inline because the order of 'meta, children' vs 'children, meta' was flipped - # between lark versions in https://github.com/lark-parser/lark/pull/993 - @v_args(meta=True, inline=True) - def command(self, meta, *args): - # The command takes 4 arguments if no input argument, 5 if input - # argument is provided - args = list(args) # convert from tuple - if len(args) != 5: - args.insert(2, None) - - meta = None if self.skip_meta else ParseMetaData(meta) - - cmd = Command( - parse_meta=meta, - qualities=args[0], - input_param=args[2], output_param=args[3], code=args[4], - **args[1], - ) - - return cmd - - def event_access(self, privilege): - return privilege[0] - - def event_with_access(self, args): - # Arguments - # - optional access for read - # - event identifier (name) - init_args = { - "name": args[-1] - } - if len(args) > 1: - init_args["readacl"] = args[0] - - return init_args - - def event(self, args): - return Event(qualities=args[0], priority=args[1], code=args[3], fields=args[4:], **args[2]) - - def view_privilege(self, args): - return AccessPrivilege.VIEW - - def operate_privilege(self, args): - return AccessPrivilege.OPERATE - - def manage_privilege(self, args): - return AccessPrivilege.MANAGE - - def administer_privilege(self, args): - return AccessPrivilege.ADMINISTER - - def read_access(self, args): - return AttributeOperation.READ - - def write_access(self, args): - return AttributeOperation.WRITE - - @v_args(inline=True) - def attribute_access_entry(self, operation, access): - return (operation, access) - - def attribute_access(self, value): - # return value as-is to not need to deal with trees in `attribute_with_access` - return value - - def attribute_with_access(self, args): - # Input arguments are: - # - acl (optional list of pairs operation + access) - # - field definition - acl = {} - if len(args) > 1: - for operation, access in args[0]: - if operation == AttributeOperation.READ: - acl['readacl'] = access - elif operation == AttributeOperation.WRITE: - acl['writeacl'] = access - else: - raise Exception( - "Unknown attribute operation: %r" % operation) - - return (args[-1], acl) - - def ram_attribute(self, _): - return AttributeStorage.RAM - - def persist_attribute(self, _): - return AttributeStorage.PERSIST - - def callback_attribute(self, _): - return AttributeStorage.CALLBACK - - @v_args(meta=True, inline=True) - def endpoint_attribute_instantiation(self, meta, storage, id, default=None): - meta = None if self.skip_meta else ParseMetaData(meta) - return AttributeInstantiation(parse_meta=meta, name=id, storage=storage, default=default) - - @v_args(meta=True, inline=True) - def endpoint_emitted_event(self, meta, id): - meta = None if self.skip_meta else ParseMetaData(meta) - return id - - def ESCAPED_STRING(self, s): - # handle escapes, skip the start and end quotes - return s.value[1:-1].encode('utf-8').decode('unicode-escape') - - @v_args(inline=True) - def attribute(self, qualities, definition_tuple): - (definition, acl) = definition_tuple - - # until we support write only (and need a bit of a reshuffle) - # if the 'attr_readonly == READABLE' is not in the list, we make things - # read/write - if AttributeQuality.READABLE not in qualities: - qualities |= AttributeQuality.READABLE - qualities |= AttributeQuality.WRITABLE - - return Attribute(definition=definition, qualities=qualities, **acl) - - @v_args(inline=True) - def struct(self, qualities, id, *fields): - return Struct(name=id, qualities=qualities, fields=list(fields)) - - @v_args(inline=True) - def request_struct(self, value): - value.tag = StructTag.REQUEST - return value - - @v_args(inline=True) - def response_struct(self, id, code, *fields): - return Struct(name=id, tag=StructTag.RESPONSE, code=code, fields=list(fields)) - - @v_args(inline=True) - def endpoint(self, number, *transforms): - endpoint = Endpoint(number=number) - - for t in transforms: - t.apply(endpoint) - - return endpoint - - @v_args(inline=True) - def endpoint_device_type(self, name, code, version): - return AddDeviceTypeToEndpointTransform(DeviceType(name=name, code=code, version=version)) - - @v_args(inline=True) - def endpoint_cluster_binding(self, id): - return AddBindingToEndpointTransform(id) - - @v_args(meta=True, inline=True) - def endpoint_server_cluster(self, meta, id, *content): - meta = None if self.skip_meta else ParseMetaData(meta) - - attributes = [] - events = set() - - for item in content: - if isinstance(item, AttributeInstantiation): - attributes.append(item) - else: - events.add(item) - return AddServerClusterToEndpointTransform( - ServerClusterInstantiation(parse_meta=meta, name=id, attributes=attributes, events_emitted=events)) - - @v_args(inline=True, meta=True) - def cluster(self, meta, side, name, code, *content): - meta = None if self.skip_meta else ParseMetaData(meta) - - # shift actual starting position where the doc comment would start - if meta and self._cluster_start_pos: - meta.start_pos = self._cluster_start_pos - - result = Cluster(parse_meta=meta, side=side, name=name, code=code) - - for item in content: - if type(item) == Enum: - result.enums.append(item) - elif type(item) == Bitmap: - result.bitmaps.append(item) - elif type(item) == Event: - result.events.append(item) - elif type(item) == Attribute: - result.attributes.append(item) - elif type(item) == Struct: - result.structs.append(item) - elif type(item) == Command: - result.commands.append(item) - else: - raise Exception("UNKNOWN cluster content item: %r" % item) - - return result - - def idl(self, items): - idl = Idl() - - for item in items: - if type(item) == Enum: - idl.enums.append(item) - elif type(item) == Struct: - idl.structs.append(item) - elif type(item) == Cluster: - idl.clusters.append(item) - elif type(item) == Endpoint: - idl.endpoints.append(item) - else: - raise Exception("UNKNOWN idl content item: %r" % item) - - return idl - - def prefix_doc_comment(self): - print("TODO: prefix") - - # Processing of (potential-doc)-comments: - def c_comment(self, token: Token): - """Processes comments starting with "/*" """ - if token.value.startswith("/**"): - self.doc_comments.append(PrefixCppDocComment(token)) - - -class ParserWithLines: - def __init__(self, skip_meta: bool): - self.transformer = MatterIdlTransformer(skip_meta) - - # NOTE: LALR parser is fast. While Earley could parse more ambigous grammars, - # earley is much slower: - # - 0.39s LALR parsing of all-clusters-app.matter - # - 2.26s Earley parsing of the same thing. - # For this reason, every attempt should be made to make the grammar context free - self.parser = Lark.open( - 'matter_grammar.lark', rel_to=__file__, start='idl', parser='lalr', propagate_positions=True, - # separate callbacks to ignore from regular parsing (no tokens) - # while still getting notified about them - lexer_callbacks={ - 'C_COMMENT': self.transformer.c_comment, - } - ) - - def parse(self, file: str, file_name: Optional[str] = None): - idl = self.transformer.transform(self.parser.parse(file)) - idl.parse_file_name = file_name - - for comment in self.transformer.doc_comments: - comment.appply_to_idl(idl, file) - - return idl - - -def CreateParser(skip_meta: bool = False): - """ - Generates a parser that will process a ".matter" file into a IDL - """ - return ParserWithLines(skip_meta) - - -if __name__ == '__main__': - # This Parser is generally not intended to be run as a stand-alone binary. - # The ability to run is for debug and to print out the parsed AST. - import pprint - - import click - - # Supported log levels, mapping string values required for argument - # parsing into logging constants - __LOG_LEVELS__ = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warn': logging.WARN, - 'fatal': logging.FATAL, - } - - @click.command() - @click.option( - '--log-level', - default='INFO', - type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), - help='Determines the verbosity of script output.') - @click.argument('filename') - def main(log_level, filename=None): - logging.basicConfig( - level=__LOG_LEVELS__[log_level], - format='%(asctime)s %(levelname)-7s %(message)s', - ) - - logging.info("Starting to parse ...") - data = CreateParser().parse(open(filename).read(), file_name=filename) - logging.info("Parse completed") - - logging.info("Data:") - pprint.pp(data) - - main(auto_envvar_prefix='CHIP') diff --git a/scripts/py_matter_idl/build/lib/matter_idl/matter_idl_types.py b/scripts/py_matter_idl/build/lib/matter_idl/matter_idl_types.py deleted file mode 100644 index 9e3b4beb53ed79..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/matter_idl_types.py +++ /dev/null @@ -1,270 +0,0 @@ -import enum -from dataclasses import dataclass, field -from typing import List, Optional, Set, Union - -from lark.tree import Meta - - -# Information about parsing location for specific items -# Helpful when referencing data items in logs when processing -@dataclass -class ParseMetaData: - line: Optional[int] - column: Optional[int] - start_pos: Optional[int] - - def __init__(self, meta: Optional[Meta] = None, line: Optional[int] = None, column: Optional[int] = None, start_pos: Optional[int] = None): - if meta: - self.line = getattr(meta, 'line', None) - self.column = getattr(meta, 'column', None) - self.start_pos = getattr(meta, 'start_pos', None) - else: - self.line = line - self.column = column - self.start_pos = start_pos - - -class StructQuality(enum.Flag): - NONE = 0 - FABRIC_SCOPED = enum.auto() - - -class FieldQuality(enum.Flag): - NONE = 0 - OPTIONAL = enum.auto() - NULLABLE = enum.auto() - FABRIC_SENSITIVE = enum.auto() - - -class CommandQuality(enum.Flag): - NONE = 0 - TIMED_INVOKE = enum.auto() - FABRIC_SCOPED = enum.auto() - - -class AttributeQuality(enum.Flag): - NONE = 0 - READABLE = enum.auto() - WRITABLE = enum.auto() - NOSUBSCRIBE = enum.auto() - TIMED_WRITE = enum.auto() - - -class AttributeStorage(enum.Enum): - RAM = enum.auto() - PERSIST = enum.auto() - CALLBACK = enum.auto() - - -class EventPriority(enum.Enum): - DEBUG = enum.auto() - INFO = enum.auto() - CRITICAL = enum.auto() - - -class EventQuality(enum.Flag): - NONE = 0 - FABRIC_SENSITIVE = enum.auto() - - -class ClusterSide(enum.Enum): - CLIENT = enum.auto() - SERVER = enum.auto() - - -class StructTag(enum.Enum): - REQUEST = enum.auto() - RESPONSE = enum.auto() - - -class EndpointContentType(enum.Enum): - SERVER_CLUSTER = enum.auto() - CLIENT_BINDING = enum.auto() - - -class AccessPrivilege(enum.Enum): - VIEW = enum.auto() - OPERATE = enum.auto() - MANAGE = enum.auto() - ADMINISTER = enum.auto() - - -class AttributeOperation(enum.Enum): - READ = enum.auto() - WRITE = enum.auto() - - -@dataclass -class DataType: - name: str - - # Applies for strings (char or binary) - max_length: Optional[int] = None - - -@dataclass -class Field: - data_type: DataType - code: int - name: str - is_list: bool = False - qualities: FieldQuality = FieldQuality.NONE - - @property - def is_optional(self): - return FieldQuality.OPTIONAL & self.qualities - - @property - def is_nullable(self): - return FieldQuality.NULLABLE & self.qualities - - -@dataclass -class Attribute: - definition: Field - qualities: AttributeQuality = AttributeQuality.NONE - readacl: AccessPrivilege = AccessPrivilege.VIEW - writeacl: AccessPrivilege = AccessPrivilege.OPERATE - default: Optional[Union[str, int]] = None - - @property - def is_readable(self): - return AttributeQuality.READABLE & self.qualities - - @property - def is_writable(self): - return AttributeQuality.WRITABLE & self.qualities - - @property - def is_subscribable(self): - return not (AttributeQuality.NOSUBSCRIBE & self.qualities) - - @property - def requires_timed_write(self): - return AttributeQuality.TIMED_WRITE & self.qualities - - -@dataclass -class Struct: - name: str - fields: List[Field] - tag: Optional[StructTag] = None - code: Optional[int] = None # for responses only - qualities: StructQuality = StructQuality.NONE - - -@dataclass -class Event: - priority: EventPriority - name: str - code: int - fields: List[Field] - readacl: AccessPrivilege = AccessPrivilege.VIEW - qualities: EventQuality = EventQuality.NONE - - @property - def is_fabric_sensitive(self): - return EventQuality.FABRIC_SENSITIVE & self.qualities - - -@dataclass -class ConstantEntry: - name: str - code: int - - -@dataclass -class Enum: - name: str - base_type: str - entries: List[ConstantEntry] - - -@dataclass -class Bitmap: - name: str - base_type: str - entries: List[ConstantEntry] - - -@dataclass -class Command: - name: str - code: int - input_param: Optional[str] - output_param: str - qualities: CommandQuality = CommandQuality.NONE - invokeacl: AccessPrivilege = AccessPrivilege.OPERATE - description: Optional[str] = None - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - @property - def is_timed_invoke(self): - return CommandQuality.TIMED_INVOKE & self.qualities - - -@dataclass -class Cluster: - side: ClusterSide - name: str - code: int - enums: List[Enum] = field(default_factory=list) - bitmaps: List[Bitmap] = field(default_factory=list) - events: List[Event] = field(default_factory=list) - attributes: List[Attribute] = field(default_factory=list) - structs: List[Struct] = field(default_factory=list) - commands: List[Command] = field(default_factory=list) - description: Optional[str] = None - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - -@dataclass -class AttributeInstantiation: - name: str - storage: AttributeStorage - default: Optional[Union[str, int, bool]] = None - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - -@dataclass -class ServerClusterInstantiation: - name: str - attributes: List[AttributeInstantiation] = field(default_factory=list) - events_emitted: Set[str] = field(default_factory=set) - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - -@dataclass -class DeviceType: - name: str - code: int - version: int - - -@dataclass -class Endpoint: - number: int - device_types: List[DeviceType] = field(default_factory=list) - server_clusters: List[ServerClusterInstantiation] = field( - default_factory=list) - client_bindings: List[str] = field(default_factory=list) - - -@dataclass -class Idl: - # Enums and structs represent globally used items - enums: List[Enum] = field(default_factory=list) - structs: List[Struct] = field(default_factory=list) - clusters: List[Cluster] = field(default_factory=list) - endpoints: List[Endpoint] = field(default_factory=list) - - # IDL file name is available only if parsing provides a file name - parse_file_name: Optional[str] = field(default=None) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/test_generators.py b/scripts/py_matter_idl/build/lib/matter_idl/test_generators.py deleted file mode 100644 index 146b6244de6cb2..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/test_generators.py +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import sys -import unittest -from dataclasses import dataclass, field -from typing import List - -import yaml - -try: - from matter_idl.matter_idl_parser import CreateParser -except ImportError: - - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.matter_idl_parser import CreateParser - -from matter_idl.generators import GeneratorStorage -from matter_idl.generators.cpp.application import CppApplicationGenerator -from matter_idl.generators.java import JavaClassGenerator, JavaJNIGenerator -from matter_idl.matter_idl_types import Idl - -TESTS_DIR = os.path.join(os.path.dirname(__file__), "tests") -REGENERATE_GOLDEN_IMAGES = False - - -@dataclass -class ExpectedOutput: - file_name: str - golden_path: str - - -@dataclass -class GeneratorTestCase: - input_idl: str - outputs: List[ExpectedOutput] = field(default_factory=list) - - def add_outputs(self, yaml_outputs_dict): - for file_name, golden_path in yaml_outputs_dict.items(): - self.outputs.append(ExpectedOutput( - file_name=file_name, golden_path=golden_path)) - - -class TestCaseStorage(GeneratorStorage): - def __init__(self, test_case: GeneratorTestCase, checker: unittest.TestCase): - super().__init__() - self.test_case = test_case - self.checker = checker - self.checked_files = set() - - def get_existing_data_path(self, relative_path: str): - for expected in self.test_case.outputs: - if expected.file_name == relative_path: - return os.path.join(TESTS_DIR, expected.golden_path) - - self.checker.fail("Expected output %s not found" % relative_path) - return None - - def get_existing_data(self, relative_path: str): - self.checked_files.add(relative_path) - - path = self.get_existing_data_path(relative_path) - if path: - with open(path, 'rt') as golden: - return golden.read() - - # This will attempt a new write, causing a unit test failure - self.checker.fail("Expected output %s not found" % relative_path) - return None - - def write_new_data(self, relative_path: str, content: str): - if REGENERATE_GOLDEN_IMAGES: - print("RE-GENERATING %r" % relative_path) - # Expect writing only on regeneration - with open(self.get_existing_data_path(relative_path), 'wt') as golden: - golden.write(content) - return - - # This is a unit test failure: we do NOT expect - # to write any new data - - # This will display actual diffs in the output files - self.checker.assertEqual( - self.get_existing_data(relative_path), content, "Content of %s" % relative_path) - - # Even if no diff, to be build system friendly, we do NOT expect any - # actual data writes. - raise AssertionError("Unexpected write to %s" % relative_path) - - -@dataclass -class GeneratorTest: - generator_name: str - test_cases: List[GeneratorTestCase] = field(default_factory=list) - - def add_test_cases(self, yaml_test_case_dict): - for idl_path, outputs in yaml_test_case_dict.items(): - test_case = GeneratorTestCase(input_idl=idl_path) - test_case.add_outputs(outputs) - self.test_cases.append(test_case) - - def _create_generator(self, storage: GeneratorStorage, idl: Idl): - if self.generator_name.lower() == 'java-jni': - return JavaJNIGenerator(storage, idl) - if self.generator_name.lower() == 'java-class': - return JavaClassGenerator(storage, idl) - if self.generator_name.lower() == 'cpp-app': - return CppApplicationGenerator(storage, idl) - if self.generator_name.lower() == 'custom-example-proto': - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '../examples'))) - from matter_idl_plugin import CustomGenerator - return CustomGenerator(storage, idl, package='com.matter.example.proto') - else: - raise Exception("Unknown generator for testing: %s", - self.generator_name.lower()) - - def run_test_cases(self, checker: unittest.TestCase): - for test in self.test_cases: - with checker.subTest(idl=test.input_idl): - storage = TestCaseStorage(test, checker) - with open(os.path.join(TESTS_DIR, test.input_idl), 'rt') as stream: - idl = CreateParser().parse(stream.read()) - - generator = self._create_generator(storage, idl) - generator.render(dry_run=False) - - checker.assertEqual(storage.checked_files, set( - map(lambda x: x.file_name, test.outputs))) - - -def build_tests(yaml_data) -> List[GeneratorTest]: - """ - Transforms the YAML dictonary (Dict[str, Dict[str, Dict[str,str]]]) into - a generator test structure. - """ - result = [] - - for key, test_cases in yaml_data.items(): - generator = GeneratorTest(generator_name=key) - generator.add_test_cases(test_cases) - result.append(generator) - - return result - - -class TestGenerators(unittest.TestCase): - def test_generators(self): - with open(os.path.join(TESTS_DIR, "available_tests.yaml"), 'rt') as stream: - yaml_data = yaml.safe_load(stream) - - for test in build_tests(yaml_data): - with self.subTest(generator=test.generator_name): - test.run_test_cases(self) - - -if __name__ == '__main__': - if 'IDL_GOLDEN_REGENERATE' in os.environ: - # run with `IDL_GOLDEN_REGENERATE=1` to cause a regeneration of test - # data. Then one can use `git diff` to see if the deltas make sense - REGENERATE_GOLDEN_IMAGES = True - unittest.main() diff --git a/scripts/py_matter_idl/build/lib/matter_idl/test_matter_idl_parser.py b/scripts/py_matter_idl/build/lib/matter_idl/test_matter_idl_parser.py deleted file mode 100644 index 2a3cfea87e76b1..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/test_matter_idl_parser.py +++ /dev/null @@ -1,601 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -try: - from matter_idl.matter_idl_parser import CreateParser -except ModuleNotFoundError: - import os - import sys - sys.path.append(os.path.dirname( - os.path.dirname(os.path.abspath(__file__)))) - - from matter_idl.matter_idl_parser import CreateParser - -import unittest - -from matter_idl.matter_idl_types import (AccessPrivilege, Attribute, AttributeInstantiation, AttributeQuality, AttributeStorage, - Bitmap, Cluster, ClusterSide, Command, CommandQuality, ConstantEntry, DataType, DeviceType, - Endpoint, Enum, Event, EventPriority, EventQuality, Field, FieldQuality, Idl, - ParseMetaData, ServerClusterInstantiation, Struct, StructQuality, StructTag) - - -def parseText(txt, skip_meta=True): - return CreateParser(skip_meta=skip_meta).parse(txt) - - -class TestParser(unittest.TestCase): - - def test_skips_comments(self): - actual = parseText(""" - // this is a single line comment - // repeated - - /* This is a C++ comment - and also whitespace should be ignored - */ - """) - expected = Idl() - - self.assertEqual(actual, expected) - - def test_global_enum(self): - actual = parseText(""" - enum GlobalEnum : ENUM8 { - kValue1 = 1; - kOther = 0x12; /* hex numbers tested sporadically */ - } - """) - - expected = Idl(enums=[ - Enum(name='GlobalEnum', base_type='ENUM8', - entries=[ - ConstantEntry(name="kValue1", code=1), - ConstantEntry(name="kOther", code=0x12), - ])] - ) - self.assertEqual(actual, expected) - - def test_global_struct(self): - actual = parseText(""" - struct Something { - CHAR_STRING astring = 1; - optional CLUSTER_ID idlist[] = 2; - nullable int valueThatIsNullable = 0x123; - char_string<123> sized_string = 222; - } - """) - - expected = Idl(structs=[ - Struct(name='Something', - fields=[ - Field( - data_type=DataType(name="CHAR_STRING"), code=1, name="astring", ), - Field(data_type=DataType(name="CLUSTER_ID"), code=2, name="idlist", - is_list=True, qualities=FieldQuality.OPTIONAL), - Field(data_type=DataType(name="int"), code=0x123, - name="valueThatIsNullable", qualities=FieldQuality.NULLABLE), - Field(data_type=DataType(name="char_string", max_length=123), - code=222, name="sized_string"), - ])] - ) - self.assertEqual(actual, expected) - - def test_fabric_scoped_struct(self): - actual = parseText(""" - fabric_scoped struct FabricStruct { - CHAR_STRING astring = 1; - optional CLUSTER_ID idlist[] = 2; - nullable fabric_sensitive int nullablesensitive = 0x123; - } - """) - - expected = Idl(structs=[ - Struct(name='FabricStruct', - qualities=StructQuality.FABRIC_SCOPED, - fields=[ - Field( - data_type=DataType(name="CHAR_STRING"), code=1, name="astring", ), - Field(data_type=DataType(name="CLUSTER_ID"), code=2, name="idlist", - is_list=True, qualities=FieldQuality.OPTIONAL), - Field(data_type=DataType(name="int"), code=0x123, name="nullablesensitive", - qualities=FieldQuality.NULLABLE | FieldQuality.FABRIC_SENSITIVE), - ])] - ) - self.assertEqual(actual, expected) - - def test_cluster_attribute(self): - actual = parseText(""" - server cluster MyCluster = 0x321 { - readonly attribute int8u roAttr = 1; - attribute int32u rwAttr[] = 123; - readonly nosubscribe attribute int8s nosub[] = 0xaa; - readonly attribute nullable int8s isNullable = 0xab; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=0x321, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE, definition=Field( - data_type=DataType(name="int8u"), code=1, name="roAttr")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int32u"), code=123, name="rwAttr", is_list=True)), - Attribute(qualities=AttributeQuality.NOSUBSCRIBE | AttributeQuality.READABLE, definition=Field( - data_type=DataType(name="int8s"), code=0xAA, name="nosub", is_list=True)), - Attribute(qualities=AttributeQuality.READABLE, definition=Field( - data_type=DataType(name="int8s"), code=0xAB, name="isNullable", qualities=FieldQuality.NULLABLE)), - ] - )]) - self.assertEqual(actual, expected) - - def test_doc_comments(self): - actual = parseText(""" - /** Documentation for MyCluster */ - server cluster MyCluster = 0x321 { - } - - /** Documentation for MyCluster #2 */ - client cluster MyCluster = 0x321 { - /* NOT a doc comment */ - command WithoutArg(): DefaultSuccess = 123; - - /** Some command doc comment */ - command InOutStuff(InParam): OutParam = 222; - } - """, skip_meta=False) - - # meta_data may not match but is required for doc comments. Clean it up - - # Metadata parsing varies line/column, so only check doc comments - self.assertEqual( - actual.clusters[0].description, "Documentation for MyCluster") - self.assertEqual( - actual.clusters[1].description, "Documentation for MyCluster #2") - self.assertIsNone(actual.clusters[1].commands[0].description) - self.assertEqual( - actual.clusters[1].commands[1].description, "Some command doc comment") - - def test_sized_attribute(self): - actual = parseText(""" - server cluster MyCluster = 1 { - attribute char_string<11> attr1 = 1; - attribute octet_string<33> attr2[] = 2; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=1, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="char_string", max_length=11), code=1, name="attr1")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="octet_string", max_length=33), code=2, name="attr2", is_list=True)), - ] - )]) - self.assertEqual(actual, expected) - - def test_timed_attributes(self): - actual = parseText(""" - server cluster MyCluster = 1 { - attribute int32u attr1 = 1; - timedwrite attribute int32u attr2 = 2; - attribute int32u attr3 = 3; - timedwrite attribute octet_string<44> attr4[] = 4; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=1, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int32u"), code=1, name="attr1")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE | AttributeQuality.TIMED_WRITE, definition=Field( - data_type=DataType(name="int32u"), code=2, name="attr2")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int32u"), code=3, name="attr3")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE | AttributeQuality.TIMED_WRITE, definition=Field( - data_type=DataType(name="octet_string", max_length=44), code=4, name="attr4", is_list=True)), - ] - )]) - self.assertEqual(actual, expected) - - def test_attribute_access(self): - actual = parseText(""" - server cluster MyCluster = 1 { - attribute int8s attr1 = 1; - attribute access() int8s attr2 = 2; - attribute access(read: manage) int8s attr3 = 3; - attribute access(write: administer) int8s attr4 = 4; - attribute access(read: operate, write: manage) int8s attr5 = 5; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=1, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=1, name="attr1"), - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=2, name="attr2"), - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=3, name="attr3"), - readacl=AccessPrivilege.MANAGE - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=4, name="attr4"), - writeacl=AccessPrivilege.ADMINISTER - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=5, name="attr5"), - readacl=AccessPrivilege.OPERATE, - writeacl=AccessPrivilege.MANAGE - ), - ] - )]) - self.assertEqual(actual, expected) - - def test_cluster_commands(self): - actual = parseText(""" - server cluster WithCommands = 1 { - struct FreeStruct {} - request struct InParam {} - response struct OutParam = 223 {} - - command WithoutArg(): DefaultSuccess = 123; - command InOutStuff(InParam): OutParam = 222; - timed command TimedCommand(InParam): DefaultSuccess = 0xab; - fabric command FabricScopedCommand(InParam): DefaultSuccess = 0xac; - fabric Timed command FabricScopedTimedCommand(InParam): DefaultSuccess = 0xad; - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="WithCommands", - code=1, - structs=[ - Struct(name="FreeStruct", fields=[]), - Struct(name="InParam", fields=[], - tag=StructTag.REQUEST), - Struct(name="OutParam", fields=[], - tag=StructTag.RESPONSE, code=223), - ], - commands=[ - Command(name="WithoutArg", code=123, - input_param=None, output_param="DefaultSuccess"), - Command(name="InOutStuff", code=222, - input_param="InParam", output_param="OutParam"), - Command(name="TimedCommand", code=0xab, - input_param="InParam", output_param="DefaultSuccess", - qualities=CommandQuality.TIMED_INVOKE), - Command(name="FabricScopedCommand", code=0xac, - input_param="InParam", output_param="DefaultSuccess", - qualities=CommandQuality.FABRIC_SCOPED), - Command(name="FabricScopedTimedCommand", code=0xad, - input_param="InParam", output_param="DefaultSuccess", - qualities=CommandQuality.TIMED_INVOKE | CommandQuality.FABRIC_SCOPED), - ], - )]) - self.assertEqual(actual, expected) - - def test_cluster_command_access(self): - actual = parseText(""" - server cluster WithCommands = 1 { - request struct InParam {} - response struct OutParam = 4 {} - - command WithoutArg(): DefaultSuccess = 1; - timed command access(invoke: manage) TimedCommand(InParam): OutParam = 2; - command access(invoke: administer) OutOnly(): OutParam = 3; - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="WithCommands", - code=1, - structs=[ - Struct(name="InParam", fields=[], - tag=StructTag.REQUEST), - Struct(name="OutParam", fields=[], - tag=StructTag.RESPONSE, code=4), - ], - commands=[ - Command(name="WithoutArg", code=1, - invokeacl=AccessPrivilege.OPERATE, - input_param=None, output_param="DefaultSuccess"), - Command(name="TimedCommand", code=2, - input_param="InParam", output_param="OutParam", - invokeacl=AccessPrivilege.MANAGE, - qualities=CommandQuality.TIMED_INVOKE), - Command(name="OutOnly", code=3, - input_param=None, output_param="OutParam", - invokeacl=AccessPrivilege.ADMINISTER, - ), - ], - )]) - self.assertEqual(actual, expected) - - def test_cluster_enum(self): - actual = parseText(""" - client cluster WithEnums = 0xab { - enum TestEnum : ENUM16 { - A = 0x123; - B = 0x234; - } - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="WithEnums", - code=0xab, - enums=[ - Enum(name="TestEnum", base_type="ENUM16", - entries=[ - ConstantEntry(name="A", code=0x123), - ConstantEntry(name="B", code=0x234), - ])], - )]) - self.assertEqual(actual, expected) - - def test_cluster_bitmap(self): - actual = parseText(""" - client cluster Test = 0xab { - bitmap TestBitmap : BITMAP32 { - kFirst = 0x1; - kSecond = 0x2; - } - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="Test", - code=0xab, - bitmaps=[ - Bitmap(name="TestBitmap", base_type="BITMAP32", - entries=[ - ConstantEntry(name="kFirst", code=0x1), - ConstantEntry(name="kSecond", code=0x2), - ])], - )]) - self.assertEqual(actual, expected) - - def test_cluster_events(self): - actual = parseText(""" - client cluster EventTester = 0x123 { - critical event StartUp = 0 { - INT32U softwareVersion = 0; - } - info event Hello = 1 {} - debug event GoodBye = 2 {} - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="EventTester", - code=0x123, - events=[ - Event(priority=EventPriority.CRITICAL, name="StartUp", code=0, fields=[ - Field(data_type=DataType(name="INT32U"), - code=0, name="softwareVersion"), - ]), - Event(priority=EventPriority.INFO, - name="Hello", code=1, fields=[]), - Event(priority=EventPriority.DEBUG, - name="GoodBye", code=2, fields=[]), - ])]) - self.assertEqual(actual, expected) - - def test_cluster_event_acl(self): - actual = parseText(""" - client cluster EventTester = 0x123 { - info event Hello = 1 {} - debug event access(read: manage) GoodBye = 2 {} - debug event access(read: administer) AdminEvent = 3 {} - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="EventTester", - code=0x123, - events=[ - Event(priority=EventPriority.INFO, readacl=AccessPrivilege.VIEW, - name="Hello", code=1, fields=[]), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.MANAGE, - name="GoodBye", code=2, fields=[]), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.ADMINISTER, - name="AdminEvent", code=3, fields=[]), - ])]) - self.assertEqual(actual, expected) - - def test_fabric_sensitive_event(self): - actual = parseText(""" - client cluster EventTester = 0x123 { - fabric_sensitive info event Hello = 1 {} - fabric_sensitive debug event access(read: manage) GoodBye = 2 {} - fabric_sensitive debug event access(read: administer) AdminEvent = 3 {} - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="EventTester", - code=0x123, - events=[ - Event(priority=EventPriority.INFO, readacl=AccessPrivilege.VIEW, - name="Hello", code=1, fields=[], qualities=EventQuality.FABRIC_SENSITIVE), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.MANAGE, - name="GoodBye", code=2, fields=[], qualities=EventQuality.FABRIC_SENSITIVE), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.ADMINISTER, - name="AdminEvent", code=3, fields=[], qualities=EventQuality.FABRIC_SENSITIVE), - ])]) - self.assertEqual(actual, expected) - - def test_parsing_metadata_for_cluster(self): - actual = CreateParser(skip_meta=False).parse(""" -server cluster A = 1 { /* Test comment */ } - -// some empty lines and then indented - client cluster B = 2 { } - """) - - expected = Idl(clusters=[ - Cluster(parse_meta=ParseMetaData(line=2, column=1, start_pos=1), - side=ClusterSide.SERVER, name="A", code=1), - Cluster(parse_meta=ParseMetaData(line=5, column=4, start_pos=87), - side=ClusterSide.CLIENT, name="B", code=2), - ]) - self.assertEqual(actual, expected) - - def test_multiple_clusters(self): - actual = parseText(""" - server cluster A = 1 { /* Test comment */ } - client cluster B = 2 { } - client cluster C = 3 { } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, name="A", code=1), - Cluster(side=ClusterSide.CLIENT, name="B", code=2), - Cluster(side=ClusterSide.CLIENT, name="C", code=3), - ]) - self.assertEqual(actual, expected) - - def test_endpoints(self): - actual = parseText(""" - endpoint 12 { - device type foo = 123, version 1; - device type bar = 0xFF, version 2; - - server cluster Foo { } - server cluster Bar { } - binding cluster Bar; - binding cluster Test; - } - """) - - expected = Idl(endpoints=[Endpoint(number=12, - device_types=[ - DeviceType( - name="foo", code=123, version=1), - DeviceType( - name="bar", code=0xFF, version=2), - ], - server_clusters=[ - ServerClusterInstantiation( - name="Foo"), - ServerClusterInstantiation( - name="Bar"), - ], - client_bindings=["Bar", "Test"],) - ]) - self.assertEqual(actual, expected) - - def test_cluster_instantiation(self): - actual = parseText(""" - endpoint 3 { - server cluster Example { - ram attribute inRamZero; - ram attribute inRamWithDefault default=123; - persist attribute inNVMNoDef; - persist attribute inNVMStr default="abc"; - persist attribute inNVMWithDefault default = -33; - callback attribute hasCallbackBool default = true; - } - } - """) - - expected = Idl(endpoints=[Endpoint(number=3, - server_clusters=[ - ServerClusterInstantiation(name="Example", attributes=[ - AttributeInstantiation( - name='inRamZero', storage=AttributeStorage.RAM), - AttributeInstantiation(name='inRamWithDefault', - storage=AttributeStorage.RAM, default=123), - AttributeInstantiation( - name='inNVMNoDef', storage=AttributeStorage.PERSIST), - AttributeInstantiation( - name='inNVMStr', storage=AttributeStorage.PERSIST, default="abc"), - AttributeInstantiation(name='inNVMWithDefault', - storage=AttributeStorage.PERSIST, default=-33), - AttributeInstantiation(name='hasCallbackBool', - storage=AttributeStorage.CALLBACK, default=True), - ]), - ], - client_bindings=[],) - ]) - self.assertEqual(actual, expected) - - def test_multi_endpoints(self): - actual = parseText(""" - endpoint 1 {} - endpoint 2 {} - endpoint 0xa {} - endpoint 100 {} - """) - - expected = Idl(endpoints=[ - Endpoint(number=1), - Endpoint(number=2), - Endpoint(number=10), - Endpoint(number=100), - ]) - self.assertEqual(actual, expected) - - def test_emits_events(self): - actual = parseText(""" - endpoint 1 { - server cluster Example {} - } - endpoint 2 { - server cluster Example { - emits event FooBar; - emits event SomeNewEvent; - } - server cluster AnotherExample { - emits event StartUp; - emits event ShutDown; - } - } - """) - - expected = Idl(endpoints=[ - Endpoint(number=1, server_clusters=[ - ServerClusterInstantiation(name="Example")]), - Endpoint(number=2, server_clusters=[ - ServerClusterInstantiation(name="Example", events_emitted={ - "FooBar", "SomeNewEvent"}), - ServerClusterInstantiation(name="AnotherExample", events_emitted={ - "StartUp", "ShutDown"}), - ]) - ]) - - self.assertEqual(actual, expected) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/py_matter_idl/build/lib/matter_idl/test_xml_parser.py b/scripts/py_matter_idl/build/lib/matter_idl/test_xml_parser.py deleted file mode 100644 index 7828c4219694fd..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/test_xml_parser.py +++ /dev/null @@ -1,382 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import io -import unittest -from typing import List, Union - -try: - from matter_idl.zapxml import ParseSource, ParseXmls -except ImportError: - import os - import sys - - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.zapxml import ParseSource, ParseXmls - -from matter_idl.matter_idl_types import (AccessPrivilege, Attribute, AttributeQuality, Bitmap, Cluster, ClusterSide, Command, - ConstantEntry, DataType, Enum, Event, EventPriority, EventQuality, Field, FieldQuality, - Idl, Struct, StructQuality, StructTag) - - -def XmlToIdl(what: Union[str, List[str]]) -> Idl: - if not isinstance(what, list): - what = [what] - - sources = [] - for idx, txt in enumerate(what): - sources.append(ParseSource(source=io.StringIO( - txt), name=("Input %d" % (idx + 1)))) - - return ParseXmls(sources, include_meta_data=False) - - -class TestXmlParser(unittest.TestCase): - - def testEmptyInput(self): - idl = XmlToIdl('') - self.assertEqual(idl, Idl()) - - def testCluster(self): - idl = XmlToIdl(''' - - - - Test - 0x1234 - Test - - SomeIntAttribute - - - AttributeWithAccess - - - - - - This is just a test: client to server - - - - - - - Reply from server - - - - - - ''') - self.assertEqual(idl, - Idl(clusters=[ - Cluster( - side=ClusterSide.CLIENT, - name='Test', - code=0x1234, - description="Test", - attributes=[ - Attribute(definition=Field( - data_type=DataType(name='INT32U'), - code=11, - name='SomeIntAttribute', - qualities=FieldQuality.NULLABLE), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, writeacl=AccessPrivilege.OPERATE), - - Attribute(definition=Field( - data_type=DataType(name='INT8U'), - code=22, name='AttributeWithAccess', - qualities=FieldQuality.OPTIONAL), - qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, - readacl=AccessPrivilege.OPERATE, - writeacl=AccessPrivilege.MANAGE) - ], - structs=[ - Struct(name='GetSomeDataRequest', - fields=[ - Field(data_type=DataType( - name='INT8U'), code=0, name='firstInput'), - Field(data_type=DataType( - name='INT16U'), code=1, name='secondInput') - ], - tag=StructTag.REQUEST), - Struct(name='GetSomeDataResponse', - fields=[ - Field(data_type=DataType(name='INT8U'), code=0, - name='dataPoint1'), - Field(data_type=DataType(name='INT8U'), code=1, name='dataPoint2', - qualities=FieldQuality.OPTIONAL) - ], - tag=StructTag.RESPONSE, code=0x44) - ], - commands=[ - Command(name='GetSomeData', code=33, - input_param='GetSomeDataRequest', output_param='GetSomeDataResponse', - description='This is just a test: client to server', - invokeacl=AccessPrivilege.ADMINISTER) - ]) - ])) - - def testBitmap(self): - idl = XmlToIdl(''' - - Test10x0001 - Test20x0002 - - - - - - - - - - ''') - bitmap = Bitmap( - name='MyBitmap', - base_type='BITMAP32', - entries=[ - ConstantEntry(name='BitmapMask1', code=1), - ConstantEntry(name='BitmapMask2', code=2), - ConstantEntry(name='BitmapMask3', code=4) - ]) - - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name='Test1', code=1, bitmaps=[bitmap]), - Cluster(side=ClusterSide.CLIENT, - name='Test2', code=2, bitmaps=[bitmap]), - ])) - - def testFabricScopedAndSensitive(self): - idl = XmlToIdl(''' - - - Test - 0x0001 - - - This is a test event - - - - - - - - - - - - - - - - ''') - self.assertEqual(idl, - Idl(clusters=[Cluster(side=ClusterSide.CLIENT, - name='Test', - code=1, - events=[Event(priority=EventPriority.INFO, - name='FabricEvent', - code=0x1234, - fields=[Field(data_type=DataType(name='node_id'), - code=1, - name='AdminNodeID', - qualities=FieldQuality.NULLABLE)], - readacl=AccessPrivilege.ADMINISTER, - qualities=EventQuality.FABRIC_SENSITIVE)], - structs=[Struct(name='FabricStruct', - fields=[Field(data_type=DataType(name='int32u'), - code=1, - name='Field1', - qualities=FieldQuality.FABRIC_SENSITIVE), - Field(data_type=DataType(name='int32u'), - code=3, - name='Field3', - qualities=FieldQuality.FABRIC_SENSITIVE), - Field(data_type=DataType(name='int32u', - max_length=None), - code=10, - name='Field10')], - qualities=StructQuality.FABRIC_SCOPED)], - )])) - - def testEnum(self): - idl = XmlToIdl(''' - - Test110 - Test220 - - - - - - - - - - - - - - - - - - - ''') - e1 = Enum( - name='GlobalEnum', - base_type="ENUM8", - entries=[ - ConstantEntry(name="First", code=0), - ConstantEntry(name="Second", code=1), - ] - ) - e2 = Enum( - name='OneCluster', - base_type="ENUM8", - entries=[ - ConstantEntry(name="Three", code=3), - ] - ) - e3 = Enum( - name='TwoClusters', - base_type="ENUM8", - entries=[ - ConstantEntry(name="Big", code=100), - ConstantEntry(name="Bigger", code=2000), - ] - ) - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name='Test1', code=10, enums=[e2, e3]), - Cluster(side=ClusterSide.CLIENT, - name='Test2', code=20, enums=[e3])], - enums=[e1], - )) - - def testStruct(self): - idl = XmlToIdl(''' - - Test10x000A - - Test2 - 20 - - - FabricAttribute - - - - - - - - - - - - ''') - struct = Struct( - name='SomeStruct', - qualities=StructQuality.FABRIC_SCOPED, - fields=[ - Field(data_type=DataType(name='int16u'), - code=0, name='FirstMember'), - Field(data_type=DataType(name='int32u'), - code=1, name='SecondMember') - ] - ) - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name='Test1', code=10, structs=[struct]), - Cluster(side=ClusterSide.CLIENT, name='Test2', code=20, - structs=[struct], - attributes=[ - Attribute( - definition=Field( - data_type=DataType( - name='SomeStruct'), - code=123, - name='FabricAttribute', - qualities=FieldQuality.NULLABLE - ), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE)]), ])) - - def testSkipsNotProcessedFields(self): - # Zap has extra fields that are generally not processed - # This includes such fields and ansures we do not consider them - idl = XmlToIdl(''' - - - - - Window Covering - Closures - 0x0102 - WINDOW_COVERING_CLUSTER - Provides an interface for controlling and adjusting automatic window coverings. - - - - - - - - - true - true - - - - Type - - - ''') - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, name='WindowCovering', code=0x102, - description='Provides an interface for controlling and adjusting automatic window coverings. ', - structs=[], - attributes=[ - Attribute( - definition=Field( - data_type=DataType( - name='Type'), - code=0, - name='Type', - ), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE)]), ])) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/py_matter_idl/build/lib/matter_idl/xml_parser.py b/scripts/py_matter_idl/build/lib/matter_idl/xml_parser.py deleted file mode 100644 index 5a07490e9c3b68..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/xml_parser.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import os - -try: - from matter_idl.zapxml import ParseSource, ParseXmls -except ImportError: - import sys - - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.zapxml import ParseSource, ParseXmls - - -if __name__ == '__main__': - # This Parser is generally not intended to be run as a stand-alone binary. - # The ability to run is for debug and to print out the parsed AST. - import pprint - - import click - - # Supported log levels, mapping string values required for argument - # parsing into logging constants - __LOG_LEVELS__ = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warn': logging.WARN, - 'fatal': logging.FATAL, - } - - @ click.command() - @ click.option( - '--log-level', - default='INFO', - show_default=True, - type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), - help='Determines the verbosity of script output.') - @ click.option( - '--no-print', - show_default=True, - default=False, - is_flag=True, - help='Do not pring output data (parsed data)') - @ click.argument('filenames', nargs=-1) - def main(log_level, no_print, filenames): - logging.basicConfig( - level=__LOG_LEVELS__[log_level], - format='%(asctime)s %(levelname)-7s %(message)s', - ) - - logging.info("Starting to parse ...") - - sources = [ParseSource(source=name) for name in filenames] - data = ParseXmls(sources) - logging.info("Parse completed") - - if not no_print: - print("Data:") - pprint.pp(data) - - main(auto_envvar_prefix='CHIP') diff --git a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/zapxml/__init__.py deleted file mode 100644 index 606abc6c9b7cb1..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/__init__.py +++ /dev/null @@ -1,122 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import typing -import xml.sax.handler -from dataclasses import dataclass -from typing import List, Optional, Union - -from matter_idl.matter_idl_types import Idl -from matter_idl.zapxml.handlers import Context, ZapXmlHandler - - -class ParseHandler(xml.sax.handler.ContentHandler): - """A parser for ZAP-style XML data definitions. - - Defers its processing to ZapXmlHandler and keeps track of: - - an internal context for all handlers - - the parsed Idl structure that is incrementally built - - sets up parsing location within the context - - keeps track of ParsePath - - Overall converts a python SAX handler into matter_idl.zapxml.handlers - """ - - def __init__(self, include_meta_data=True): - super().__init__() - self._idl = Idl() - self._processing_stack = [] - # Context persists across all - self._context = Context() - self._include_meta_data = include_meta_data - self._locator = None - - def PrepareParsing(self, filename): - # This is a bit ugly: filename keeps changing during parse - # IDL meta is not prepared for this (as source is XML and .matter is - # single file) - if self._include_meta_data: - self._idl.parse_file_name = filename - - self._context.file_name = filename - - def Finish(self) -> Idl: - self._context.PostProcess(self._idl) - return self._idl - - def startDocument(self): - if self._include_meta_data and self._locator: - self._context.locator = self._locator - self._processing_stack = [ZapXmlHandler(self._context, self._idl)] - - def endDocument(self): - if len(self._processing_stack) != 1: - raise Exception("Unexpected nesting!") - - def startElement(self, name: str, attrs): - logging.debug("ELEMENT START: %r / %r" % (name, attrs)) - self._context.path.push(name) - self._processing_stack.append( - self._processing_stack[-1].GetNextProcessor(name, attrs)) - - def endElement(self, name: str): - logging.debug("ELEMENT END: %r" % name) - - last = self._processing_stack.pop() - last.EndProcessing() - - # important to pop AFTER processing end to allow processing - # end to access the current context - self._context.path.pop() - - def characters(self, content): - self._processing_stack[-1].HandleContent(content) - - -@dataclass -class ParseSource: - """Represents an input sopurce for ParseXmls. - - Allows for named data sources to be parsed. - """ - source: Union[str, typing.IO] # filename or stream - # actual filename to use, None if the source is a filename already - name: Optional[str] = None - - @ property - def source_file_name(self): - if self.name: - return self.name - return self.source # assume string - - -def ParseXmls(sources: List[ParseSource], include_meta_data=True) -> Idl: - """Parse one or more XML inputs and return the resulting Idl data. - - Params: - sources - what to parse - include_meta_data - if parsing location data should be included in the Idl - """ - handler = ParseHandler(include_meta_data=include_meta_data) - - for source in sources: - logging.info('Parsing %s...' % source.source_file_name) - handler.PrepareParsing(source.source_file_name) - - parser = xml.sax.make_parser() - parser.setContentHandler(handler) - parser.parse(source.source) - - return handler.Finish() diff --git a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/__init__.py b/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/__init__.py deleted file mode 100644 index 3745954a195cfd..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .base import BaseHandler -from .context import Context -from .handlers import ConfiguratorHandler - -from matter_idl.matter_idl_types import Idl - - -class ZapXmlHandler(BaseHandler): - """Handles the top level (/) of a zap xml file. - - Generally these files only contain a 'configurator' element in them - """ - - def __init__(self, context: Context, idl: Idl): - super().__init__(context) - self._idl = idl - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'configurator': - return ConfiguratorHandler(self.context, self._idl) - else: - return BaseHandler(self.context) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/base.py b/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/base.py deleted file mode 100644 index ac17363d3fa6ae..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/base.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum - -from .context import Context - - -class HandledDepth: - """Defines how deep a XML element has been handled.""" - NOT_HANDLED = enum.auto() # Unknown/parsed element - ENTIRE_TREE = enum.auto() # Entire tree can be ignored - SINGLE_TAG = enum.auto() # Single tag processed, but not sub-items - - -class BaseHandler: - """A generic element handler. - - XML processing is done in the form of depth-first processing: - - Tree is descended into using `GetNextProcessor` - - Processors are expected to extend `BaseHandler` and allow for: - - GetNextProcessor to recurse - - HandleContent in case the text content is relevant - - EndProcessing once the entire tree has been walked (when xml element ends) - - BaseHandler keeps track if it has been handled or ot by its `_handled` setting and - init parameter. Non-handled elements will be tagged within the context, resulting - in logs. This is to detect if unknown/new tags appear in XML files. - """ - - def __init__(self, context: Context, handled=HandledDepth.NOT_HANDLED): - self.context = context - self._handled = handled - - def GetNextProcessor(self, name, attrs): - """Get the next processor to use for the given name""" - - if self._handled == HandledDepth.SINGLE_TAG: - handled = HandledDepth.NOT_HANDLED - else: - handled = self._handled - - return BaseHandler(context=self.context, handled=handled) - - def HandleContent(self, content): - """Processes some content""" - pass - - def EndProcessing(self): - """Finalizes the processing of the current element""" - if self._handled == HandledDepth.NOT_HANDLED: - self.context.MarkTagNotHandled() diff --git a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/context.py b/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/context.py deleted file mode 100644 index 230016e1eb5b98..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/context.py +++ /dev/null @@ -1,147 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import xml.sax.xmlreader -from typing import List, Optional - -from matter_idl.matter_idl_types import Attribute, Idl, ParseMetaData - - -class IdlPostProcessor: - """Defines a callback that will apply after an entire parsing - is complete. - """ - - def FinalizeProcessing(self, idl: Idl): - """Update idl with any post-processing directives.""" - pass - - -class ProcessingPath: - """Maintains the current path of tags within xml processing. - - As processing descents into an xml like `....` - paths will have contents like ['configurator', 'cluster', ...]. - - The main purpose for this is to log and keep track of what was visited - and in general to report things like 'this path found but was not handled'. - """ - - def __init__(self, paths: Optional[List[str]] = None): - if paths is None: - paths = [] - self.paths = paths - - def push(self, name: str): - self.paths.append(name) - - def pop(self): - self.paths.pop() - - def __str__(self): - return '::'.join(self.paths) - - def __repr__(self): - return 'ProcessingPath(%r)' % self.paths - - -class Context: - """ - Contains a processing state during XML reading. - - The purpose of this is to allow elements to interact with each other, share - data and defer processing. - - Usage: - - globally shared data: - > locator: parsing location, for error reporting - > path: current ProcessingPath for any logging of where we are located - - shared data: - > global attributes are parsed by one handler, but used by others - - post-processing support: - > can register AddIdlPostProcessor to perform some processing once - a full parsing pass has been done - - More data may be added in time if it involves separate XML parse handlers - needing to interact with each other. - """ - - def __init__(self, locator: Optional[xml.sax.xmlreader.Locator] = None): - self.path = ProcessingPath() - self.locator = locator - self.file_name = None - self._not_handled = set() - self._idl_post_processors = [] - - # Map of code -> attribute - self._global_attributes = {} - - def GetCurrentLocationMeta(self) -> Optional[ParseMetaData]: - if not self.locator: - return None - - return ParseMetaData(line=self.locator.getLineNumber(), column=self.locator.getColumnNumber()) - - def ParseLogLocation(self) -> Optional[str]: - if not self.file_name: - return None - meta = self.GetCurrentLocationMeta() - if not meta: - return None - - return f"{self.file_name}:{meta.line}:{meta.column}" - - def GetGlobalAttribute(self, code): - if code in self._global_attributes: - return self._global_attributes[code] - - raise Exception( - 'Global attribute 0x%X (%d) not found. You probably need to load global-attributes.xml' % (code, code)) - - def GetGlobalAttributes(self): - return [attribute for code, attribute in self._global_attributes.items()] - - def AddGlobalAttribute(self, attribute: Attribute): - # NOTE: this may get added several times as both 'client' and 'server' - # however matter should not differentiate between the two - code = attribute.definition.code - logging.info('Adding global attribute 0x%X (%d): %s' % - (code, code, attribute.definition.name)) - - self._global_attributes[code] = attribute - - def MarkTagNotHandled(self): - path = str(self.path) - if path not in self._not_handled: - msg = "TAG %s was not handled/recognized" % path - - where = self.ParseLogLocation() - if where: - msg = msg + " at " + where - - logging.warning(msg) - self._not_handled.add(path) - - def AddIdlPostProcessor(self, processor: IdlPostProcessor, has_priority: bool = False): - if has_priority: - self._idl_post_processors.insert(0, processor) - else: - self._idl_post_processors.append(processor) - - def PostProcess(self, idl: Idl): - for p in self._idl_post_processors: - p.FinalizeProcessing(idl) - - self._idl_post_processors = [] diff --git a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/handlers.py b/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/handlers.py deleted file mode 100644 index 966d875c3355ed..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/handlers.py +++ /dev/null @@ -1,661 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -from typing import Any, Optional - -from matter_idl.matter_idl_types import (Attribute, Bitmap, Cluster, ClusterSide, Command, CommandQuality, ConstantEntry, DataType, - Enum, Event, EventPriority, EventQuality, Field, FieldQuality, Idl, Struct, StructQuality, - StructTag) - -from .base import BaseHandler, HandledDepth -from .context import Context, IdlPostProcessor -from .parsing import AttrsToAccessPrivilege, AttrsToAttribute, ParseInt - -LOGGER = logging.getLogger('matter-xml-parser') - - -class ClusterNameHandler(BaseHandler): - """Handles /configurator/cluster/name elements.""" - - def __init__(self, context: Context, cluster: Cluster): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._cluster = cluster - - def HandleContent(self, content): - self._cluster.name = content.replace(' ', '') - - -class AttributeDescriptionHandler(BaseHandler): - """Handles /configurator/cluster/attribute/description elements.""" - - def __init__(self, context: Context, attribute: Attribute): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._attribute = attribute - - def HandleContent(self, content: str): - self._attribute.definition.name = content.replace(' ', '') - - -class ClusterCodeHandler(BaseHandler): - """Handles /configurator/cluster/code elements.""" - - def __init__(self, context: Context, cluster: Cluster): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._cluster = cluster - - def HandleContent(self, content: str): - self._cluster.code = ParseInt(content) - - -class EventHandler(BaseHandler): - """Handles /configurator/cluster/event elements.""" - - def __init__(self, context: Context, cluster: Cluster, attrs): - super().__init__(context) - self._cluster = cluster - - if attrs['priority'] == 'debug': - priority = EventPriority.DEBUG - elif attrs['priority'] == 'info': - priority = EventPriority.INFO - elif attrs['priority'] == 'critical': - priority = EventPriority.CRITICAL - else: - raise Exception("Unknown event priority: %s" % attrs['priority']) - - self._event = Event( - priority=priority, - code=ParseInt(attrs['code']), - name=attrs['name'], - fields=[], - ) - - if attrs.get('isFabricSensitive', "false").lower() == 'true': - self._event.qualities |= EventQuality.FABRIC_SENSITIVE - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'field': - data_type = DataType(name=attrs['type']) - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=ParseInt(attrs['id']), - name=attrs['name'], - is_list=(attrs.get('array', 'false').lower() == 'true'), - ) - - if attrs.get('optional', "false").lower() == 'true': - field.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - field.qualities |= FieldQuality.NULLABLE - - self._event.fields.append(field) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'access': - self._event.readacl = AttrsToAccessPrivilege(attrs) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def EndProcessing(self): - self._cluster.events.append(self._event) - - -class AttributeHandler(BaseHandler): - """Handles /configurator/cluster/attribute elements.""" - - def __init__(self, context: Context, cluster: Cluster, attrs): - super().__init__(context) - self._cluster = cluster - self._attribute = AttrsToAttribute(attrs) - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'access': - # Modifier not currently used: fabric scoped exists on the structure itself. - if 'modifier' in attrs: - if attrs['modifier'] != 'fabric-scoped': - raise Exception("UNKNOWN MODIFIER: %s" % attrs['modifier']) - - if ('role' in attrs) or ('privilege' in attrs): - role = AttrsToAccessPrivilege(attrs) - - if attrs['op'] == 'read': - self._attribute.readacl = role - elif attrs['op'] == 'write': - self._attribute.writeacl = role - else: - LOGGER.error("Unknown access: %r" % attrs['op']) - - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - return AttributeDescriptionHandler(self.context, self._attribute) - else: - return BaseHandler(self.context) - - def HandleContent(self, content: str): - # Content generally is the name EXCEPT if access controls - # exist, in which case `description` contains the name - content = content.strip() - if content and not self._attribute.definition.name: - self._attribute.definition.name = content - - def EndProcessing(self): - if self._attribute.definition.name is None: - raise Exception("Name for attribute was not parsed.") - - self._cluster.attributes.append(self._attribute) - - -class StructHandler(BaseHandler, IdlPostProcessor): - """ Handling /configurator/struct elements.""" - - def __init__(self, context: Context, attrs): - super().__init__(context) - - # if set, struct belongs to a specific cluster - self._cluster_codes = set() - self._struct = Struct(name=attrs['name'], fields=[]) - self._field_index = 0 - # The following are not set: - # - tag not set because not a request/response - # - code not set because not a response - - if attrs.get('isFabricScoped', "false").lower() == 'true': - self._struct.qualities |= StructQuality.FABRIC_SCOPED - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'item': - data_type = DataType( - name=attrs['type'] - ) - - if 'fieldId' in attrs: - field_index = ParseInt(attrs['fieldId']) - else: - # NOTE: code does NOT exist, so the number is incremental here - # this seems a defficiency in XML format. - field_index = self._field_index - self._field_index = field_index + 1 - - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=field_index, - name=attrs['name'], - is_list=(attrs.get('array', 'false').lower() == 'true'), - ) - - if attrs.get('optional', "false").lower() == 'true': - field.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - field.qualities |= FieldQuality.NULLABLE - - if attrs.get('isFabricSensitive', "false").lower() == 'true': - field.qualities |= FieldQuality.FABRIC_SENSITIVE - - self._struct.fields.append(field) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'cluster': - self._cluster_codes.add(ParseInt(attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - # We have two choices of adding a struct: - # - inside a cluster if a code exists - # - inside top level if no codes were associated - if self._cluster_codes: - for code in self._cluster_codes: - found = False - for c in idl.clusters: - if c.code == code: - c.structs.append(self._struct) - found = True - - if not found: - LOGGER.error('Enum %s could not find cluster (code %d/0x%X)' % - (self._struct.name, code, code)) - else: - idl.structs.append(self._struct) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class EnumHandler(BaseHandler, IdlPostProcessor): - """ Handling /configurator/enum elements.""" - - def __init__(self, context: Context, attrs): - super().__init__(context) - - # no cluster codes means global. Note that at the time - # of writing this, no global enums were defined in XMLs - self._cluster_codes = set() - self._enum = Enum(name=attrs['name'], - base_type=attrs['type'], entries=[]) - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'item': - self._enum.entries.append(ConstantEntry( - name=attrs['name'], - code=ParseInt(attrs['value']) - )) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'cluster': - self._cluster_codes.add(ParseInt(attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - # We have two choices of adding an enum: - # - inside a cluster if a code exists - # - inside top level if a code does not exist - - if not self._cluster_codes: - idl.enums.append(self._enum) - else: - found = set() - for c in idl.clusters: - if c.code in self._cluster_codes: - c.enums.append(self._enum) - found.add(c.code) - - if found != self._cluster_codes: - LOGGER.error('Enum %s could not find its clusters (codes: %r)' % - (self._enum.name, self._cluster_codes - found)) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class BitmapHandler(BaseHandler): - """ Handling /configurator/bitmap elements.""" - - def __init__(self, context: Context, attrs): - super().__init__(context) - self._cluster_codes = set() - self._bitmap = Bitmap( - name=attrs['name'], base_type=attrs['type'], entries=[]) - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'cluster': - # Multiple clusters may be associated, like IasZoneStatus - self._cluster_codes.add(ParseInt(attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'field': - self._bitmap.entries.append(ConstantEntry( - name=attrs['name'], - code=ParseInt(attrs['mask']) - )) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - # We have two choices of adding an enum: - # - inside a cluster if a code exists - # - inside top level if a code does not exist - if not self._cluster_codes: - # Log only instead of critical, as not our XML is well formed. - # For example at the time of writing this, SwitchFeature in switch-cluster.xml - # did not have a code associated with it. - LOGGER.error("Bitmap %r has no cluster codes" % self._bitmap) - return - - for code in self._cluster_codes: - found = False - for c in idl.clusters: - if c.code == code: - c.bitmaps.append(self._bitmap) - found = True - if not found: - LOGGER.error('Bitmap %s could not find its cluster (code %d/0x%X)' % - (self._bitmap.name, code, code)) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class DescriptionHandler(BaseHandler): - """Handles .../description text elements - - Attaches a "description" attribute to a given structure - """ - - def __init__(self, context: Context, target: Any): - super().__init__(context) - self.target = target - - def HandleContent(self, content): - self.target.description = content - - -class CommandHandler(BaseHandler): - """Handles /configurator/cluster/command elements.""" - - def __init__(self, context: Context, cluster: Cluster, attrs): - super().__init__(context) - self._cluster = cluster - self._command = None - self._struct = Struct(name=attrs['name'], fields=[]) - self._field_index = 0 # commands DO NOT support field index it seems - - if attrs['source'].lower() == 'client': - self._struct.tag = StructTag.REQUEST - - name = attrs['name'] - - if name.endswith('Request'): - request_name = name - else: - request_name = name+'Request' - - self._struct.name = request_name - - if 'response' in attrs: - response_name = attrs['response'] - else: - response_name = 'DefaultResponse' - - self._command = Command( - name=name, - code=ParseInt(attrs['code']), - input_param=request_name, - output_param=response_name, - ) - - if attrs.get('isFabricScoped', 'false') == 'true': - self._command.qualities |= CommandQuality.FABRIC_SCOPED - - if attrs.get('mustUseTimedInvoke', 'false') == 'true': - self._command.qualities |= CommandQuality.TIMED_INVOKE - - else: - self._struct.tag = StructTag.RESPONSE - self._struct.code = ParseInt(attrs['code']) - - def GetArgumentField(self, attrs): - data_type = DataType(name=attrs['type']) - - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=self._field_index, - name=attrs['name'], - is_list=(attrs.get('array', 'false') == 'true') - ) - - self._field_index += 1 - - if attrs.get('optional', "false").lower() == 'true': - field.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - field.qualities |= FieldQuality.NULLABLE - - return field - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'access': - if attrs['op'] != 'invoke': - raise Exception('Unknown access for %r' % self._struct) - - if self._command: - self._command.invokeacl = AttrsToAccessPrivilege(attrs) - else: - LOGGER.warning( - "Ignored access role for reply %r" % self._struct) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'arg': - self._struct.fields.append(self.GetArgumentField(attrs)) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - if self._command: - return DescriptionHandler(self.context, self._command) - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def EndProcessing(self): - - if self._struct.fields: - self._cluster.structs.append(self._struct) - else: - # no input - self._command.input_param = None - - if self._command: - self._cluster.commands.append(self._command) - - -class ClusterGlobalAttributeHandler(BaseHandler): - """Handles /configurator/cluster/globalAttribute elements.""" - - def __init__(self, context: Context, cluster: Cluster, code: int): - super().__init__(context) - self._cluster = cluster - self._code = code - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'featurebit': - # It is uncler what featurebits mean. likely a bitmap should be created - # here, however only one such example exists currently: door-lock-cluster.xml - LOGGER.info('Ignoring featurebit tag for global attribute 0x%X (%d)' % ( - self._code, self._code)) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - for attribute in self._cluster.attributes: - if attribute.definition.code == self._code: - # NOTE: For now the value is ignored, but if needed it could - # be updated here. - return - - self._cluster.attributes.append( - self.context.GetGlobalAttribute(self._code)) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class ClusterHandler(BaseHandler): - """Handles /configurator/cluster elements.""" - - def __init__(self, context: Context, idl: Optional[Idl]): - super().__init__(context) - self._cluster = Cluster( - side=ClusterSide.CLIENT, - name="NAME-MISSING", - code=-1, - parse_meta=context.GetCurrentLocationMeta() - ) - self._idl = idl - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'code': - return ClusterCodeHandler(self.context, self._cluster) - elif name.lower() == 'name': - return ClusterNameHandler(self.context, self._cluster) - elif name.lower() == 'attribute': - return AttributeHandler(self.context, self._cluster, attrs) - elif name.lower() == 'event': - return EventHandler(self.context, self._cluster, attrs) - elif name.lower() == 'globalattribute': - # We ignore 'side' and 'value' since they do not seem useful - return ClusterGlobalAttributeHandler(self.context, self._cluster, ParseInt(attrs['code'])) - elif name.lower() == 'command': - return CommandHandler(self.context, self._cluster, attrs) - elif name.lower() == 'description': - return DescriptionHandler(self.context, self._cluster) - elif name.lower() in ['define', 'domain', 'tag', 'client', 'server']: - # NOTE: we COULD use client and server to create separate definitions - # of each, but the usefulness of this is unclear as the definitions are - # likely identical and matter has no concept of differences between the two - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def EndProcessing(self): - if not self._idl: - raise Exception("Missing idl") - if self._cluster.name == "NAME-MISSING": - raise Exception("Missing cluster name") - elif self._cluster.code == -1: - raise Exception("Missing cluster code") - - self._idl.clusters.append(self._cluster) - -# Cluster extensions have extra bits for existing clusters. Can only be loaded -# IF the underlying cluster exits - - -class ClusterExtensionHandler(ClusterHandler, IdlPostProcessor): - """Handling /configurator/clusterExtension elements.""" - - def __init__(self, context: Context, code: int): - # NOTE: IDL is set to NONE so that ClusterHandler cannot - # inadvertently change it (it will be invalid anyway) - super().__init__(context, None) - self._cluster_code = code - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - def FinalizeProcessing(self, idl: Idl): - found = False - for c in idl.clusters: - if c.code == self._cluster_code: - found = True - - # Append everything that can be appended - c.enums.extend(self._cluster.enums) - c.bitmaps.extend(self._cluster.bitmaps) - c.events.extend(self._cluster.events) - c.attributes.extend(self._cluster.attributes) - c.structs.extend(self._cluster.structs) - c.commands.extend(self._cluster.commands) - - if not found: - LOGGER.error('Could not extend cluster 0x%X (%d): cluster not found' % - (self._cluster_code, self._cluster_code)) - - -class GlobalAttributeHandler(BaseHandler): - """Handling configurator/global/globalAttribute elements.""" - - def __init__(self, context: Context, attribute: Attribute): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._attribute = attribute - - def HandleContent(self, content: str): - # Content generally is the name EXCEPT if access controls - # exist, in which case `description` contains the name - # - # Global attributes do not currently have access controls, so this - # case is not handled here - content = content.strip() - if content and not self._attribute.definition.name: - self._attribute.definition.name = content - - def EndProcessing(self): - if self._attribute.definition.name is None: - raise Exception("Name for attribute was not parsed.") - - self.context.AddGlobalAttribute(self._attribute) - - -class GlobalHandler(BaseHandler): - """Handling configurator/global elements.""" - - def __init__(self, context: Context): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'attribute': - if attrs['side'].lower() == 'client': - # We expect to also have 'server' equivalent, so ignore client - # side attributes - LOGGER.debug( - 'Ignoring global client-side attribute %s' % (attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - - return GlobalAttributeHandler(self.context, AttrsToAttribute(attrs)) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - global_attributes = self.context.GetGlobalAttributes() - for cluster in idl.clusters: - cluster.attributes += global_attributes - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self, True) - - -class ConfiguratorHandler(BaseHandler): - """ Handling /configurator elements.""" - - def __init__(self, context: Context, idl: Idl): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._idl = idl - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'cluster': - return ClusterHandler(self.context, self._idl) - elif name.lower() == 'enum': - return EnumHandler(self.context, attrs) - elif name.lower() == 'struct': - return StructHandler(self.context, attrs) - elif name.lower() == 'bitmap': - return BitmapHandler(self.context, attrs) - elif name.lower() == 'domain': - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'clusterextension': - return ClusterExtensionHandler(self.context, ParseInt(attrs['code'])) - elif name.lower() == 'accesscontrol': - # These contain operation/role/modifier and generally only contain a - # description. These do not seem as useful to parse. - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'atomic': - # A list of types in 'chip-types' - # Generally does not seem useful - matches a type id to a description, size and some discrete/analog flags - # - # Could be eventually used as a preload of types into base types, however matter idl - # generator logic has hardcoded sizing as well. - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'devicetype': - # A list of device types in 'matter-devices.xml' - # Useful for conformance tests, but does not seem usable for serialization logic - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'global': - return GlobalHandler(self.context) - else: - return BaseHandler(self.context) diff --git a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/parsing.py b/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/parsing.py deleted file mode 100644 index 09243a627fea5e..00000000000000 --- a/scripts/py_matter_idl/build/lib/matter_idl/zapxml/handlers/parsing.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from matter_idl.matter_idl_types import AccessPrivilege, Attribute, AttributeQuality, DataType, Field, FieldQuality - - -def ParseInt(value: str) -> int: - """Convert a string that is a known integer into an actual number. - - Supports decimal or hex values prefixed with '0x' - """ - if value.startswith('0x'): - return int(value[2:], 16) - else: - return int(value) - - -def AttrsToAccessPrivilege(attrs) -> AccessPrivilege: - """Given attributes of an '' tag, generate the underlying - access privilege by looking at the role/privilege attribute. - """ - - # XML seems to use both role and privilege to mean the same thing - # they are used interchangeably - if 'role' in attrs: - role = attrs['role'] - else: - role = attrs['privilege'] - - if role.lower() == 'view': - return AccessPrivilege.VIEW - elif role.lower() == 'operate': - return AccessPrivilege.OPERATE - elif role.lower() == 'manage': - return AccessPrivilege.MANAGE - elif role.lower() == 'administer': - return AccessPrivilege.ADMINISTER - else: - raise Exception('Unknown ACL role: %r' % role) - - -def AttrsToAttribute(attrs) -> Attribute: - """Given the attributes of an '' tag, generate the - underlying IDL Attribute dataclass. - """ - - if attrs['type'].lower() == 'array': - data_type = DataType(name=attrs['entryType']) - else: - data_type = DataType(name=attrs['type']) - - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=ParseInt(attrs['code']), - name='', - is_list=(attrs['type'].lower() == 'array') - ) - - attribute = Attribute(definition=field) - - if attrs.get('optional', "false").lower() == 'true': - attribute.definition.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - attribute.definition.qualities |= FieldQuality.NULLABLE - - if attrs.get('readable', "true").lower() == 'true': - attribute.qualities |= AttributeQuality.READABLE - - if attrs.get('writable', "false").lower() == 'true': - attribute.qualities |= AttributeQuality.WRITABLE - - # TODO(#22937): NOSUBSCRIBE attribute tag is not available - could find no - # clear source to get this info. - - # NOTE: default values are also present in this XML, however generally IDL - # **DATA** definitions would not care about the defaults. The - # defaults should be used to initializ storage for devices, hence - # they are part of endpoint definition/composition. We are not doing - # that here, so defaults are ignored. - - return attribute diff --git a/scripts/py_matter_idl/examples/README.md b/scripts/py_matter_idl/examples/README.md deleted file mode 100644 index 5897d53e1e2a9d..00000000000000 --- a/scripts/py_matter_idl/examples/README.md +++ /dev/null @@ -1,25 +0,0 @@ -## Creating a custom matter_idl generator - -The matter_idl tool can be used to generate arbitrary code based on the Matter -data model schemas. To create a custom generator that lives outside of the -Matter SDK tree, follow the design pattern of -scripts/py_matter_idl/examples/matter_idl_plugin: - -1. Create a directory for your python generator module, for example - "matter_idl_plugin". -2. Add an `__init__.py` under "matter_idl_plugin" implementing a subclass of - `CodeGenerator` named `CustomGenerator`. -3. Have `CustomGenerator` load jinja templates, also under the - "matter_idl_plugin" subdirectory. -4. Execute the `codegen.py` script passing the path to the parent directory of - "matter_idl_plugin" via - `--generator custom::` argument and package - name like `--option package:com.example.matter.proto` - -``` -# From top-of-tree in this example -./scripts/codegen.py \ - --generator custom:./scripts/py_matter_idl/examples:matter_idl_plugin \ - --option package:com.example.matter.proto \ - ./src/controller/data_model/controller-clusters.matter -``` diff --git a/scripts/py_matter_idl/examples/matter_idl_plugin/__init__.py b/scripts/py_matter_idl/examples/matter_idl_plugin/__init__.py deleted file mode 100644 index 470ee09d5181f3..00000000000000 --- a/scripts/py_matter_idl/examples/matter_idl_plugin/__init__.py +++ /dev/null @@ -1,247 +0,0 @@ -# Copyright (c) 2023 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os - -from matter_idl.generators import CodeGenerator, GeneratorStorage -from matter_idl.matter_idl_types import Cluster, ClusterSide, Command, Field, Idl - - -def toUpperSnakeCase(s): - """ Convert camelCaseString to UPPER_SNAKE_CASE with proper handling of acronyms and numerals. """ - lastLower = False - letters = [] - for c in s: - if c.isupper(): - if lastLower: - letters.append('_') - letters.append(c) - lastLower = False - else: - letters.append(c.upper()) - lastLower = True - - return ''.join(letters) - - -def toLowerSnakeCase(s): - """ Convert camelCaseString to lower_snake_case with proper handling of acronyms and numerals. """ - return toUpperSnakeCase(s).lower() - - -def toUpperAcronym(s): - """ Remove lower case letters and numbers from the given string""" - return ''.join([i for i in s if i.isupper() or i.isnumeric()]).upper() - - -def toEnumEntryName(enumEntry, enumName): - """ Create enum entry name by prepending that acronym of the enum name and converting to upper snake case """ - prefix = toUpperAcronym(enumName) - if (enumEntry[0] == 'k'): - enumEntry = enumEntry[1:] - return prefix + '_' + toUpperSnakeCase(enumEntry) - - -def toProtobufType(zapType: str) -> str: - """ Convert zap type to protobuf type """ - u32Types = [ - "uint32", "enum8", "enum16", "enum32", "bitmap8", - "bitmap16", "bitmap32", "cluster_id", "attrib_id", - "event_id", "command_id", "endpoint_no", "group_id", - "devtype_id", "fabric_idx", "vendor_id", "status_code", - "faulttype", "levelcontroloptions", "percent100ths", - "percent" - ] - u64Types = [ - "uint64", "enum64", "bitmap64", "node_id", "fabric_id", - "int40u", "int48u", "int56u", "int64u" - ] - i32Types = ["int32", "int8s", "int16s", "int24s", "int32s"] - i64Types = ["int64", "int40s", "int48s", "int56s", "int64s"] - floatTypes = ["float", "double"] - stringTypes = ["char_string", "long_char_string"] - bytesTypes = ["octet_string", "long_octet_string"] - - zapTypeLower = zapType.lower() - if zapTypeLower in u32Types: - return "uint32" - if zapTypeLower in u64Types: - return "uint64" - if zapTypeLower in i32Types: - return "int32" - if zapTypeLower in i64Types: - return "int64" - if zapTypeLower in floatTypes: - return "float" - if zapTypeLower == "double": - return "double" - if zapTypeLower == "boolean": - return "bool" - if zapTypeLower in stringTypes: - return "string" - if zapTypeLower in bytesTypes: - return "bytes" - - # If no match, return the original type name for the Struct, Enum, or Bitmap. - return zapType - - -# Enum for encoding the type information into protobuf field tag for stateless translation. -# These values encoded to the upper range of the protobuf field tag. -class EncodingDataType: - UINT = 1 - INT = 2 - BOOL = 3 - CHAR_STRING = 4 - OCT_STRING = 5 - STRUCT = 6 - FLOAT = 7 - DOUBLE = 8 - - @staticmethod - def fromType(protobufType: str): - if protobufType == "uint32": - return EncodingDataType.UINT - if protobufType == "uint64": - return EncodingDataType.UINT - if protobufType == "int32": - return EncodingDataType.INT - if protobufType == "int64": - return EncodingDataType.INT - if protobufType == "bool": - return EncodingDataType.BOOL - if protobufType == "string": - return EncodingDataType.CHAR_STRING - if protobufType == "bytes": - return EncodingDataType.OCT_STRING - if protobufType == "float": - return EncodingDataType.FLOAT - if protobufType == "double": - return EncodingDataType.DOUBLE - - # If not a primitive type, it is a named type; assume it is a Struct. - # NOTE: the actual type may be an Enum or Bitmap. - return EncodingDataType.STRUCT - - -def commandArgs(command: Command, cluster: Cluster): - """Return the list of fields for the command request for the given command and cluster.""" - for struct in cluster.structs: - if struct.name == command.input_param: - return struct.fields - - # If the command has no input parameters, just return an empty list. - return [] - - -def commandResponseArgs(command: Command, cluster: Cluster): - """Return the list of fields for the command response for the given command and cluster.""" - for struct in cluster.structs: - if struct.name == command.output_param: - return struct.fields - - return [] - - -def toEncodedTag(tag, typeNum: EncodingDataType): - """ Return the final encoded tag from the given field number and field encoded data type. - The Matter field type information is encoded into the upper range of the protobuf field - tag for stateless translation to Matter TLV. """ - tag = (int(typeNum) << 19) | int(tag) - return tag - - -def toProtobufFullType(field: Field): - """Return the full protobuf type for the given field, including repeated and optional specifiers.""" - prefix = "" - protobufType = toProtobufType(field.data_type.name) - if field.is_list: - prefix = "repeated " + prefix - elif field.is_optional: - prefix = "optional " + prefix - return prefix + protobufType - - -def toFieldTag(field: Field): - protobufType = toProtobufType(field.data_type.name) - typeNum = EncodingDataType.fromType(protobufType) - tag = toEncodedTag(field.code, typeNum) - return tag - - -def toFieldComment(field: Field): - protobufType = toProtobufType(field.data_type.name) - typeNum = EncodingDataType.fromType(protobufType) - tagComment = "/** %s Type: %d IsList: %d FieldId: %d */" % ( - field.data_type.name, typeNum, field.is_list, field.code) - return tagComment - - -class CustomGenerator(CodeGenerator): - """ - Example of a custom generator. Outputs protobuf representation of Matter clusters. - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, **kargs): - """ - Inintialization is specific for java generation and will add - filters as required by the java .jinja templates to function. - """ - super().__init__(storage, idl, fs_loader_searchpath=os.path.dirname(__file__)) - - if 'package' not in kargs: - raise Exception('Please provide a "--option package:" argument') - self.package = kargs['package'] - - # String helpers - self.jinja_env.filters['toLowerSnakeCase'] = toLowerSnakeCase - self.jinja_env.filters['toUpperSnakeCase'] = toUpperSnakeCase - - # Type helpers - self.jinja_env.filters['toEnumEntryName'] = toEnumEntryName - self.jinja_env.filters['toProtobufType'] = toProtobufType - self.jinja_env.filters['toEncodedTag'] = toEncodedTag - - # Tag helpers - self.jinja_env.filters['toFieldTag'] = toFieldTag - self.jinja_env.filters['toProtobufFullType'] = toProtobufFullType - self.jinja_env.filters['toFieldComment'] = toFieldComment - - # Command helpers - self.jinja_env.filters['commandArgs'] = commandArgs - self.jinja_env.filters['commandResponseArgs'] = commandResponseArgs - - def internal_render_all(self): - """ - Renders the given custom template to the given output filename. - """ - - # Every cluster has its own impl, to avoid - # very large compilations (running out of RAM) - for cluster in self.idl.clusters: - if cluster.side != ClusterSide.CLIENT: - continue - - filename = "proto/%s_cluster.proto" % toLowerSnakeCase( - cluster.name) - - # Header containing a macro to initialize all cluster plugins - self.internal_render_one_output( - template_path="matter_cluster_proto.jinja", - output_file_name=filename, - vars={ - 'cluster': cluster, - 'package': self.package, - } - ) diff --git a/scripts/py_matter_idl/examples/matter_idl_plugin/matter_cluster_proto.jinja b/scripts/py_matter_idl/examples/matter_idl_plugin/matter_cluster_proto.jinja deleted file mode 100644 index 1f390fd231414f..00000000000000 --- a/scripts/py_matter_idl/examples/matter_idl_plugin/matter_cluster_proto.jinja +++ /dev/null @@ -1,94 +0,0 @@ - -/// AUTO-GENERATED with matter_idl. - -syntax = "proto3"; - -package {{package}}; - -option java_multiple_files = true; - -message {{cluster.name}}Cluster { - // option (message_type) = MATTER_TRAIT; - - enum ClusterId { - CLUSTER_ID_UNSUPPORTED = 0; - CLUSTER_ID = {{cluster.code}}; - } -{%- if cluster.enums %} - - // Enums -{%- for entry in cluster.enums %} - enum {{entry.name}} { - {%- if (entry.entries[0].code != 0) %} - {{"unsupported" | toEnumEntryName(entry.name)}} = 0;{% endif -%} - {%- for field in entry.entries %} - {{field.name | toEnumEntryName(entry.name)}} = {{field.code}};{% endfor %} - } -{% endfor %}{% endif -%} -{%- if cluster.bitmaps %} - - // Bitmaps -{%- for entry in cluster.bitmaps %} - enum {{entry.name}} { - {{"unsupported" | toEnumEntryName(entry.name)}} = 0; - {%- for field in entry.entries %} - {{field.name | toEnumEntryName(entry.name)}} = {{field.code}};{% endfor %} - } -{% endfor %}{% endif -%} -{%- if cluster.structs %} - - // Structs -{%- for entry in cluster.structs %}{% if not entry.tag %} - message {{entry.name}} { - {%- for field in entry.fields %} - {{field | toFieldComment}} - {{field | toProtobufFullType}} {{field.name | toLowerSnakeCase}} = {{field | toFieldTag}};{% endfor %} - } -{% endif %}{% endfor %}{% endif -%} -{%- if cluster.attributes %} - - // Attributes -{%- for attr in cluster.attributes %} - {{attr.definition | toFieldComment}} - {{attr.definition.data_type.name | toProtobufType}} {{attr.definition.name | toLowerSnakeCase}} = {{attr.definition | toFieldTag()}}; - /* - [(attribute) = { -{%- if attr.is_writable %} - is_writable : true,{% endif %} -{%- if attr.is_subscribable %} - is_subscribable: true,{% endif %} - }]; - */ - -{% endfor %}{% endif -%} -{%- if cluster.commands %} - - // Commands -{%- for cmd in cluster.commands %} - message {{cmd.name}}Command { - // option (message_type) = MATTER_COMMAND; - {% if cmd.input_param %}{%- for field in cmd | commandArgs(cluster) %} - {{field | toFieldComment}} - {{field | toProtobufFullType}} {{field.name | toLowerSnakeCase}} = {{field | toFieldTag}};{% endfor %}{% endif %} - }{% if cmd.output_param != "DefaultSuccess" %} - - message {{cmd.name}}CommandResponse { - // option (message_type) = MATTER_COMMAND_RESPONSE; - {% if cmd.output_param %}{%- for field in cmd | commandResponseArgs(cluster) %} - {{field | toFieldComment}} - {{field | toProtobufFullType}} {{field.name | toLowerSnakeCase}} = {{field | toFieldTag}};{% endfor %}{% endif %} - }{% endif %} -{% endfor %}{% endif %} - -{%- if cluster.events %} - // Events -{%- for entry in cluster.events %} - message {{entry.name}} { - // option (message_type) = MATTER_EVENT; - {% for field in entry.fields %} - {{field | toFieldComment}} - {{field | toProtobufFullType}} {{field.name | toLowerSnakeCase}} = {{field | toFieldTag}};{% endfor %} - } - -{% endfor %}{% endif %} -} // {{cluster.name}}Cluster diff --git a/scripts/py_matter_idl/files.gni b/scripts/py_matter_idl/files.gni deleted file mode 100644 index bfcfd27aec6fcd..00000000000000 --- a/scripts/py_matter_idl/files.gni +++ /dev/null @@ -1,51 +0,0 @@ -import("//build_overrides/build.gni") -import("//build_overrides/chip.gni") - -# Templates used for generation -matter_idl_generator_templates = [ - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_cpp.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_h.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/CHIPCallbackTypes.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ChipEventStructs.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/CHIPGlobalCallbacks_cpp.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/CHIPReadCallbacks_h.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ChipStructs.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ClusterIDMapping.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ClusterReadMapping.jinja", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ClusterWriteMapping.jinja", -] - -matter_idl_generator_sources = [ - "${chip_root}/scripts/py_matter_idl/matter_idl/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/filters.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/registry.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/generators/types.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/lint/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/lint/types.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/matter_idl_parser.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/matter_idl_types.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/test_generators.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/test_xml_parser.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/xml_parser.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py", - "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py", -] - -# All the files that the matter idl infrastructure will use -matter_idl_generator_files = - matter_idl_generator_templates + matter_idl_generator_sources diff --git a/scripts/py_matter_idl/matter_idl/README.md b/scripts/py_matter_idl/matter_idl/README.md deleted file mode 100644 index 4446760bc5dc90..00000000000000 --- a/scripts/py_matter_idl/matter_idl/README.md +++ /dev/null @@ -1,239 +0,0 @@ -# IDL based codegen - -## What is a matter IDL - -A matter IDL is a text-file that aims to be a concise representation of data -structures, cluster definitions and bindings. It is intended for human -readability (has to be clear and concise, supports comments) as well as machine -parsing (well defined syntax, not free form). - -The actual grammar is defined as a -[Lark](https://lark-parser.readthedocs.io/en/latest/index.html) parsing grammar, -however it may be easier to understand with an example: - -``` -/* C++ comments are supported */ -// so are C-style ones - - -// Types such as enums and structs can be defined globally -// An enum has a name and must have an underlying type (a sized integer defining -// storage size and how it gets transmitted over the wire) -enum StatusCode : ENUM8 { - kBusy = 1; // every enum MUST have an integer value - kPAKEParameterError = 0x02; // throughout, either HEX or integer can be used - kWindowNotOpen = 3; -} - -// Structures just have a name -struct LabelStruct { - CHAR_STRING<16> label = 0; // structure fields have a type. Some types can be sized (strings, octet strings) - CHAR_STRING<16> value = 1; // every structure field has an index. this is the tag when encoding over the wire -} - -// Server clusters are clusters that are expected to be exposed as servers -// -// Clusters may have optional things (e.g. optional attributes). A server -// cluster only defines attributes actually exposed by the server. -// -// Every cluster has an identifier that is defined by the matter spec (31 in this case) -server cluster AccessControl = 31 { - - // Enums and structs can be defined globally or be cluster specific. - // IDL generation rules will take into account scoping (i.e. pick local defined - // name first, things defined in one cluster are not visible in another). - enum AuthMode : ENUM8 { - kPase = 1; - kCase = 2; - kGroup = 3; - } - - // structures may be fabric scoped by tagging them as 'fabric_scoped' - // in a fabric scoped structure, fields may be 'fabric_sensitive' - fabric_scoped struct AccessControlEntry { - fabric_idx fabricIndex = 0; - fabric_sensitive Privilege privilege = 1; - fabric_sensitive AuthMode authMode = 2; - nullable fabric_sensitive INT64U subjects[] = 3; // fields in structures may be lists and - nullable fabric_sensitive Target targets[] = 4; // they may have attributes: nullable - } - - // request structures are regular structures that are used - // as command inputs. Special tagging to make the use clear. - request struct AnnounceOTAProviderRequest {} - request struct ConnectNetworkRequest { - OCTET_STRING networkID = 0; - INT64U breadcrumb = 1; - } - - // Response structures are used for command outputs - // Responses are encoded as a command and use a unique ID for encoding - response struct ConnectNetworkResponse = 123 { - CHAR_STRING debugText = 1; - INT32S errorValue = 2; - } - - // events can be specified with a type (critical/info) and may contain data - critical event StartUp = 0 { - INT32U softwareVersion = 0; - } - - // no-data events are supported - info event Leave = 2 { - } - - // events default to 'view' privilege however this can be modified - info event access(read: manage) RestrictedEvent = 3 { - } - - attribute AccessControlEntry acl[] = 0; // attributes are read-write by default - attribute ExtensionEntry extension[] = 1; // and require a (spec defined) number - - // attributes may require timed writes - timedwrite attribute int16u require_timed_writes = 3; - - // Access control privileges on attributes default to: - // - // access(read: view, write: operate) - // - // These defaults can be modified to any of view/operate/manage/administer roles. - attribute access(read: manage, write: administer) int32u customAcl = 3; - - // attributes may be read-only as well - readonly attribute int16u clusterRevision = 65533; - - // Commands have spec-defined numbers which are used for over-the-wire - // invocation. - // - // Commands have input and output data types, generally encoded as structures. - command ConnectNetwork(ConnectNetworkRequest): ConnectNetworkResponse = 0; - - // An output is always available even if just for ok/failure, however - // IDLs specifically do not define a structure for DefaultSuccess. - // - // which is considered an internal type. - command AnnounceOTAProvider(AnnounceOTAProviderRequest): DefaultSuccess = 1; - - // Some commands may take no inputs at all - command On(): DefaultSuccess = 2; - command Off(): DefaultSuccess = 3; - - // command invocation default to "operate" privilege, however these - // can be modified as well - command access(invoke: administer) Off(): DefaultSuccess = 4; - - // command invocation can require timed invoke usage - timed command access(invoke: administer) RevokeCommissioning(): DefaultSuccess = 2; - - // commands may be fabric scoped - fabric command ViewGroup(ViewGroupRequest): ViewGroupResponse = 1; - - // commands may have multiple attributes - fabric timed command RequiresTimedInvoke(): DefaultSuccess = 7; -} - -// A client cluster represents something that is used by an app -// but no server is exposed. -// -// A code generation may generate either combination of client and server -// clusters for a given cluster name. -// -// Even if both client and server cluster are declared within an IDL, their -// content may differ. For example -// - server cluster contains only attributes that the server exposes. As such -// some optional attributes may be missing. -// -// - client cluster contains attributes that the app wants to access as a -// client. So an optional attribute may be presented because the -// underlying application can make use of that attribute. -client cluster OtaSoftwareUpdateProvider = 41 { - ///.... content removed: it is very similar to a server cluster -} - - -// On every endpoint number (non-dynamic) -// a series of clusters can be exposed -endpoint 0 { - // A binding cluster is a CLIENT cluster that can be bound to for the - // application to make use. - // - // As an example, a light switch can be bound to a light bulb or - // a cluster can be bound to a OTA provider to use for updates. - binding cluster OtaSoftwareUpdateProvider; - - // A server cluster is a server that gets exposed to the world. - // - // As an example, a light bulb may expose a OnOff cluster. - server cluster OtaSoftwareUpdateRequestor { - - // Each endpoint server cluster instantiations will have individual - // attributes chosen for storage/defaults - // - // If no storage default is given, the value is initialized with 0/false/empty - // - // Defaults are currently only supported for primitive types (i.e. not - // list/struct/array, but supports strings) - - ram attribute zeroInit; // initialized with 0. - ram attribute stringDefault default="abc"; // Strings can have defaults. - ram attribute boolDefault default=true; // bools can have defaults. - ram attribute inRam default=123; // stored in RAM, lost on reboot. - persist attribute persist; // persisted in NVM across reboot. - callback attribute usesCallback; // the zap/ember 'EXTERNAL' callback. - } -} - -``` - -## Parsing of IDLs - -IDL parsing is done within the `matter_idl` python package (this is the current -directory of this README). Most of the heavy lifting is done by the lark using -[matter_grammar.lark](./matter_grammar.lark), which is then turned into an AST: - -- [matter_grammar.lark](./matter_grammar.lark) parses and validates textual - content -- [matter_idl_parser.py](./matter_idl_parser.py) has a transformer that - converts the text given by lark into a more type-safe (and type-rich) AST as - defined ing [matter_idl_types.py](./matter_idl_types.py) - -## Code generation - -Code generators are defined in `generators` and their purpose is to convert the -parsed AST into one or several output files. In most cases the output will be -split per cluster so that large CPP files are not generated (faster and more -parallel compilation). - -### Code generator base functionality - -Generators use [Jinja2](https://jinja.palletsprojects.com/en/3.0.x/) as a -templating language. The general `CodeGenerator` class in -[generators/**init**.py](./generators/__init__.py) provides the ability to -output files based on jinja templates. - -In order to build working jinja2 templates, some further processing of the AST -data is required. Some facilities for lookup namespacing (e.g. search for named -data types within cluster first then globally) as well interpretation of data -types into more concrete types is provided by `generators/types.py`. - -### Implementing generators - -Beyond default AST processing, each generator is expected to add -language-specific filters to create templates that work. This includes: - -- add any additional filters and transforms for data -- add any additional type processing that is language specific - -See the java code generator in `generators/java` as an example of codegen. - -### Testing generators - -Tests of generation are based on checking that a given input matches an expected -output. The [tests/available_tests](./test/available_tests.yaml) describe for -each input and generator the expected output. - -Intent for tests is to be focused and still easy to see deltas. Input IDLs are -expected to be small and focusing on a specific functionality. Keep in mind that -the test outputs are expected to be human-reviwed when codegen logic changes. - -These generator tests are run by `test_generators.py`. diff --git a/scripts/py_matter_idl/matter_idl/__init__.py b/scripts/py_matter_idl/matter_idl/__init__.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/scripts/py_matter_idl/matter_idl/generators/__init__.py b/scripts/py_matter_idl/matter_idl/generators/__init__.py deleted file mode 100644 index 131d8e38ccbeba..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/__init__.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import os -from typing import Dict, Optional - -import jinja2 -from matter_idl.matter_idl_types import Idl - -from .filters import RegisterCommonFilters - - -class GeneratorStorage: - """ - Handles file operations for generator output. Specifically can create - required files for output. - - Is overriden for unit tests. - """ - - def __init__(self): - self._generated_paths = set() - - @property - def generated_paths(self): - return self._generated_paths - - def report_output_file(self, relative_path: str): - self._generated_paths.add(relative_path) - - def get_existing_data(self, relative_path: str): - """Gets the existing data at the given path. - If such data does not exist, will return None. - """ - raise NotImplementedError() - - def write_new_data(self, relative_path: str, content: str): - """Write new data to the given path.""" - raise NotImplementedError() - - -class FileSystemGeneratorStorage(GeneratorStorage): - """ - A storage generator which will physically write files to disk into - a given output folder. - """ - - def __init__(self, output_dir: str): - super().__init__() - self.output_dir = output_dir - - def get_existing_data(self, relative_path: str): - """Gets the existing data at the given path. - If such data does not exist, will return None. - """ - target = os.path.join(self.output_dir, relative_path) - - if not os.path.exists(target): - return None - - logging.info("Checking existing data in %s" % target) - with open(target, 'rt') as existing: - return existing.read() - - def write_new_data(self, relative_path: str, content: str): - """Write new data to the given path.""" - - target = os.path.join(self.output_dir, relative_path) - target_dir = os.path.dirname(target) - if not os.path.exists(target_dir): - logging.info("Creating output directory: %s" % target_dir) - os.makedirs(target_dir) - - logging.info("Writing new data to: %s" % target) - with open(target, "wt") as out: - out.write(content) - - -class CodeGenerator: - """ - Defines the general interface for things that can generate code output. - - A CodeGenerator takes a AST as input (a `Idl` type) and generates files - as output (like java/cpp/mm/other). - - Its public interface surface is reasonably small: - 'storage' init argument specifies where generated code goes - 'idl' is the input AST to generate - 'render' will perform a rendering of all files. - - As special optimizations, CodeGenerators generally will try to read - existing data and will not re-write content if not changed (so that - write time of files do not change and rebuilds are not triggered). - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, loader: Optional[jinja2.BaseLoader] = None, fs_loader_searchpath: Optional[str] = None): - """ - A code generator will render a parsed IDL (a AST) into a given storage. - - Args: - storage: Storage to use to read/save data - loader: if given, use a custom loader for templates - fs_loader_searchpath: if a loader is NOT given, this controls the search path - of a default FileSystemLoader that will be used - """ - if not loader: - if not fs_loader_searchpath: - fs_loader_searchpath = os.path.dirname(__file__) - loader = jinja2.FileSystemLoader(searchpath=fs_loader_searchpath) - - self.storage = storage - self.idl = idl - self.jinja_env = jinja2.Environment( - loader=loader, keep_trailing_newline=True) - self.dry_run = False - - RegisterCommonFilters(self.jinja_env.filters) - - def render(self, dry_run=False): - """ - Renders all required files given the idl contained in the code generator. - Reset the list of generated outputs. - - Args: - dry_run: if true, outputs are not actually written to disk. - if false, outputs are actually written to disk. - """ - self.dry_run = dry_run - self.internal_render_all() - - def internal_render_all(self): - """This method is to be implemented by subclasses to run all generation - as needed. - """ - raise NotImplementedError("Method should be implemented by subclasses") - - def internal_render_one_output(self, template_path: str, output_file_name: str, vars: Dict): - """ - Method to be called by subclasses to mark that a template is to be generated. - - File will either actually do a jinja2 generation or just log things - if dry-run was requested during `render`. - - NOTE: to make this method suitable for rebuilds, this file will NOT alter - the timestamp of the output file if the file content would not - change (i.e. no write will be invoked in that case.) - - Args: - template_path - the path to the template to be loaded for file generation. - Template MUST be a jinja2 template. - output_file_name - File name that the template is to be generated to. - vars - variables used for template generation - """ - logging.info("File to be generated: %s" % output_file_name) - if self.dry_run: - return - - rendered = self.jinja_env.get_template(template_path).render(vars) - - # Report regardless if it has changed or not. This is because even if - # files are unchanged, validation of what the correct output is should - # still be done. - self.storage.report_output_file(output_file_name) - - if rendered == self.storage.get_existing_data(output_file_name): - logging.info("File content not changed") - else: - self.storage.write_new_data(output_file_name, rendered) diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py b/scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py deleted file mode 100644 index e69de29bb2d1d6..00000000000000 diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja b/scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja deleted file mode 100644 index cd800400dc4d10..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include -#include -#include - -using namespace chip; - -// Cluster Init Functions -void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) -{ - switch (clusterId) - { - {%- for name in clusters | sort(attribute='name') | map(attribute='name') | unique %} - case app::Clusters::{{name}}::Id: - emberAf{{name}}ClusterInitCallback(endpoint); - break; - {%- endfor %} - default: - // Unrecognized cluster ID - break; - } -} - -{%- for name in clusters | sort(attribute='name') | map(attribute='name') | unique %} -void __attribute__((weak)) emberAf{{name}}ClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -{%- endfor %} diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja b/scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja deleted file mode 100644 index 2e31426b3d05fc..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -{%- for cluster in clusters | serverClustersOnly | sort(attribute='name') %} -void Matter{{ cluster.name }}PluginServerInitCallback(); -{%- endfor %} - -#define MATTER_PLUGINS_INIT \ -{%- for cluster in clusters | serverClustersOnly | sort(attribute='name') %} - Matter{{ cluster.name }}PluginServerInitCallback();{{ " \\" if not loop.last else ""}} -{%- else %} - (void)0; /* No server side clusters */ -{%- endfor %} - diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py b/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py deleted file mode 100644 index 2b9158864d28e4..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from typing import List - -from matter_idl.generators import CodeGenerator, GeneratorStorage -from matter_idl.matter_idl_types import Cluster, ClusterSide, Idl - - -def serverClustersOnly(clusters: List[Cluster]) -> List[Cluster]: - return [c for c in clusters if c.side == ClusterSide.SERVER] - - -class CppApplicationGenerator(CodeGenerator): - """ - Generation of cpp code for application implementation for matter. - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, **kargs): - """ - Inintialization is specific for java generation and will add - filters as required by the java .jinja templates to function. - """ - super().__init__(storage, idl, fs_loader_searchpath=os.path.dirname(__file__)) - - self.jinja_env.filters['serverClustersOnly'] = serverClustersOnly - - def internal_render_all(self): - """ - Renders the cpp and header files required for applications - """ - - # Header containing a macro to initialize all cluster plugins - self.internal_render_one_output( - template_path="PluginApplicationCallbacksHeader.jinja", - output_file_name="app/PluginApplicationCallbacks.h", - vars={ - 'clusters': self.idl.clusters, - } - ) - - # Source for __attribute__(weak) implementations of all cluster - # initialization methods - self.internal_render_one_output( - template_path="CallbackStubSource.jinja", - output_file_name="app/callback-stub.cpp", - vars={ - 'clusters': self.idl.clusters, - } - ) diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_cpp.jinja b/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_cpp.jinja deleted file mode 100644 index 548f8f399feb66..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_cpp.jinja +++ /dev/null @@ -1,44 +0,0 @@ -#include - -namespace chip { -namespace TLVMeta { -namespace { - -using namespace chip::FlatTree; -using namespace chip::TLV; - -{%- for table in sub_tables %} - -const Entry _{{table.full_name}}[] = { - {%- for entry in table.entries %} - { { {{entry.code}}, "{{entry.name}}", ItemType::{{entry.item_type}} }, {{entry.reference | indexInTable(sub_tables)}} }, // {{entry.real_type}} - {%- endfor %} -}; -{%- endfor %} - -const Entry _all_clusters[] = { -{%- for cluster in clusters | sort(attribute='code') %} - { { ClusterTag({{"0x%02X" | format(cluster.code)}}), "{{cluster.name}}", ItemType::kDefault }, {{cluster.name | indexInTable(sub_tables)}} }, -{%- endfor %} - -}; - -// For any non-structure list like u64[] or similar. -const Entry _primitive_type_list[] = { - { { AnonymousTag(), "Anonymous<>", ItemType::kDefault }, kInvalidNodeIndex }, -}; - -} // namespace - -#define _ENTRY(n) { sizeof(n) / sizeof(n[0]), n} - -const std::array, {{ sub_tables | length }} + 2> {{table_name}} = { { - _ENTRY(_all_clusters), // 0 - _ENTRY(_primitive_type_list), // 1 -{%- for table in sub_tables %} - _ENTRY(_{{table.full_name}}), // {{loop.index + 1}} -{%- endfor %} -} }; - -} // namespace TLVMeta -} // namespace chip diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_h.jinja b/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_h.jinja deleted file mode 100644 index f8d1e77b60de33..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/TLVMetaData_h.jinja +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include - -#include - -namespace chip { -namespace TLVMeta { - -extern const std::array, {{ sub_tables | length }} + 2> {{table_name}}; - -} // namespace TLVMeta -} // namespace chip diff --git a/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/__init__.py b/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/__init__.py deleted file mode 100644 index 46c7de39498fac..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/cpp/tlvmeta/__init__.py +++ /dev/null @@ -1,315 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2023 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -from dataclasses import dataclass -from typing import Generator, List, Optional - -from matter_idl.generators import CodeGenerator, GeneratorStorage -from matter_idl.matter_idl_types import Cluster, ClusterSide, Field, Idl, StructTag - - -@dataclass -class TableEntry: - code: str # Encoding like ContextTag() or AnonymousTag() or similar - name: str # human friendly name - reference: Optional[str] # reference to full name - real_type: str # real type - item_type: str = 'kDefault' # type flag for decoding - - -@dataclass -class Table: - # Usable variable fully qualified name (like _) - full_name: str - entries: List[TableEntry] - - -class ClusterTablesGenerator: - """Handles conversion from a cluster to tables.""" - - def __init__(self, cluster: Cluster): - self.cluster = cluster - self.known_types = set() # all types where we create reference_to - self.list_types = set() # all types that require a list entry - self.item_type_map = { - "protocol_cluster_id": "kProtocolClusterId", - "protocol_attribute_id": "kProtocolAttributeId", - "protocol_command_id": "kProtocolCommandId", - "protocol_event_id": "kProtocolEventId", - - "cluster_attribute_payload": "kProtocolPayloadAttribute", - "cluster_command_payload": "kProtocolPayloadCommand", - "cluster_event_payload": "kProtocolPayloadEvent", - - "protocol_binary_data": "kProtocolBinaryData", - } - - for e in self.cluster.enums: - self.item_type_map[e.name] = "kEnum" - - for b in self.cluster.bitmaps: - self.item_type_map[b.name] = "kBitmap" - - def FieldEntry(self, field: Field, tag_type: str = 'ContextTag', type_override: Optional[str] = None) -> TableEntry: - data_type_name = type_override or field.data_type.name - type_reference = "%s_%s" % (self.cluster.name, data_type_name) - - if type_reference not in self.known_types: - type_reference = None - - item_type = self.item_type_map.get(data_type_name, 'kDefault') - - real_type = "%s::%s" % (self.cluster.name, data_type_name) - if field.is_list: - real_type = real_type + "[]" - item_type = "kList" - - if type_reference: - self.list_types.add(type_reference) - type_reference = type_reference + "_list_" - else: - type_reference = "primitive_type_list_" - - return TableEntry( - code=f'{tag_type}({field.code})', - name=field.name, - reference=type_reference, - real_type=real_type, - item_type=item_type, - ) - - def ComputeKnownTypes(self): - self.known_types.clear() - - for s in self.cluster.structs: - self.known_types.add("%s_%s" % (self.cluster.name, s.name)) - - # Events are structures - for e in self.cluster.events: - if e.fields: - self.known_types.add("%s_%s" % (self.cluster.name, e.name)) - - for e in self.cluster.enums: - self.known_types.add("%s_%s" % (self.cluster.name, e.name)) - - for b in self.cluster.bitmaps: - self.known_types.add("%s_%s" % (self.cluster.name, b.name)) - - def CommandEntries(self) -> Generator[TableEntry, None, None]: - # yield entries for every command input - for c in self.cluster.commands: - if c.input_param: - yield TableEntry( - name=c.name, - code=f'CommandTag({c.code})', - reference="%s_%s" % ( - self.cluster.name, c.input_param), - real_type="%s::%s::%s" % ( - self.cluster.name, c.name, c.input_param) - ) - else: - yield TableEntry( - name=c.name, - code=f'CommandTag({c.code})', - reference=None, - real_type="%s::%s::()" % ( - self.cluster.name, c.name) - ) - - # yield entries for every command output. We use "respons struct" - # for this to figure out where to tag IDs from. - for c in self.cluster.structs: - if c.tag != StructTag.RESPONSE: - continue - yield TableEntry( - name=c.name, - code=f'CommandTag({c.code})', - reference="%s_%s" % ( - self.cluster.name, c.name), - real_type="%s::%s" % (self.cluster.name, c.name), - ) - - def GenerateTables(self) -> Generator[Table, None, None]: - self.ComputeKnownTypes() - - cluster_feature_map = None - for b in self.cluster.bitmaps: - # Older matter files use `ClusterNameFeature` as naming, newer code was - # updated to just `Feature`. For now support both. - if b.name in {'Feature', f'{self.cluster.name}Feature'} and b.base_type.lower() == 'bitmap32': - cluster_feature_map = b.name - - # Clusters have attributes. They are direct descendants for - # attributes - cluster_entries = [] - cluster_entries.extend([ - self.FieldEntry(a.definition, tag_type='AttributeTag', - type_override=(cluster_feature_map if a.definition.code == 0xFFFC else None)) - for a in self.cluster.attributes - ]) - - cluster_entries.extend([ - # events always reference an existing struct - TableEntry( - code=f'EventTag({e.code})', - name=e.name, - reference="%s_%s" % (self.cluster.name, e.name), - real_type='%s::%s' % (self.cluster.name, e.name) - ) - for e in self.cluster.events if e.fields - ]) - cluster_entries.extend( - [entry for entry in self.CommandEntries()] - ) - - yield Table( - full_name=self.cluster.name, - entries=cluster_entries, - ) - - for s in self.cluster.structs: - yield Table( - full_name="%s_%s" % (self.cluster.name, s.name), - entries=[self.FieldEntry(field) for field in s.fields] - ) - - for e in self.cluster.events: - if e.fields: - yield Table( - full_name="%s_%s" % (self.cluster.name, e.name), - entries=[self.FieldEntry(field) for field in e.fields] - ) - - # some items have lists, create an intermediate item for those - for name in self.list_types: - yield Table( - full_name="%s_list_" % name, - entries=[ - TableEntry( - code="AnonymousTag()", - name="Anonymous<>", - reference=name, - real_type="%s[]" % name, - ) - ] - ) - - for e in self.cluster.enums: - yield Table( - full_name="%s_%s" % (self.cluster.name, e.name), - entries=[ - TableEntry( - code="ConstantValueTag(0x%X)" % entry.code, - name=entry.name, - reference=None, - real_type="%s::%s::%s" % ( - self.cluster.name, e.name, entry.name) - ) - for entry in e.entries - ] - ) - - for e in self.cluster.bitmaps: - yield Table( - full_name="%s_%s" % (self.cluster.name, e.name), - entries=[ - TableEntry( - code="ConstantValueTag(0x%X)" % entry.code, - name=entry.name, - reference=None, - real_type="%s::%s::%s" % ( - self.cluster.name, e.name, entry.name) - ) - for entry in e.entries - ] - ) - - -def CreateTables(idl: Idl) -> List[Table]: - result = [] - for cluster in idl.clusters: - result.extend( - [table for table in ClusterTablesGenerator(cluster).GenerateTables()]) - - return result - - -def IndexInTable(name: Optional[str], table: List[Table]) -> str: - """Find the index of the given name in the table. - - The index is 1-based (to allow for a first entry containing a - starting point for the app) - """ - if not name: - return "kInvalidNodeIndex" - - if name == "primitive_type_list_": - return "1" - - for idx, t in enumerate(table): - if t.full_name == name: - # Index skipping hard-coded items - return "%d" % (idx + 2) - - raise Exception("Name %r not found in table" % name) - - -class TLVMetaDataGenerator(CodeGenerator): - """ - Generation of cpp code containing TLV metadata information. - - Epecting extra option for constant naming - - Example execution via codegen.py: - - ./scripts/codegen.py \ - --output-dir out/metaexample \ - --generator cpp-tlvmeta \ - --option table_name:protocols_meta \ - src/lib/format/protocol_messages.matter - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, table_name: str = "clusters_meta", **kargs): - super().__init__(storage, idl, fs_loader_searchpath=os.path.dirname(__file__)) - self.table_name = table_name - self.jinja_env.filters['indexInTable'] = IndexInTable - - def internal_render_all(self): - """ - Renders the cpp and header files required for applications - """ - - tables = CreateTables(self.idl) - - self.internal_render_one_output( - template_path="TLVMetaData_cpp.jinja", - output_file_name=f"tlv/meta/{self.table_name}.cpp", - vars={ - 'clusters': [c for c in self.idl.clusters if c.side == ClusterSide.CLIENT], - 'table_name': self.table_name, - 'sub_tables': tables, - - } - ) - - self.internal_render_one_output( - template_path="TLVMetaData_h.jinja", - output_file_name=f"tlv/meta/{self.table_name}.h", - vars={ - 'clusters': [c for c in self.idl.clusters if c.side == ClusterSide.CLIENT], - 'table_name': self.table_name, - 'sub_tables': tables, - } - ) diff --git a/scripts/py_matter_idl/matter_idl/generators/filters.py b/scripts/py_matter_idl/matter_idl/generators/filters.py deleted file mode 100644 index b1ea94a7cd36c6..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/filters.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import stringcase - - -def normalize_acronyms(s: str) -> str: - """Replaces variations of acronyms when converting various words. - - Specifically when considering how to generate a CONST_CASE constant, - strings such as WiFi should not be WI_FI but rather WIFI - """ - return s.replace('WiFi', 'Wifi').replace('WI_FI', 'WIFI') - - -def lowfirst(s: str) -> str: - """Make the first letter lowercase. """ - return s[0].lower() + s[1:] - - -def upfirst(s: str) -> str: - """Make the first letter uppercase """ - return s[0].upper() + s[1:] - - -def lowfirst_except_acronym(s: str) -> str: - """Make the first letter lowercase assuming the string is already in - CamelCase. - - Differs from lowfirst because it checks the string for starting with - several uppercase, which is the case for acronyms (HVAC, ACL, WIFI), - in which case it will NOT lowercase first - """ - if len(s) >= 2: - if s[1].isupper(): - return s - - return lowfirst(s) - - -def RegisterCommonFilters(filtermap): - """ - Register filters that are NOT considered platform-generator specific. - - Codegen often needs standardized names, like "method names are CamelCase" - or "command names need-to-be-spinal-case" so these filters are often - generally registered on all generators. - """ - - # General casing for output naming - filtermap['camelcase'] = stringcase.camelcase - filtermap['capitalcase'] = stringcase.capitalcase - filtermap['constcase'] = stringcase.constcase - filtermap['pascalcase'] = stringcase.pascalcase - filtermap['snakecase'] = stringcase.snakecase - filtermap['spinalcase'] = stringcase.spinalcase - - filtermap['normalize_acronyms'] = normalize_acronyms - filtermap['lowfirst'] = lowfirst - filtermap['lowfirst_except_acronym'] = lowfirst_except_acronym - filtermap['upfirst'] = upfirst diff --git a/scripts/py_matter_idl/matter_idl/generators/java/CHIPCallbackTypes.jinja b/scripts/py_matter_idl/matter_idl/generators/java/CHIPCallbackTypes.jinja deleted file mode 100644 index 2cc43bc99b0d7e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/CHIPCallbackTypes.jinja +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -typedef void (*CHIPDefaultSuccessCallbackType)(void *, const chip::app::DataModel::NullObjectType &); -typedef void (*CHIPDefaultWriteSuccessCallbackType)(void *); -typedef void (*CHIPDefaultFailureCallbackType)(void *, CHIP_ERROR); - -{% for cluster in clientClusters | sort(attribute='code') %} - {%- for response in cluster.structs | select('is_response_struct') -%} -typedef void (*CHIP{{cluster.name}}Cluster{{response.name}}CallbackType)(void *, const chip::app::Clusters::{{cluster.name}}::Commands::{{response.name}}::DecodableType &); - {%- endfor -%} - - {#- TODO: global response types? -#} - {%- for attribute in cluster.attributes | sort(attribute='name') %} -typedef void (*CHIP{{cluster.name}}Cluster{{attribute.definition.name | upfirst}}AttributeCallbackType)(void *, {##} - {%- if attribute.definition.is_list -%} - const chip::app::Clusters::{{cluster.name}}::Attributes::{{attribute.definition.name | upfirst}}::TypeInfo::DecodableType &); - {%- else -%} - chip::app::Clusters::{{cluster.name}}::Attributes::{{attribute.definition.name | upfirst}}::TypeInfo::DecodableArgType); - {%- endif -%} - {%- endfor -%} -{% endfor %} - diff --git a/scripts/py_matter_idl/matter_idl/generators/java/CHIPGlobalCallbacks_cpp.jinja b/scripts/py_matter_idl/matter_idl/generators/java/CHIPGlobalCallbacks_cpp.jinja deleted file mode 100644 index 3042568424a86e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/CHIPGlobalCallbacks_cpp.jinja +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -{% for type in globalTypes -%} -{%- set typeLookup = idl | createLookupContext(None) -%} -{%- set encodable = type.idl_type | globalAsEncodable(typeLookup) -%} -CHIP{{type.name}}AttributeCallback::CHIP{{type.name}}AttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback<{{type.name}}AttributeCallback>(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIP{{type.name}}AttributeCallback::~CHIP{{type.name}}AttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIP{{type.name}}AttributeCallback::CallbackFn(void * context, {{type.cpp_type}} value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - {%- if encodable.is_octet_string %} - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "([B)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - - VerifyOrReturn(chip::CanCastTo(value.size()), ChipLogError(Zcl, "Value too long")); - jbyteArray valueArr = env->NewByteArray(static_cast(value.size())); - env->ExceptionClear(); - env->SetByteArrayRegion(valueArr, 0, static_cast(value.size()), reinterpret_cast(value.data())); - - env->CallVoidMethod(javaCallbackRef, javaMethod, valueArr); - {%- elif encodable.is_char_string %} - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - - chip::UtfString valueStr(env, value); - env->CallVoidMethod(javaCallbackRef, javaMethod, valueStr.jniValue()); - {%- else %} - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "({{encodable.unboxed_java_signature}})V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast<{{encodable.jni_fundamental_type}}>(value)); - {%- endif %} -} - -{% endfor %} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/CHIPReadCallbacks_h.jinja b/scripts/py_matter_idl/matter_idl/generators/java/CHIPReadCallbacks_h.jinja deleted file mode 100644 index 63d730f87a1a9d..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/CHIPReadCallbacks_h.jinja +++ /dev/null @@ -1,81 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include - -{% for type in globalTypes -%} -class CHIP{{type.name}}AttributeCallback : public chip::Callback::Callback<{{type.name}}AttributeCallback> -{ -public: - CHIP{{type.name}}AttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIP{{type.name}}AttributeCallback(); - - static void maybeDestroy(CHIP{{type.name}}AttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, {{type.cpp_type}} value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -{% endfor %} - -{% for cluster in clientClusters | sort(attribute='code') %} - {% set typeLookup = idl | createLookupContext(cluster) %} - {%- for attr in cluster.attributes | rejectattr('definition', 'is_using_global_callback', typeLookup) %} -class CHIP{{cluster.name}}{{attr.definition.name | capitalcase}}AttributeCallback : public chip::Callback::Callback -{ -public: - CHIP{{cluster.name}}{{attr.definition.name | capitalcase}}AttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIP{{cluster.name}}{{attr.definition.name | capitalcase}}AttributeCallback(); - - static void maybeDestroy(CHIP{{cluster.name}}{{attr.definition.name | capitalcase}}AttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, {{attr.definition | decodableJniType(typeLookup)}} {%if attr.definition.is_list%}list{%else%}value{%endif%}); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - {% endfor %} -{% endfor %} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja deleted file mode 100644 index 22812797373cdf..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja +++ /dev/null @@ -1,216 +0,0 @@ -{%- macro encode_optional(target, source, depth, encodable) -%} - { - jobject optionalValue_{{depth}} = nullptr; - chip::JniReferences::GetInstance().GetOptionalValue({{source}}, optionalValue_{{depth}}); - if (optionalValue_{{depth}}) { - auto & definedValue_{{depth}} = {{target}}.Emplace(); - {{ encode_value( - "definedValue_{}".format(depth), - "optionalValue_{}".format(depth), - depth+1, - encodable.without_optional() - )}} - } - } -{%- endmacro %} - -{%- macro encode_nullable(target, source, depth, encodable) -%} - if ({{source}} == nullptr) { - {{target}}.SetNull(); - } else { - auto & nonNullValue_{{depth}} = {{target}}.SetNonNull(); - {{encode_value("nonNullValue_{}".format(depth), source, depth+1, encodable.without_nullable())}} - } -{%- endmacro %} - -{%- macro encode_list(target, source, depth, encodable) -%} - { - using ListType_{{depth}} = std::remove_reference_t; - using ListMemberType_{{depth}} = ListMemberTypeGetter::Type; - jint {{source}}Size; - chip::JniReferences::GetInstance().GetListSize({{source}}, {{source}}Size); - if ({{source}}Size != 0) { - auto * listHolder_{{depth}} = new ListHolder({{source}}Size); - listFreer.add(listHolder_{{depth}}); - - for (jint i_{{depth}} = 0; i_{{depth}} < {{source}}Size; ++i_{{depth}}) { - jobject element_{{depth}}; - chip::JniReferences::GetInstance().GetListItem({{source}}, i_{{depth}}, element_{{depth}}); - {{encode_value( - "listHolder_{}->mList[static_cast(i_{})]".format(depth, depth), - "element_{}".format(depth), - depth+1, encodable.without_list() - )}} - } - {{target}} = ListType_{{depth}}(listHolder_{{depth}}->mList, {{source}}Size); - } else { - {{target}} = ListType_{{depth}}(); - } - } -{%- endmacro %} - -{%- macro encode_value(target, source, depth, encodable) -%} - {%- if encodable.is_optional -%} - {{encode_optional(target, source, depth, encodable)}} - {%- elif encodable.is_nullable -%} - {{encode_nullable(target, source, depth, encodable)}} - {%- elif encodable.is_list -%} - {{encode_list(target, source, depth, encodable)}} - {%- elif encodable.is_octet_string -%} - cleanupByteArrays.push_back(chip::Platform::MakeUnique(env, static_cast({{source}}))); - {{target}} = cleanupByteArrays.back()->byteSpan(); - {%- elif encodable.is_char_string -%} - cleanupStrings.push_back(chip::Platform::MakeUnique(env, static_cast({{source}}))); - {{target}} = cleanupStrings.back()->charSpan(); - {%- elif encodable.is_struct -%} - {% set struct = encodable.get_underlying_struct() -%} - {% for field in struct.fields %} - {% set fieldEncodable = field | asEncodable(encodable.context) -%} - jobject {{source}}_{{field.name}}Item_{{depth}}; - chip::JniReferences::GetInstance().GetObjectField({{source}}, "{{field.name}}", "{{fieldEncodable.boxed_java_signature}}", {{source}}_{{field.name}}Item_{{depth}}); - {{ encode_value( - "{}.{}".format(target, field.name | lowercaseFirst), - "{}_{}Item_{}".format(source, field.name, depth), - depth + 1, - fieldEncodable - )}} - {%- endfor -%} - {%- elif encodable.is_enum -%} - {{target}} = static_cast>(chip::JniReferences::GetInstance().IntegerToPrimitive({{source}})); - {%- elif encodable.is_untyped_bitmap -%} - {{target}} = static_cast>(chip::JniReferences::GetInstance().{{encodable.boxed_java_type}}ToPrimitive({{source}})); - {%- elif encodable.is_bitmap -%} - {{target}}.SetRaw(static_cast::IntegerType>(chip::JniReferences::GetInstance().{{encodable.boxed_java_type}}ToPrimitive({{source}}))); - {% else -%} - {{target}} = static_cast>(chip::JniReferences::GetInstance().{{encodable.boxed_java_type}}ToPrimitive({{source}})); - {% endif -%} -{% endmacro -%} - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, {{cluster.name | capitalcase}}Cluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -{% for command in cluster.commands -%} - -JNI_METHOD(void, {{cluster.name | capitalcase}}Cluster, - {{command.name | lowercaseFirst}})(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, - {%- if command.input_param -%} - {%- for field in (cluster.structs | named(command.input_param)).fields -%} - {{ field | toBoxedJavaType }} {{field.name}}, - {%- endfor -%} - {%- endif -%} - jobject timedInvokeTimeoutMs) -{ - chip::DeviceLayer::StackLock lock; - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster; - - ListFreer listFreer; - chip::app::Clusters::{{cluster.name | capitalcase}}::Commands::{{command.name | capitalcase}}::Type request; - - std::vector> cleanupByteArrays; - std::vector> cleanupStrings; - {%- if command.input_param -%} - {%- for field in (cluster.structs | named(command.input_param)).fields -%} - {{ encode_value( - "request." + (field.name | lowercaseFirst), - (field.name | lowercaseFirst), - 0, - field | asEncodable(typeLookup) - )}} - {%- endfor -%} - {% endif %} - - {% set callbackName = command | commandCallbackName(cluster) %} - std::unique_ptr onSuccess( - Platform::New(callback), Platform::Delete); - std::unique_ptr onFailure(Platform::New(callback), Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native callback", CHIP_ERROR_NO_MEMORY)); - VerifyOrReturn(onFailure.get() != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native callback", CHIP_ERROR_NO_MEMORY)); - - cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error getting native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - {% if command.is_timed_invoke -%} - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall, chip::JniReferences::GetInstance().IntegerToPrimitive(timedInvokeTimeoutMs)); - {%- else -%} - if (timedInvokeTimeoutMs == nullptr) { - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall); - } else { - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall, chip::JniReferences::GetInstance().IntegerToPrimitive(timedInvokeTimeoutMs)); - } - {%- endif %} - VerifyOrReturn(err == CHIP_NO_ERROR, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error invoking command", CHIP_ERROR_INCORRECT_STATE)); - - onSuccess.release(); - onFailure.release(); -} -{% endfor %} - -{%- for attr in cluster.attributes if attr.is_subscribable -%} -{%- if attr | canGenerateSubscribe(typeLookup) -%} - -JNI_METHOD(void, {{cluster.name}}Cluster, subscribe{{attr.definition.name | capitalcase}}Attribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock; - - {%- set callbackName = attr | callbackName(typeLookup) -%} - - std::unique_ptr<{{callbackName}}, void (*)({{callbackName}} *)> onSuccess(Platform::New<{{callbackName}}>(callback, true), chip::Platform::Delete<{{callbackName}}>); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::{{cluster.name}}::Attributes::{{attr.definition.name | capitalcase}}::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), {{callbackName}}::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - -{%- endif -%} -{% endfor %} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja deleted file mode 100644 index f5e4c228419ebd..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja +++ /dev/null @@ -1,54 +0,0 @@ -{# Copyright (c) 2022 Project CHIP Authors - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - #} -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -{%- for attr in cluster.attributes | attributesWithCallback(typeLookup) %} -JNI_METHOD(void, {{cluster.name | capitalcase}}Cluster, read{{attr.definition.name | capitalcase}}Attribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback{% if attr | isFabricScopedList(typeLookup) %}, jboolean isFabricFiltered{% endif %}) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::{{cluster.name | capitalcase}}::Attributes::{{attr.definition.name | capitalcase}}::TypeInfo; - {%- set callbackName = attr | callbackName(typeLookup) %} - std::unique_ptr<{{callbackName}}, void (*)({{callbackName}} *)> onSuccess(chip::Platform::New<{{callbackName}}>(callback, false), chip::Platform::Delete<{{callbackName}}>); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall{% if attr | isFabricScopedList(typeLookup) %}, isFabricFiltered{% endif %}); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - -{% endfor %} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ChipEventStructs.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ChipEventStructs.jinja deleted file mode 100644 index 4ce1f2f19d5861..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ChipEventStructs.jinja +++ /dev/null @@ -1,153 +0,0 @@ -{%- macro encode_value(source, encodable, depth) -%} - {%- if encodable.is_nullable -%} - {{encode_value(source, encodable.without_nullable(), depth + 1)}}? - {%- elif encodable.is_optional -%} - Optional<{{encode_value(source, encodable.without_optional(), depth + 1)}}> - {%- elif encodable.is_list -%} - List<{{encode_value(source, encodable.without_list(), depth + 1)}}> - {%- elif encodable.is_struct -%} - {%- set struct = encodable.get_underlying_struct() -%} - chip.devicecontroller.cluster.structs.{{source.name}}Cluster{{struct.name}} - {%- else -%} - {{encodable.kotlin_type}} - {%- endif -%} -{%- endmacro -%} - -{%- macro encode_tlv(encodable, tag, name, depth) %} - {%- if encodable.is_nullable -%} - if ({{name}} != null) { - {{encode_tlv(encodable.without_nullable(), tag, name, depth + 1)}} - } else { - putNull({{tag}}) - } - {%- elif encodable.is_optional -%} - if ({{name}}.isPresent) { - val opt{{name}} = {{name}}.get() - {{encode_tlv(encodable.without_optional(), tag, "opt" + name, depth + 1)}} - } - {%- elif encodable.is_list -%} - startList({{tag}}) - for (item in {{name}}.iterator()) { - {{encode_tlv(encodable.without_list(), "AnonymousTag", "item", depth + 1)}} - } - endList() - {%- elif encodable.is_struct -%} - {{name}}.toTlv({{tag}}, this) - {%- else -%} - put({{tag}}, {{name}}) - {%- endif -%} -{%- endmacro -%} - -{%- macro decode_tlv(source, encodable, tag, depth) %} - {%- if encodable.is_nullable -%} - if (!tlvReader.isNull()) { - {{decode_tlv(source, encodable.without_nullable(), tag, depth + 1)}} - } else { - tlvReader.getNull({{tag}}) - null - } - {%- elif encodable.is_optional -%} - if (tlvReader.isNextTag({{tag}})) { - Optional.of({{decode_tlv(source, encodable.without_optional(), tag, depth + 1)}}) - } else { - Optional.empty() - } - {%- elif encodable.is_list -%} - {%- set encodablewithoutlist = encodable.without_list() -%} - buildList <{{encode_value(source, encodablewithoutlist, depth + 1)}}> { - tlvReader.enterList({{tag}}) - while(!tlvReader.isEndOfContainer()) { - this.add({{decode_tlv(source, encodablewithoutlist, "AnonymousTag", depth + 1)}}) - } - tlvReader.exitContainer() - } - {%- elif encodable.is_struct -%} - {%- set struct = encodable.get_underlying_struct() -%} - chip.devicecontroller.cluster.structs.{{source.name}}Cluster{{struct.name}}.fromTlv({{tag}}, tlvReader) - {%- else -%} - tlvReader.get{{encodable.kotlin_type}}({{tag}}) - {%- endif -%} -{%- endmacro -%} - -{%- macro contextSpecificTag(field) -%} - ContextSpecificTag(TAG_{{field.name | constcase}}) -{%- endmacro -%} - -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller.cluster.eventstructs - -import chip.devicecontroller.cluster.* -import chip.tlv.AnonymousTag -import chip.tlv.ContextSpecificTag -import chip.tlv.Tag -import chip.tlv.TlvParsingException -import chip.tlv.TlvReader -import chip.tlv.TlvWriter - -import java.util.Optional - -class {{cluster.name}}Cluster{{event.name}}Event ( - {%- for field in event.fields -%} - {%- set encodable = field | asEncodable(typeLookup) %} - val {{field.name}}: {{encode_value(cluster, encodable, 0)}} - {%- if loop.index0 < loop.length - 1 -%}{{","}}{%- endif -%} - {%- endfor -%}) { - override fun toString(): String = buildString { - append("{{cluster.name}}Cluster{{event.name}}Event {\n") - {%- for field in event.fields %} - append("\t{{field.name}} : ${{field.name}}\n") - {%- endfor %} - append("}\n") - } - - fun toTlv(tag: Tag, tlvWriter: TlvWriter) { - tlvWriter.apply { - startStructure(tag) - {% for field in event.fields %} - {%- set encodable = field | asEncodable(typeLookup) %} - {%- set tag = contextSpecificTag(field) -%} - {{encode_tlv(encodable, tag, field.name, 0)}} - {% endfor -%} - endStructure() - } - } - - companion object { - {%- for field in event.fields %} - private const val TAG_{{field.name | constcase}} = {{field.code}} - {%- endfor %} - - fun fromTlv(tag: Tag, tlvReader: TlvReader) : {{cluster.name}}Cluster{{event.name}}Event { - tlvReader.enterStructure(tag) - {% for field in event.fields %} - {%- set decodable = field | asEncodable(typeLookup) %} - {%- set tag = contextSpecificTag(field) -%} - val {{field.name}} = {{decode_tlv(cluster, decodable, tag, 0)}} - {% endfor %} - tlvReader.exitContainer() - - return {{cluster.name}}Cluster{{event.name}}Event( - {%- for field in event.fields -%} - {%- set encodable = field | asEncodable(typeLookup) -%} - {{field.name}} - {%- if loop.index0 < loop.length - 1 -%}{{", "}}{%- endif -%} - {%- endfor -%} - ) - } - } -} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ChipStructs.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ChipStructs.jinja deleted file mode 100644 index 7463e6f26c7a2c..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ChipStructs.jinja +++ /dev/null @@ -1,153 +0,0 @@ -{%- macro encode_value(source, encodable, depth) -%} - {%- if encodable.is_nullable -%} - {{encode_value(source, encodable.without_nullable(), depth + 1)}}? - {%- elif encodable.is_optional -%} - Optional<{{encode_value(source, encodable.without_optional(), depth + 1)}}> - {%- elif encodable.is_list -%} - List<{{encode_value(source, encodable.without_list(), depth + 1)}}> - {%- elif encodable.is_struct -%} - {%- set struct = encodable.get_underlying_struct() -%} - {{source.name}}Cluster{{struct.name}} - {%- else -%} - {{encodable.kotlin_type}} - {%- endif -%} -{%- endmacro -%} - -{%- macro encode_tlv(encodable, tag, name, depth) %} - {%- if encodable.is_nullable -%} - if ({{name}} != null) { - {{encode_tlv(encodable.without_nullable(), tag, name, depth + 1)}} - } else { - putNull({{tag}}) - } - {%- elif encodable.is_optional -%} - if ({{name}}.isPresent) { - val opt{{name}} = {{name}}.get() - {{encode_tlv(encodable.without_optional(), tag, "opt" + name, depth + 1)}} - } - {%- elif encodable.is_list -%} - startList({{tag}}) - for (item in {{name}}.iterator()) { - {{encode_tlv(encodable.without_list(), "AnonymousTag", "item", depth + 1)}} - } - endList() - {%- elif encodable.is_struct -%} - {{name}}.toTlv({{tag}}, this) - {%- else -%} - put({{tag}}, {{name}}) - {%- endif -%} -{%- endmacro -%} - -{%- macro decode_tlv(source, encodable, tag, depth) %} - {%- if encodable.is_nullable -%} - if (!tlvReader.isNull()) { - {{decode_tlv(source, encodable.without_nullable(), tag, depth + 1)}} - } else { - tlvReader.getNull({{tag}}) - null - } - {%- elif encodable.is_optional -%} - if (tlvReader.isNextTag({{tag}})) { - Optional.of({{decode_tlv(source, encodable.without_optional(), tag, depth + 1)}}) - } else { - Optional.empty() - } - {%- elif encodable.is_list -%} - {%- set encodablewithoutlist = encodable.without_list() -%} - buildList<{{encode_value(source, encodablewithoutlist, depth + 1)}}> { - tlvReader.enterList({{tag}}) - while(!tlvReader.isEndOfContainer()) { - add({{decode_tlv(source, encodablewithoutlist, "AnonymousTag", depth + 1)}}) - } - tlvReader.exitContainer() - } - {%- elif encodable.is_struct -%} - {%- set struct = encodable.get_underlying_struct() -%} - {{source.name}}Cluster{{struct.name}}.fromTlv({{tag}}, tlvReader) - {%- else -%} - tlvReader.get{{encodable.kotlin_type}}({{tag}}) - {%- endif -%} -{%- endmacro -%} - -{%- macro contextSpecificTag(field) -%} - ContextSpecificTag(TAG_{{field.name | constcase}}) -{%- endmacro -%} - -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller.cluster.structs - -import chip.devicecontroller.cluster.* -import chip.tlv.AnonymousTag -import chip.tlv.ContextSpecificTag -import chip.tlv.Tag -import chip.tlv.TlvParsingException -import chip.tlv.TlvReader -import chip.tlv.TlvWriter - -import java.util.Optional - -class {{cluster.name}}Cluster{{struct.name}} ( - {%- for field in struct.fields %} - {%- set encodable = field | asEncodable(typeLookup) %} - val {{field.name}}: {{encode_value(cluster, encodable, 0)}} - {%- if loop.index0 < loop.length - 1 -%}{{","}}{%- endif -%} - {%- endfor -%}) { - override fun toString(): String = buildString { - append("{{cluster.name}}Cluster{{struct.name}} {\n") - {%- for field in struct.fields %} - append("\t{{field.name}} : ${{field.name}}\n") - {%- endfor %} - append("}\n") - } - - fun toTlv(tag: Tag, tlvWriter: TlvWriter) { - tlvWriter.apply { - startStructure(tag) - {% for field in struct.fields %} - {%- set encodable = field | asEncodable(typeLookup) %} - {%- set tag = contextSpecificTag(field) -%} - {{encode_tlv(encodable, tag, field.name, 0)}} - {% endfor -%} - endStructure() - } - } - - companion object { - {%- for field in struct.fields %} - private const val TAG_{{field.name | constcase}} = {{field.code}} - {%- endfor %} - - fun fromTlv(tag: Tag, tlvReader: TlvReader) : {{cluster.name}}Cluster{{struct.name}} { - tlvReader.enterStructure(tag) - {% for field in struct.fields %} - {%- set decodable = field | asEncodable(typeLookup) %} - {%- set tag = contextSpecificTag(field) -%} - val {{field.name}} = {{decode_tlv(cluster, decodable, tag, 0)}} - {% endfor %} - tlvReader.exitContainer() - - return {{cluster.name}}Cluster{{struct.name}}( - {%- for field in struct.fields -%} - {%- set encodable = field | asEncodable(typeLookup) -%} - {{field.name}} - {%- if loop.index0 < loop.length - 1 -%}{{", "}}{%- endif -%} - {%- endfor -%} - ) - } - } -} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ClusterIDMapping.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ClusterIDMapping.jinja deleted file mode 100644 index 03e055730c075e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ClusterIDMapping.jinja +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller; - -public class ClusterIDMapping { - public interface BaseCluster { - long getID(); - String getAttributeName(long id) throws NoSuchFieldError; - String getEventName(long id) throws NoSuchFieldError; - String getCommandName(long id) throws NoSuchFieldError; - long getAttributeID(String name) throws IllegalArgumentException; - long getEventID(String name) throws IllegalArgumentException; - long getCommandID(String name) throws IllegalArgumentException; - } - - public static BaseCluster getCluster(long clusterId) { - {%- for cluster in clientClusters | sort(attribute='code') %} - if (clusterId == {{cluster.name}}.ID) { - return new {{cluster.name}}(); - } - {%- endfor -%} - return null; - } - - {%- for cluster in clientClusters | sort(attribute='code') %} - public static class {{cluster.name}} implements BaseCluster { - public static final long ID = {{cluster.code}}L; - public long getID() { - return ID; - } - - public enum Attribute { - {%- for attribute in cluster.attributes | sort(attribute='code') %} - {{attribute.definition.name | upfirst}}({{attribute.definition.code}}L), - {%- endfor -%} - ; - private final long id; - Attribute(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Attribute value(long id) throws NoSuchFieldError { - for (Attribute attribute : Attribute.values()) { - if (attribute.getID() == id) { - return attribute; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Event { - {%- for event in cluster.events | sort(attribute='code') %} - {{event.name | upfirst}}({{event.code}}L), - {%- endfor -%} - ; - private final long id; - Event(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Event value(long id) throws NoSuchFieldError { - for (Event event : Event.values()) { - if (event.getID() == id) { - return event; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Command { - {%- for command in cluster.commands | sort(attribute='code') %} - {{command.name | upfirst}}({{command.code}}L), - {%- endfor -%} - ; - private final long id; - Command(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Command value(long id) throws NoSuchFieldError { - for (Command command : Command.values()) { - if (command.getID() == id) { - return command; - } - } - throw new NoSuchFieldError(); - } - } - - {%- for command in cluster.commands | sort(attribute='code') %} - {%- if command.input_param -%} - public enum {{command.name | upfirst}}CommandField { - {%- for field in (cluster.structs | named(command.input_param)).fields -%} {{field.name | upfirst}}({{field.code}}), {%- endfor -%}; - private final int id; - {{command.name | upfirst}}CommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static {{command.name | upfirst}}CommandField value(int id) throws NoSuchFieldError { - for ({{command.name | upfirst}}CommandField field : {{command.name | upfirst}}CommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - } - {%- endif -%} - {%- endfor -%} - - @Override - public String getAttributeName(long id) throws NoSuchFieldError { - return Attribute.value(id).toString(); - } - - @Override - public String getEventName(long id) throws NoSuchFieldError { - return Event.value(id).toString(); - } - - @Override - public String getCommandName(long id) throws NoSuchFieldError { - return Command.value(id).toString(); - } - - @Override - public long getAttributeID(String name) throws IllegalArgumentException { - return Attribute.valueOf(name).getID(); - } - - @Override - public long getEventID(String name) throws IllegalArgumentException { - return Event.valueOf(name).getID(); - } - - @Override - public long getCommandID(String name) throws IllegalArgumentException { - return Command.valueOf(name).getID(); - } - } - {%- endfor -%} -} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ClusterReadMapping.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ClusterReadMapping.jinja deleted file mode 100644 index 05bab57d3c88fc..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ClusterReadMapping.jinja +++ /dev/null @@ -1,59 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller; - -import chip.clusterinfo.CommandParameterInfo; -import chip.clusterinfo.InteractionInfo; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -public class ClusterReadMapping { - -{% for cluster in clientClusters | sort(attribute='code') %} - {%- set typeLookup = idl | createLookupContext(cluster) %} - private static Map read{{cluster.name}}InteractionInfo() { - Map result = new LinkedHashMap<>(); - {%- for attribute in cluster.attributes | sort(attribute='name') | attributesWithCallback(typeLookup) %} - {#- TODO: add support for struct-typed attributes -#} - Map read{{cluster.name}}{{attribute.definition.name | upfirst}}CommandParams = new LinkedHashMap(); - InteractionInfo read{{cluster.name}}{{attribute.definition.name | upfirst}}AttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.{{cluster.name}}Cluster) cluster).read{{attribute.definition.name | upfirst}}Attribute( - ({{ attribute | chipClustersCallbackName(typeLookup) }}) callback - ); - }, - () -> new ClusterInfoMapping.{{ attribute | delegatedCallbackName(typeLookup)}}(), - read{{cluster.name}}{{attribute.definition.name | upfirst}}CommandParams - ); - result.put("read{{attribute.definition.name | upfirst}}Attribute", read{{cluster.name}}{{attribute.definition.name | upfirst}}AttributeInteractionInfo); - {% endfor %} - return result; - } - -{%- endfor %} - @SuppressWarnings("serial") - public Map> getReadAttributeMap() { - - return new HashMap>(){% raw %}{{{% endraw %} - {%- for cluster in clientClusters | sort(attribute='code') %} - put("{{cluster.name | lowfirst_except_acronym}}", read{{cluster.name}}InteractionInfo()); - {%- endfor -%} - }}; - } -} - diff --git a/scripts/py_matter_idl/matter_idl/generators/java/ClusterWriteMapping.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ClusterWriteMapping.jinja deleted file mode 100644 index 836267e835d965..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/ClusterWriteMapping.jinja +++ /dev/null @@ -1,67 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller; - -import chip.clusterinfo.CommandParameterInfo; -import chip.clusterinfo.InteractionInfo; -import chip.devicecontroller.ChipClusters.DefaultClusterCallback; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -public class ClusterWriteMapping { - public Map> getWriteAttributeMap() { - Map> writeAttributeMap = new HashMap<>(); - - {%- for cluster in clientClusters | sort(attribute='code') %} - {%- set typeLookup = idl | createLookupContext(cluster) %} - Map write{{cluster.name}}InteractionInfo = new LinkedHashMap<>(); - {%- for attribute in cluster.attributes | sort(attribute='name') | attributesWithCallback(typeLookup) %} - {#- TODO: add support for struct-typed attributes -#} - {% if not attribute.definition.is_list and attribute.is_writable %} - Map write{{cluster.name}}{{attribute.definition.name | upfirst}}CommandParams = new LinkedHashMap(); - {%- set encodable = attribute.definition | asEncodable(typeLookup) %} - CommandParameterInfo {{cluster.name | lowfirst_except_acronym}}{{attribute.definition.name | lowfirst_except_acronym}}CommandParameterInfo = - new CommandParameterInfo( - "value", - {{ encodable.boxed_java_type }}.class, {# {{asJavaType type null parent.parent.name removeGenericType=true}}.class, #} - {{ encodable.boxed_java_type }}.class {# {{asJavaType type null parent.parent.name underlyingType=true}}.class #} - ); - write{{cluster.name}}{{attribute.definition.name | upfirst}}CommandParams.put( - "value", - {{cluster.name | lowfirst_except_acronym}}{{attribute.definition.name | lowfirst_except_acronym}}CommandParameterInfo - ); - InteractionInfo write{{cluster.name}}{{attribute.definition.name | upfirst}}AttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.{{cluster.name}}Cluster) cluster).write{{attribute.definition.name | upfirst}}Attribute( - (DefaultClusterCallback) callback, - ({{ encodable.boxed_java_type }}) commandArguments.get("value") - {%- if attribute.requires_timed_write -%}, 10000 {% endif %} - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - write{{cluster.name}}{{attribute.definition.name | upfirst}}CommandParams - ); - write{{cluster.name}}InteractionInfo.put("write{{attribute.definition.name | upfirst}}Attribute", write{{cluster.name}}{{attribute.definition.name | upfirst}}AttributeInteractionInfo); - {%- endif %} - {%- endfor %} - writeAttributeMap.put("{{cluster.name | lowfirst_except_acronym}}", write{{cluster.name}}InteractionInfo); - {%- endfor -%} - - return writeAttributeMap; - } -} diff --git a/scripts/py_matter_idl/matter_idl/generators/java/__init__.py b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py deleted file mode 100644 index 5abc912ebabd34..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/java/__init__.py +++ /dev/null @@ -1,831 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import dataclasses -import enum -import logging -import os -from typing import List, Optional, Set - -from matter_idl.generators import CodeGenerator, GeneratorStorage -from matter_idl.generators.types import (BasicInteger, BasicString, FundamentalType, IdlBitmapType, IdlEnumType, IdlType, - ParseDataType, TypeLookupContext) -from matter_idl.matter_idl_types import (Attribute, Cluster, ClusterSide, Command, DataType, Field, FieldQuality, Idl, Struct, - StructQuality, StructTag) -from stringcase import capitalcase - - -@dataclasses.dataclass -class GenerateTarget: - template: str - output_name: str - - -@dataclasses.dataclass -class GlobalType: - name: str # java name - cpp_type: str # underlying type - idl_type: str # assumed IDL type - - -# types that java should see globally -_GLOBAL_TYPES = [ - GlobalType("Boolean", "bool", "boolean"), - GlobalType("CharString", "const chip::CharSpan", "char_string"), - GlobalType("Double", "double", "double"), - GlobalType("Float", "float", "single"), - GlobalType("Int8s", "int8_t", "int8s"), - GlobalType("Int8u", "uint8_t", "int8u"), - GlobalType("Int16s", "int16_t", "int16s"), - GlobalType("Int16u", "uint16_t", "int16u"), - GlobalType("Int32s", "int32_t", "int32s"), - GlobalType("Int32u", "uint32_t", "int32u"), - GlobalType("Int64s", "int64_t", "int64s"), - GlobalType("Int64u", "uint64_t", "int64u"), - GlobalType("OctetString", "const chip::ByteSpan", "octet_string"), -] - - -def _UnderlyingType(field: Field, context: TypeLookupContext) -> Optional[str]: - actual = ParseDataType(field.data_type, context) - if isinstance(actual, (IdlEnumType, IdlBitmapType)): - actual = actual.base_type - - if isinstance(actual, BasicString): - if actual.is_binary: - return 'OctetString' - else: - return 'CharString' - elif isinstance(actual, BasicInteger): - if actual.is_signed: - return "Int{}s".format(actual.power_of_two_bits) - else: - return "Int{}u".format(actual.power_of_two_bits) - elif isinstance(actual, FundamentalType): - if actual == FundamentalType.BOOL: - return 'Boolean' - elif actual == FundamentalType.FLOAT: - return 'Float' - elif actual == FundamentalType.DOUBLE: - return 'Double' - else: - logging.warn('Unknown fundamental type: %r' % actual) - - return None - - -def FieldToGlobalName(field: Field, context: TypeLookupContext) -> Optional[str]: - """Global names are used for generic callbacks shared across - all clusters (e.g. for bool/float/uint32 and similar) - """ - if field.is_list: - return None # lists are always specific per cluster - - if FieldQuality.NULLABLE & field.qualities: - return None - - return _UnderlyingType(field, context) - - -# Based on atomicType in ZAP: -# src-electron/generator/matter/app/zap-templates/common/override.js -_KNOWN_DECODABLE_TYPES = { - 'action_id': 'chip::ActionId', - 'attrib_id': 'chip::AttributeId', - 'cluster_id': 'chip::ClusterId', - 'command_id': 'chip::CommandId', - 'data_ver': 'chip::DataVersion', - 'devtype_id': 'chip::DeviceTypeId', - 'endpoint_no': 'chip::EndpointId', - 'eui64': 'chip::NodeId', - 'event_id': 'chip::EventId', - 'event_no': 'chip::EventNumber', - 'fabric_id': 'chip::FabricId', - 'fabric_idx': 'chip::FabricIndex', - 'fabric_idx': 'chip::FabricIndex', - 'field_id': 'chip::FieldId', - 'group_id': 'chip::GroupId', - 'node_id': 'chip::NodeId', - 'percent': 'chip::Percent', - 'percent100ths': 'chip::Percent100ths', - 'transaction_id': 'chip::TransactionId', - 'vendor_id': 'chip::VendorId', - - # non-named enums - 'enum8': 'uint8_t', - 'enum16': 'uint16_t', - 'enum32': 'uint32_t', - 'enum64': 'uint64_t', -} - - -def _CppType(field: Field, context: TypeLookupContext) -> str: - if field.data_type.name.lower() in _KNOWN_DECODABLE_TYPES: - return _KNOWN_DECODABLE_TYPES[field.data_type.name.lower()] - - actual = ParseDataType(field.data_type, context) - if isinstance(actual, BasicString): - if actual.is_binary: - return 'chip::ByteSpan' - else: - return 'chip::CharSpan' - elif isinstance(actual, BasicInteger): - if actual.is_signed: - return "int{}_t".format(actual.power_of_two_bits) - else: - return "uint{}_t".format(actual.power_of_two_bits) - elif isinstance(actual, FundamentalType): - if actual == FundamentalType.BOOL: - return 'bool' - elif actual == FundamentalType.FLOAT: - return 'float' - elif actual == FundamentalType.DOUBLE: - return 'double' - else: - logging.warn('Unknown fundamental type: %r' % actual) - elif isinstance(actual, IdlType): - return f"chip::app::Clusters::{context.cluster.name}::Structs::{field.data_type.name}::DecodableType" - elif isinstance(actual, IdlBitmapType): - return f"chip::BitMask" - - # Handles IdlEnumType - return f"chip::app::Clusters::{context.cluster.name}::{field.data_type.name}" - - -def DecodableJniType(field: Field, context: TypeLookupContext) -> str: - actual = _CppType(field, context) - - needsConstRef = False - if field.is_list: - needsConstRef = True - actual = f"chip::app::DataModel::DecodableList<{actual}>" - - if field.is_nullable: - needsConstRef = True - actual = f"chip::app::DataModel::Nullable<{actual}>" - - if needsConstRef: - actual = f"const {actual} &" - - return actual - - -def GlobalNameToJavaName(name: str) -> str: - if name in {'Int8u', 'Int8s', 'Int16u', 'Int16s'}: - return 'Integer' - - if name.startswith('Int'): - return 'Long' - - # Double/Float/Booleans/CharString/OctetString - return name - - -def DelegatedCallbackName(attr: Attribute, context: TypeLookupContext) -> str: - """ - Figure out what callback name to use for delegate callback construction. - """ - global_name = FieldToGlobalName(attr.definition, context) - - if global_name: - return 'Delegated{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - - return 'Delegated{}Cluster{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) - - -def ChipClustersCallbackName(attr: Attribute, context: TypeLookupContext) -> str: - """ - Figure out what callback name to use when building a ChipCluster.*AttributeCallback - in java codegen. - """ - global_name = FieldToGlobalName(attr.definition, context) - - if global_name: - return 'ChipClusters.{}AttributeCallback'.format(GlobalNameToJavaName(global_name)) - - return 'ChipClusters.{}Cluster.{}AttributeCallback'.format(context.cluster.name, capitalcase(attr.definition.name)) - - -def CallbackName(attr: Attribute, context: TypeLookupContext) -> str: - """ - Figure out what callback name to use when a variable requires a read callback. - - These are split into native types, like Boolean/Float/Double/CharString, where - one callback type can support anything. - - For specific types (e.g. A struct) codegen will generate its own callback name - specific to that type. - """ - global_name = FieldToGlobalName(attr.definition, context) - - if global_name: - return 'CHIP{}AttributeCallback'.format(capitalcase(global_name)) - - return 'CHIP{}{}AttributeCallback'.format( - capitalcase(context.cluster.name), - capitalcase(attr.definition.name) - ) - - -def CommandCallbackName(command: Command, cluster: Cluster): - if command.output_param.lower() == 'defaultsuccess': - return 'DefaultSuccess' - return '{}Cluster{}'.format(cluster.name, command.output_param) - - -def attributesWithSupportedCallback(attrs, context: TypeLookupContext): - for attr in attrs: - # Attributes will be generated for all types - # except non-list structures - if not attr.definition.is_list: - underlying = ParseDataType(attr.definition.data_type, context) - if isinstance(underlying, IdlType): - continue - - yield attr - - -def _IsUsingGlobalCallback(field: Field, context: TypeLookupContext): - """Test to determine if the data type of a field can use one of - the global callbacks (i.e. it is a basic double/integer/bool etc.) - """ - if field.is_list: - return False - - if field.is_nullable: - return False - - return field.data_type.name in { - "boolean", - "single", - "double", - "int8s", - "int8u", - "int16s", - "int16u", - "int24s", - "int24u", - "int32s", - "int32u", - "int40s", - "int40u", - "int48s", - "int48u", - "int56s", - "int56u", - "int64s", - "int64u", - "enum8", - "enum16", - "enum32", - "enum64", - "bitmap8", - "bitmap16", - "bitmap32", - "bitmap64", - "char_string", - "long_char_string", - "octet_string", - "long_octet_string", - } - - -def NamedFilter(choices: List, name: str): - for choice in choices: - if choice.name == name: - return choice - raise Exception("No item named %s in %r" % (name, choices)) - - -def ToBoxedJavaType(field: Field): - if field.is_optional: - return 'jobject' - elif field.data_type.name.lower() in ['octet_string', 'long_octet_string']: - return 'jbyteArray' - elif field.data_type.name.lower() in ['char_string', 'long_char_string']: - return 'jstring' - else: - return 'jobject' - - -def LowercaseFirst(name: str) -> str: - """ - Change the first letter of a string to lowercase as long as the 2nd - letter is not uppercase. - - Can be used for variable naming, eg insider structures, codegen will - call things "Foo foo" (notice variable name is lowercase). - """ - if len(name) > 1 and name[1].lower() != name[1]: - # Odd workaround: PAKEVerifier should not become pAKEVerifier - return name - return name[0].lower() + name[1:] - - -class EncodableValueAttr(enum.Enum): - LIST = enum.auto() - NULLABLE = enum.auto() - OPTIONAL = enum.auto() - - -class EncodableValue: - """ - Contains helpers for encoding values, specifically lookups - for optionality, lists and recursive data type lookups within - the IDL and cluster - - Intended use is to be able to: - - derive types (see clone and without_* methods) such that codegen - can implement things like 'if x != null { treat non-null x}' - - Java specific conversions: get boxed types and JNI string signautes - for the underlying types. - """ - - def __init__(self, context: TypeLookupContext, data_type: DataType, attrs: Set[EncodableValueAttr]): - self.context = context - self.data_type = data_type - self.attrs = attrs - - @property - def is_nullable(self): - return EncodableValueAttr.NULLABLE in self.attrs - - @property - def is_optional(self): - return EncodableValueAttr.OPTIONAL in self.attrs - - @property - def is_list(self): - return EncodableValueAttr.LIST in self.attrs - - @property - def is_octet_string(self): - return self.data_type.name.lower() in ['octet_string', 'long_octet_string'] - - @property - def is_char_string(self): - return self.data_type.name.lower() in ['char_string', 'long_char_string'] - - @property - def is_struct(self): - return self.context.is_struct_type(self.data_type.name) - - @property - def is_enum(self): - return self.context.is_enum_type(self.data_type.name) - - @property - def is_bitmap(self): - return self.context.is_bitmap_type(self.data_type.name) - - @property - def is_untyped_bitmap(self): - return self.context.is_untyped_bitmap_type(self.data_type.name) - - def clone(self): - return EncodableValue(self.context, self.data_type, self.attrs) - - def without_nullable(self): - result = self.clone() - result.attrs.remove(EncodableValueAttr.NULLABLE) - return result - - def without_optional(self): - result = self.clone() - result.attrs.remove(EncodableValueAttr.OPTIONAL) - return result - - def without_list(self): - result = self.clone() - result.attrs.remove(EncodableValueAttr.LIST) - return result - - def get_underlying_struct(self): - s = self.context.find_struct(self.data_type.name) - if not s: - raise Exception("Struct %s not found" % self.data_type.name) - return s - - def get_underlying_enum(self): - e = self.context.find_enum(self.data_type.name) - if not e: - raise Exception("Enum %s not found" % self.data_type.name) - return e - - @property - def jni_fundamental_type(self): - java_type = self.boxed_java_type - - if java_type == 'Boolean': - return 'jboolean' - elif java_type == 'Float': - return 'jfloat' - elif java_type == 'Double': - return 'jdouble' - elif java_type == 'Long': - return 'jlong' - elif java_type == 'Integer': - return 'jint' - - raise Exception("Unknown jni fundamental type.") - - @property - def boxed_java_type(self): - t = ParseDataType(self.data_type, self.context) - - if isinstance(t, FundamentalType): - if t == FundamentalType.BOOL: - return "Boolean" - elif t == FundamentalType.FLOAT: - return "Float" - elif t == FundamentalType.DOUBLE: - return "Double" - else: - raise Exception("Unknown fundamental type") - elif isinstance(t, BasicInteger): - # the >= 3 will include int24_t to be considered "long" - if t.byte_count >= 3: - return "Long" - else: - return "Integer" - elif isinstance(t, BasicString): - if t.is_binary: - return "byte[]" - else: - return "String" - elif isinstance(t, IdlEnumType): - if t.base_type.byte_count >= 3: - return "Long" - else: - return "Integer" - elif isinstance(t, IdlBitmapType): - if t.base_type.byte_count >= 3: - return "Long" - else: - return "Integer" - else: - return "Object" - - @property - def kotlin_type(self): - t = ParseDataType(self.data_type, self.context) - - if isinstance(t, FundamentalType): - if t == FundamentalType.BOOL: - return "Boolean" - elif t == FundamentalType.FLOAT: - return "Float" - elif t == FundamentalType.DOUBLE: - return "Double" - else: - raise Exception("Unknown fundamental type") - elif isinstance(t, BasicInteger): - # the >= 3 will include int24_t to be considered "long" - if t.byte_count >= 3: - return "Long" - else: - return "Int" - elif isinstance(t, BasicString): - if t.is_binary: - return "ByteArray" - else: - return "String" - elif isinstance(t, IdlEnumType): - if t.base_type.byte_count >= 3: - return "Long" - else: - return "Int" - elif isinstance(t, IdlBitmapType): - if t.base_type.byte_count >= 3: - return "Long" - else: - return "Int" - else: - return "Any" - - @property - def unboxed_java_signature(self): - if self.is_optional or self.is_list: - raise Exception("Not a basic type: %r" % self) - - t = ParseDataType(self.data_type, self.context) - - if isinstance(t, FundamentalType): - if t == FundamentalType.BOOL: - return "Z" - elif t == FundamentalType.FLOAT: - return "F" - elif t == FundamentalType.DOUBLE: - return "D" - else: - raise Exception("Unknown fundamental type") - elif isinstance(t, BasicInteger): - if t.byte_count >= 3: - return "J" - else: - return "I" - else: - raise Exception("Not a basic type: %r" % self) - - @property - def boxed_java_signature(self): - # Optional takes precedence over list - Optional compiles down to just java.util.Optional. - if self.is_optional: - return "Ljava/util/Optional;" - - if self.is_list: - return "Ljava/util/ArrayList;" - - t = ParseDataType(self.data_type, self.context) - - if isinstance(t, FundamentalType): - if t == FundamentalType.BOOL: - return "Ljava/lang/Boolean;" - elif t == FundamentalType.FLOAT: - return "Ljava/lang/Float;" - elif t == FundamentalType.DOUBLE: - return "Ljava/lang/Double;" - else: - raise Exception("Unknown fundamental type") - elif isinstance(t, BasicInteger): - if t.byte_count >= 3: - return "Ljava/lang/Long;" - else: - return "Ljava/lang/Integer;" - elif isinstance(t, BasicString): - if t.is_binary: - return "[B" - else: - return "Ljava/lang/String;" - elif isinstance(t, IdlEnumType): - if t.base_type.byte_count >= 3: - return "Ljava/lang/Long;" - else: - return "Ljava/lang/Integer;" - elif isinstance(t, IdlBitmapType): - if t.base_type.byte_count >= 3: - return "Ljava/lang/Long;" - else: - return "Ljava/lang/Integer;" - else: - return "Lchip/devicecontroller/ChipStructs${}Cluster{};".format(self.context.cluster.name, self.data_type.name) - - -def GlobalEncodableValueFrom(typeName: str, context: TypeLookupContext) -> EncodableValue: - """ - Filter to convert a global type name to an encodable value - """ - return EncodableValue(context, DataType(name=typeName), set()) - - -def EncodableValueFrom(field: Field, context: TypeLookupContext) -> EncodableValue: - """ - Filter to convert a standard field to an EncodableValue. - - This converts the AST information (field name/info + lookup context) into - a java-generator specific wrapper that can be manipulated and - queried for properties like java native name or JNI string signature. - """ - attrs = set() - - if field.is_optional: - attrs.add(EncodableValueAttr.OPTIONAL) - - if field.is_nullable: - attrs.add(EncodableValueAttr.NULLABLE) - - if field.is_list: - attrs.add(EncodableValueAttr.LIST) - - return EncodableValue(context, field.data_type, attrs) - - -def CreateLookupContext(idl: Idl, cluster: Optional[Cluster]) -> TypeLookupContext: - """ - A filter to mark a lookup context to be within a specific cluster. - - This is used to specify how structure/enum/other names are looked up. - Generally one looks up within the specific cluster then if cluster does - not contain a definition, we loop at global namespacing. - """ - return TypeLookupContext(idl, cluster) - - -def CanGenerateSubscribe(attr: Attribute, lookup: TypeLookupContext) -> bool: - """ - Filter that returns if an attribute can be subscribed to. - - Uses the given attribute and the lookupContext to figure out the attribute - type. - """ - # For backwards compatibility, we do not subscribe to structs - # (although list of structs is ok ...) - if attr.definition.is_list: - return True - - return not lookup.is_struct_type(attr.definition.data_type.name) - - -def IsFabricScopedList(attr: Attribute, lookup: TypeLookupContext) -> bool: - if not attr.definition.is_list: - return False - - struct = lookup.find_struct(attr.definition.data_type.name) - return struct and struct.qualities == StructQuality.FABRIC_SCOPED - - -def IsResponseStruct(s: Struct) -> bool: - return s.tag == StructTag.RESPONSE - - -class __JavaCodeGenerator(CodeGenerator): - """ - Code generation for java-specific files. - - Registers filters used by all java generators. - """ - - def __init__(self, storage: GeneratorStorage, idl: Idl, **kargs): - """ - Inintialization is specific for java generation and will add - filters as required by the java .jinja templates to function. - """ - super().__init__(storage, idl, fs_loader_searchpath=os.path.dirname(__file__)) - - self.jinja_env.filters['attributesWithCallback'] = attributesWithSupportedCallback - self.jinja_env.filters['callbackName'] = CallbackName - self.jinja_env.filters['chipClustersCallbackName'] = ChipClustersCallbackName - self.jinja_env.filters['delegatedCallbackName'] = DelegatedCallbackName - self.jinja_env.filters['commandCallbackName'] = CommandCallbackName - self.jinja_env.filters['named'] = NamedFilter - self.jinja_env.filters['toBoxedJavaType'] = ToBoxedJavaType - self.jinja_env.filters['lowercaseFirst'] = LowercaseFirst - self.jinja_env.filters['asEncodable'] = EncodableValueFrom - self.jinja_env.filters['globalAsEncodable'] = GlobalEncodableValueFrom - self.jinja_env.filters['createLookupContext'] = CreateLookupContext - self.jinja_env.filters['canGenerateSubscribe'] = CanGenerateSubscribe - self.jinja_env.filters['decodableJniType'] = DecodableJniType - self.jinja_env.filters['isFabricScopedList'] = IsFabricScopedList - - self.jinja_env.tests['is_response_struct'] = IsResponseStruct - self.jinja_env.tests['is_using_global_callback'] = _IsUsingGlobalCallback - - -class JavaJNIGenerator(__JavaCodeGenerator): - """Generates JNI java files (i.e. C++ source/headers).""" - - def __init__(self, *args, **kargs): - super().__init__(*args, **kargs) - - def internal_render_all(self): - """ - Renders .CPP files required for JNI support. - """ - - large_targets = [ - GenerateTarget(template="CHIPCallbackTypes.jinja", - output_name="jni/CHIPCallbackTypes.h"), - GenerateTarget(template="CHIPReadCallbacks_h.jinja", - output_name="jni/CHIPReadCallbacks.h"), - GenerateTarget(template="CHIPGlobalCallbacks_cpp.jinja", - output_name="jni/CHIPGlobalCallbacks.cpp"), - ] - - for target in large_targets: - self.internal_render_one_output( - template_path=target.template, - output_file_name=target.output_name, - vars={ - 'idl': self.idl, - 'clientClusters': [c for c in self.idl.clusters if c.side == ClusterSide.CLIENT], - 'globalTypes': _GLOBAL_TYPES, - } - ) - - cluster_targets = [ - GenerateTarget(template="ChipClustersRead.jinja", - output_name="jni/{cluster_name}Client-ReadImpl.cpp"), - GenerateTarget(template="ChipClustersCpp.jinja", - output_name="jni/{cluster_name}Client-InvokeSubscribeImpl.cpp"), - ] - - self.internal_render_one_output( - template_path="CHIPCallbackTypes.jinja", - output_file_name="jni/CHIPCallbackTypes.h", - vars={ - 'idl': self.idl, - 'clientClusters': [c for c in self.idl.clusters if c.side == ClusterSide.CLIENT], - } - ) - - # Every cluster has its own impl, to avoid - # very large compilations (running out of RAM) - for cluster in self.idl.clusters: - if cluster.side != ClusterSide.CLIENT: - continue - - for target in cluster_targets: - self.internal_render_one_output( - template_path=target.template, - output_file_name=target.output_name.format( - cluster_name=cluster.name), - vars={ - 'cluster': cluster, - 'typeLookup': TypeLookupContext(self.idl, cluster), - 'globalTypes': _GLOBAL_TYPES, - } - ) - - -class JavaClassGenerator(__JavaCodeGenerator): - """Generates .java files """ - - def __init__(self, *args, **kargs): - super().__init__(*args, **kargs) - - def internal_render_all(self): - """ - Renders .java files required for java matter support - """ - - clientClusters = [ - c for c in self.idl.clusters if c.side == ClusterSide.CLIENT] - - self.internal_render_one_output( - template_path="ClusterReadMapping.jinja", - output_file_name="java/chip/devicecontroller/ClusterReadMapping.java", - vars={ - 'idl': self.idl, - 'clientClusters': clientClusters, - } - ) - - self.internal_render_one_output( - template_path="ClusterWriteMapping.jinja", - output_file_name="java/chip/devicecontroller/ClusterWriteMapping.java", - vars={ - 'idl': self.idl, - 'clientClusters': clientClusters, - } - ) - - self.internal_render_one_output( - template_path="ClusterIDMapping.jinja", - output_file_name="java/chip/devicecontroller/ClusterIDMapping.java", - vars={ - 'idl': self.idl, - 'clientClusters': clientClusters, - } - ) - - # Every cluster has its own impl, to avoid - # very large compilations (running out of RAM) - for cluster in self.idl.clusters: - if cluster.side != ClusterSide.CLIENT: - continue - - for struct in cluster.structs: - if struct.tag: - continue - - output_name = "java/chip/devicecontroller/cluster/structs/{cluster_name}Cluster{struct_name}.kt" - self.internal_render_one_output( - template_path="ChipStructs.jinja", - output_file_name=output_name.format( - cluster_name=cluster.name, - struct_name=struct.name), - vars={ - 'cluster': cluster, - 'struct': struct, - 'typeLookup': TypeLookupContext(self.idl, cluster), - } - ) - - for event in cluster.events: - if not event.fields: - continue - - output_name = "java/chip/devicecontroller/cluster/eventstructs/{cluster_name}Cluster{event_name}Event.kt" - self.internal_render_one_output( - template_path="ChipEventStructs.jinja", - output_file_name=output_name.format( - cluster_name=cluster.name, - event_name=event.name), - vars={ - 'cluster': cluster, - 'event': event, - 'typeLookup': TypeLookupContext(self.idl, cluster), - } - ) diff --git a/scripts/py_matter_idl/matter_idl/generators/registry.py b/scripts/py_matter_idl/matter_idl/generators/registry.py deleted file mode 100644 index e3c8e1ed32397e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/registry.py +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum -import importlib - -from matter_idl.generators.cpp.application import CppApplicationGenerator -from matter_idl.generators.cpp.tlvmeta import TLVMetaDataGenerator -from matter_idl.generators.java import JavaClassGenerator, JavaJNIGenerator - - -class CodeGenerator(enum.Enum): - """ - Represents every generator type supported by codegen and maps - the simple enum value (user friendly and can be a command line input) - into underlying generators. - """ - JAVA_JNI = enum.auto() - JAVA_CLASS = enum.auto() - CPP_APPLICATION = enum.auto() - CPP_TLVMETA = enum.auto() - CUSTOM = enum.auto() - - def Create(self, *args, **kargs): - if self == CodeGenerator.JAVA_JNI: - return JavaJNIGenerator(*args, **kargs) - elif self == CodeGenerator.JAVA_CLASS: - return JavaClassGenerator(*args, **kargs) - elif self == CodeGenerator.CPP_APPLICATION: - return CppApplicationGenerator(*args, **kargs) - elif self == CodeGenerator.CPP_TLVMETA: - return TLVMetaDataGenerator(*args, **kargs) - elif self == CodeGenerator.CUSTOM: - # Use a package naming convention to find the custom generator: - # ./matter_idl_plugin/__init__.py defines a subclass of CodeGenerator named CustomGenerator. - # The plugin is expected to be in the path provided via the `--plugin ` cli argument. - # Replaces `from plugin_module import CustomGenerator`` - plugin_module = importlib.import_module(kargs['plugin_module']) - CustomGenerator = plugin_module.CustomGenerator - return CustomGenerator(*args, **kargs) - else: - raise NameError("Unknown code generator type") - - @staticmethod - def FromString(name): - global GENERATORS - - if name.lower() in GENERATORS: - return GENERATORS[name.lower()] - else: - raise NameError("Unknown code generator type '%s'" % name) - - -# Contains all known code generators along with a string -# to uniquely identify them when running command line tools or -# executing tests -GENERATORS = { - 'java-jni': CodeGenerator.JAVA_JNI, - 'java-class': CodeGenerator.JAVA_CLASS, - 'cpp-app': CodeGenerator.CPP_APPLICATION, - 'cpp-tlvmeta': CodeGenerator.CPP_TLVMETA, - 'custom': CodeGenerator.CUSTOM, -} diff --git a/scripts/py_matter_idl/matter_idl/generators/types.py b/scripts/py_matter_idl/matter_idl/generators/types.py deleted file mode 100644 index a22275bf29bb0f..00000000000000 --- a/scripts/py_matter_idl/matter_idl/generators/types.py +++ /dev/null @@ -1,440 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum -import logging -from dataclasses import dataclass -from typing import Optional, Union - -from matter_idl import matter_idl_types # to explicitly say 'Enum' -from matter_idl.matter_idl_types import DataType - - -def ToPowerOfTwo(bits: int) -> int: - """ - Given a number, find the next power of two that is >= to the given value. - - Can be used to figure out a variable size given non-standard bit sizes in - matter: eg. a int24 can be stored in an int32, so ToPortOfTwo(24) == 32. - - """ - # probably bit manipulation can be faster, but this should be ok as well - result = 1 - while result < bits: - result = result * 2 - return result - - -@dataclass -class BasicInteger: - """ - Represents something that is stored as a basic integer. - """ - idl_name: str - byte_count: int # NOTE: may NOT be a power of 2 for odd sized integers - is_signed: bool - - @property - def bits(self): - return self.byte_count * 8 - - @property - def power_of_two_bits(self): - return ToPowerOfTwo(self.bits) - - -@dataclass -class BasicString: - """ - Represents either a string or a binary string (blob). - """ - idl_name: str - is_binary: bool - max_length: Union[int, None] = None - - -class FundamentalType(enum.Enum): - """ - Native types, generally available across C++/ObjC/Java/python/other. - """ - BOOL = enum.auto() - FLOAT = enum.auto() - DOUBLE = enum.auto() - - @property - def idl_name(self): - if self == FundamentalType.BOOL: - return "bool" - elif self == FundamentalType.FLOAT: - return "single" - elif self == FundamentalType.DOUBLE: - return "double" - else: - raise Exception("Type not handled: %r" % self) - - @property - def byte_count(self): - if self == FundamentalType.BOOL: - return 1 - elif self == FundamentalType.FLOAT: - return 4 - elif self == FundamentalType.DOUBLE: - return 8 - else: - raise Exception("Type not handled: %r" % self) - - @property - def bits(self): - return self.byte_count * 8 - - -@dataclass -class IdlEnumType: - """ - An enumeration type. Enumerations are constants with an underlying - base type that is an interger. - """ - idl_name: str - base_type: BasicInteger - - @property - def byte_count(self): - return self.base_type.byte_count - - @property - def bits(self): - return self.base_type.bits - - -@dataclass -class IdlBitmapType: - """ - Bitmaps mark that each bit (or a subset of said bits) have a meaning. - - Examples include "feature maps" where bits represent feature available or not. - """ - idl_name: str - base_type: BasicInteger - - @property - def byte_count(self): - return self.base_type.byte_count - - @property - def bits(self): - return self.base_type.bits - - -class IdlItemType(enum.Enum): - UNKNOWN = enum.auto() - STRUCT = enum.auto() - - -@dataclass -class IdlType: - """ - A type defined within the IDL. - - IDLs would generally only define structures as all other types are - described in other things like enums/bitmaps/basic types etc. - - However since IDL parsing is not yet codegen just syntactically, we allow - the option to have a type that is marked 'unknown' (likely invalid/never - defined). - """ - idl_name: str - item_type: IdlItemType - - @property - def is_struct(self) -> bool: - return self.item_type == IdlItemType.STRUCT - - -# Data types, held by ZAP in chip-types.xml and generally by the spec. -__CHIP_SIZED_TYPES__ = { - "bitmap16": BasicInteger(idl_name="bitmap16", byte_count=2, is_signed=False), - "bitmap24": BasicInteger(idl_name="bitmap24", byte_count=3, is_signed=False), - "bitmap32": BasicInteger(idl_name="bitmap32", byte_count=4, is_signed=False), - "bitmap64": BasicInteger(idl_name="bitmap64", byte_count=8, is_signed=False), - "bitmap8": BasicInteger(idl_name="bitmap8", byte_count=1, is_signed=False), - "enum16": BasicInteger(idl_name="enum16", byte_count=2, is_signed=False), - "enum32": BasicInteger(idl_name="enum32", byte_count=4, is_signed=False), - "enum8": BasicInteger(idl_name="enum8", byte_count=1, is_signed=False), - "int16s": BasicInteger(idl_name="int16s", byte_count=2, is_signed=True), - "int16u": BasicInteger(idl_name="int16u", byte_count=2, is_signed=False), - "int24s": BasicInteger(idl_name="int24s", byte_count=3, is_signed=True), - "int24u": BasicInteger(idl_name="int24u", byte_count=3, is_signed=False), - "int32s": BasicInteger(idl_name="int32s", byte_count=4, is_signed=True), - "int32u": BasicInteger(idl_name="int32u", byte_count=4, is_signed=False), - "int40s": BasicInteger(idl_name="int40s", byte_count=5, is_signed=True), - "int40u": BasicInteger(idl_name="int40u", byte_count=5, is_signed=False), - "int48s": BasicInteger(idl_name="int48s", byte_count=6, is_signed=True), - "int48u": BasicInteger(idl_name="int48u", byte_count=6, is_signed=False), - "int56s": BasicInteger(idl_name="int56s", byte_count=7, is_signed=True), - "int56u": BasicInteger(idl_name="int56u", byte_count=7, is_signed=False), - "int64s": BasicInteger(idl_name="int64s", byte_count=8, is_signed=True), - "int64u": BasicInteger(idl_name="int64u", byte_count=8, is_signed=False), - "int8s": BasicInteger(idl_name="int8s", byte_count=1, is_signed=True), - "int8u": BasicInteger(idl_name="int8u", byte_count=1, is_signed=False), - # Derived types - # Specification describes them in section '7.18.2. Derived Data Types' - "action_id": BasicInteger(idl_name="action_id", byte_count=1, is_signed=False), - "attrib_id": BasicInteger(idl_name="attrib_id", byte_count=4, is_signed=False), - "cluster_id": BasicInteger(idl_name="cluster_id", byte_count=4, is_signed=False), - "command_id": BasicInteger(idl_name="command_id", byte_count=4, is_signed=False), - "data_ver": BasicInteger(idl_name="data_ver", byte_count=4, is_signed=False), - "date": BasicInteger(idl_name="date", byte_count=4, is_signed=False), - "devtype_id": BasicInteger(idl_name="devtype_id", byte_count=4, is_signed=False), - "endpoint_no": BasicInteger(idl_name="endpoint_no", byte_count=2, is_signed=False), - "epoch_s": BasicInteger(idl_name="epoch_s", byte_count=4, is_signed=False), - "epoch_us": BasicInteger(idl_name="epoch_us", byte_count=8, is_signed=False), - "elapsed_s": BasicInteger(idl_name="elapsed_s", byte_count=4, is_signed=False), - "event_id": BasicInteger(idl_name="event_id", byte_count=4, is_signed=False), - "event_no": BasicInteger(idl_name="event_no", byte_count=8, is_signed=False), - "fabric_id": BasicInteger(idl_name="fabric_id", byte_count=8, is_signed=False), - "fabric_idx": BasicInteger(idl_name="fabric_idx", byte_count=1, is_signed=False), - "field_id": BasicInteger(idl_name="field_id", byte_count=4, is_signed=False), - "group_id": BasicInteger(idl_name="group_id", byte_count=2, is_signed=False), - "node_id": BasicInteger(idl_name="node_id", byte_count=8, is_signed=False), - "percent": BasicInteger(idl_name="percent", byte_count=1, is_signed=False), - "percent100ths": BasicInteger(idl_name="percent100ths", byte_count=2, is_signed=False), - "posix_ms": BasicInteger(idl_name="posix_ms", byte_count=8, is_signed=False), - "status": BasicInteger(idl_name="status", byte_count=2, is_signed=False), - "systime_us": BasicInteger(idl_name="systime_us", byte_count=8, is_signed=False), - "systime_ms": BasicInteger(idl_name="systime_ms", byte_count=8, is_signed=False), - "temperature": BasicInteger(idl_name="temperature", byte_count=2, is_signed=True), - "tod": BasicInteger(idl_name="tod", byte_count=4, is_signed=False), - "trans_id": BasicInteger(idl_name="trans_id", byte_count=4, is_signed=False), - "vendor_id": BasicInteger(idl_name="vendor_id", byte_count=2, is_signed=False), -} - - -class TypeLookupContext: - """ - Handles type lookups within a scope. - - Generally when looking for a struct/enum, the lookup will be first done - at a cluster level, then at a global level. - - Example: - - ================ test.matter ============== - enum A {} - - server cluster X { - struct A {} - struct B {} - } - - server cluster Y { - enum C {} - } - =========================================== - - When considering a lookup context of global (i.e. cluster is not set) - "A" is defined as an enum (::A) - "B" is undefined - "C" is undefined - - When considering a lookup context of cluster X - "A" is defined as a struct (X::A) - "B" is defined as a struct (X::B) - "C" is undefined - - When considering a lookup context of cluster Y - "A" is defined as an enum (::A) - "B" is undefined - "C" is defined as an enum (Y::C) - - """ - - def __init__(self, idl: matter_idl_types.Idl, cluster: Optional[matter_idl_types.Cluster]): - self.idl = idl - self.cluster = cluster - - def find_enum(self, name) -> Optional[matter_idl_types.Enum]: - """ - Find the first enumeration matching the given name for the given - lookup rules (searches cluster first, then global). - """ - for e in self.all_enums: - if e.name == name: - return e - - return None - - def find_struct(self, name) -> Optional[matter_idl_types.Struct]: - for s in self.all_structs: - if s.name == name: - return s - - return None - - def find_bitmap(self, name) -> Optional[matter_idl_types.Bitmap]: - for s in self.all_bitmaps: - if s.name == name: - return s - - return None - - @property - def all_enums(self): - """ - All enumerations, ordered by lookup priority. - - If an enum A is defined both in the cluster and globally, this WILL - return both instances, however it will return the cluster version first. - """ - if self.cluster: - for e in self.cluster.enums: - yield e - for e in self.idl.enums: - yield e - - @property - def all_bitmaps(self): - """ - All bitmaps defined within this lookup context. - - bitmaps are only defined at cluster level. If lookup context does not - include a cluster, the bitmal list will be empty. - """ - if self.cluster: - for b in self.cluster.bitmaps: - yield b - - @property - def all_structs(self): - """All structs, ordered by lookup prioroty. - - If a struct A is defined both in the cluster and globally, this WILL - return both instances, however it will return the cluster version first. - """ - if self.cluster: - for e in self.cluster.structs: - yield e - for e in self.idl.structs: - yield e - - def is_enum_type(self, name: str): - """ - Determine if the given type name is an enumeration. - - Handles both standard names (like enum8) as well as enumerations defined - within the current lookup context. - """ - if name.lower() in ["enum8", "enum16", "enum32"]: - return True - return any(map(lambda e: e.name == name, self.all_enums)) - - def is_struct_type(self, name: str): - """ - Determine if the given type name is type that is known to be a struct - """ - return any(map(lambda s: s.name == name, self.all_structs)) - - def is_untyped_bitmap_type(self, name: str): - """Determine if the given type is a untyped bitmap (just an interger size).""" - return name.lower() in {"bitmap8", "bitmap16", "bitmap24", "bitmap32", "bitmap64"} - - def is_bitmap_type(self, name: str): - """ - Determine if the given type name is type that is known to be a bitmap. - - Handles both standard/zcl names (like bitmap32) and types defined within - the current lookup context. - """ - if self.is_untyped_bitmap_type(name): - return True - - return any(map(lambda s: s.name == name, self.all_bitmaps)) - - -def ParseDataType(data_type: DataType, lookup: TypeLookupContext) -> Union[BasicInteger, BasicString, FundamentalType, IdlType, IdlEnumType, IdlBitmapType]: - """ - Given a AST data type and a lookup context, match it to a type that can be later - be used for generation. - - AST parsing is textual, so it does not understand what "foo" means. This method - looks up what "foo" actually means: includes basic types (e.g. bool), - zcl types (like enums or bitmaps) and does lookups to find structs/enums/bitmaps/etc - that are defined in the given lookup context. - """ - - lowercase_name = data_type.name.lower() - - if lowercase_name == 'boolean': - return FundamentalType.BOOL - if lowercase_name == 'single': - return FundamentalType.FLOAT - elif lowercase_name == 'double': - return FundamentalType.DOUBLE - elif lowercase_name in ['char_string', 'long_char_string']: - return BasicString(idl_name=lowercase_name, is_binary=False, max_length=data_type.max_length) - elif lowercase_name in ['octet_string', 'long_octet_string']: - return BasicString(idl_name=lowercase_name, is_binary=True, max_length=data_type.max_length) - elif lowercase_name in ['enum8', 'enum16', 'enum32']: - return IdlEnumType(idl_name=lowercase_name, base_type=__CHIP_SIZED_TYPES__[lowercase_name]) - elif lowercase_name in ['bitmap8', 'bitmap16', 'bitmap24', 'bitmap32']: - return IdlBitmapType(idl_name=lowercase_name, base_type=__CHIP_SIZED_TYPES__[lowercase_name]) - - int_type = __CHIP_SIZED_TYPES__.get(lowercase_name, None) - if int_type is not None: - return int_type - - # All fast checks done, now check against known data types - e = lookup.find_enum(data_type.name) - if e: - # Valid enum found. it MUST be based on a valid data type - return IdlEnumType(idl_name=data_type.name, base_type=__CHIP_SIZED_TYPES__[e.base_type.lower()]) - - b = lookup.find_bitmap(data_type.name) - if b: - # Valid enum found. it MUST be based on a valid data type - return IdlBitmapType(idl_name=data_type.name, base_type=__CHIP_SIZED_TYPES__[b.base_type.lower()]) - - result = IdlType(idl_name=data_type.name, item_type=IdlItemType.UNKNOWN) - if lookup.find_struct(data_type.name): - result.item_type = IdlItemType.STRUCT - else: - logging.warning( - "Data type %s is NOT known, but treating it as a generic IDL type." % data_type) - - return result - - -def IsSignedDataType(data_type: DataType) -> bool: - """ - Returns if the data type is a signed type. - Returns if the data type is a signed data type of False if the data type can not be found. - """ - lowercase_name = data_type.name.lower() - sized_type = __CHIP_SIZED_TYPES__.get(lowercase_name, None) - if sized_type is None: - return False - - return sized_type.is_signed - - -def GetDataTypeSizeInBits(data_type: DataType) -> Optional[int]: - """ - Returns the size in bits for a given data type or None if the data type can not be found. - """ - - lowercase_name = data_type.name.lower() - sized_type = __CHIP_SIZED_TYPES__.get(lowercase_name, None) - if sized_type is None: - return None - - return sized_type.power_of_two_bits diff --git a/scripts/py_matter_idl/matter_idl/lint/__init__.py b/scripts/py_matter_idl/matter_idl/lint/__init__.py deleted file mode 100644 index 3ab2b9f7badd25..00000000000000 --- a/scripts/py_matter_idl/matter_idl/lint/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .lint_rules_parser import CreateParser - -__all__ = [CreateParser] diff --git a/scripts/py_matter_idl/matter_idl/lint/lint_rules_grammar.lark b/scripts/py_matter_idl/matter_idl/lint/lint_rules_grammar.lark deleted file mode 100644 index 90cfd6e8d441f7..00000000000000 --- a/scripts/py_matter_idl/matter_idl/lint/lint_rules_grammar.lark +++ /dev/null @@ -1,34 +0,0 @@ -start: instruction* - -instruction: load_xml|all_endpoint_rule|specific_endpoint_rule - -load_xml: "load" ESCAPED_STRING ";" - -all_endpoint_rule: "all" "endpoints" "{" required_global_attribute* "}" - -specific_endpoint_rule: "endpoint" integer "{" (required_server_cluster|rejected_server_cluster)* "}" - -required_global_attribute: "require" "global" "attribute" id "=" integer ";" - -required_server_cluster: "require" "server" "cluster" (id|POSITIVE_INTEGER|HEX_INTEGER) ";" - -rejected_server_cluster: "reject" "server" "cluster" (id|POSITIVE_INTEGER|HEX_INTEGER) ";" - -integer: positive_integer | negative_integer - -positive_integer: POSITIVE_INTEGER | HEX_INTEGER -negative_integer: "-" positive_integer - -id: ID - -POSITIVE_INTEGER: /\d+/ -HEX_INTEGER: /0x[A-Fa-f0-9]+/ -ID: /[a-zA-Z_][a-zA-Z0-9_]*/ - -%import common.ESCAPED_STRING -%import common.WS -%import common.C_COMMENT -%import common.CPP_COMMENT -%ignore WS -%ignore C_COMMENT -%ignore CPP_COMMENT diff --git a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py deleted file mode 100755 index 9499e360399230..00000000000000 --- a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py +++ /dev/null @@ -1,377 +0,0 @@ -#!/usr/bin/env python - -import logging -import os -import xml.etree.ElementTree -from dataclasses import dataclass -from enum import Enum, auto -from typing import List, MutableMapping, Optional, Tuple, Union - -from lark import Lark -from lark.visitors import Discard, Transformer, v_args - -try: - from .types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, ClusterValidationRule, - RequiredAttributesRule, RequiredCommandsRule) -except ImportError: - import sys - - sys.path.append(os.path.join(os.path.abspath( - os.path.dirname(__file__)), "..", "..")) - from matter_idl.lint.types import (AttributeRequirement, ClusterCommandRequirement, ClusterRequirement, ClusterValidationRule, - RequiredAttributesRule, RequiredCommandsRule) - - -class ElementNotFoundError(Exception): - def __init__(self, name): - super().__init__(f"Could not find {name}") - - -def parseNumberString(n: str) -> int: - if n.startswith('0x'): - return int(n[2:], 16) - else: - return int(n) - - -@dataclass -class RequiredAttribute: - name: str - code: int - - -@dataclass -class RequiredCommand: - name: str - code: int - - -@dataclass -class DecodedCluster: - name: str - code: int - required_attributes: List[RequiredAttribute] - required_commands: List[RequiredCommand] - - -class ClusterActionEnum(Enum): - REQUIRE = auto() - REJECT = auto() - - -@dataclass -class ServerClusterRequirement: - action: ClusterActionEnum - id: Union[str, int] - - -def DecodeClusterFromXml(element: xml.etree.ElementTree.Element): - if element.tag != 'cluster': - logging.error("Not a cluster element: %r" % element) - return None - - # cluster elements contain among other children - # - name (general name for this cluster) - # - code (unique identifier, may be hex or numeric) - # - attribute with side, code and optional attributes - try: - name = element.find('name') - if name is None or not name.text: - raise ElementNotFoundError('name') - - name = name.text.replace(' ', '') - required_attributes = [] - required_commands = [] - - for attr in element.findall('attribute'): - if attr.attrib['side'] != 'server': - continue - - if 'optional' in attr.attrib and attr.attrib['optional'] == 'true': - continue - - # when introducing access controls, the content of attributes may either be: - # myName - # or - # myName... - attr_name = attr.text - description = attr.find('description') - if description is not None: - attr_name = description.text - - required_attributes.append( - RequiredAttribute( - name=attr_name, - code=parseNumberString(attr.attrib['code']) - )) - - for cmd in element.findall('command'): - if cmd.attrib['source'] != 'client': - continue - - if 'optional' in cmd.attrib and cmd.attrib['optional'] == 'true': - continue - - required_commands.append(RequiredCommand( - name=cmd.attrib["name"], code=parseNumberString(cmd.attrib['code']))) - - code = element.find('code') - if code is None: - raise Exception("Failed to find cluster code") - - return DecodedCluster( - name=name, - code=parseNumberString(code.text), - required_attributes=required_attributes, - required_commands=required_commands - ) - except Exception: - logging.exception("Failed to decode cluster %r" % element) - return None - - -def ClustersInXmlFile(path: str): - logging.info("Loading XML from %s" % path) - - # root is expected to be just a "configurator" object - configurator = xml.etree.ElementTree.parse(path).getroot() - for child in configurator: - if child.tag != 'cluster': - continue - yield child - - -class LintRulesContext: - """Represents a context for loadint lint rules. - - Handles: - - loading referenced files (matter xml definitions) - - adding linter rules as data is parsed - - Looking up identifiers for various rules - """ - - def __init__(self): - self._required_attributes_rule = RequiredAttributesRule( - "Required attributes") - self._cluster_validation_rule = ClusterValidationRule( - "Cluster validation") - self._required_commands_rule = RequiredCommandsRule( - "Required commands") - - # Map cluster names to the underlying code - self._cluster_codes: MutableMapping[str, int] = {} - - def GetLinterRules(self): - return [self._required_attributes_rule, self._required_commands_rule, self._cluster_validation_rule] - - def RequireAttribute(self, r: AttributeRequirement): - self._required_attributes_rule.RequireAttribute(r) - - def FindClusterCode(self, name: str) -> Optional[Tuple[str, int]]: - if name not in self._cluster_codes: - # Name may be a number. If this can be parsed as a number, accept it anyway - try: - return "ID_%s" % name, parseNumberString(name) - except ValueError: - logging.error("UNKNOWN cluster name %s" % name) - logging.error("Known names: %s" % - (",".join(self._cluster_codes.keys()), )) - return None - else: - return name, self._cluster_codes[name] - - def RequireClusterInEndpoint(self, name: str, code: int): - """Mark that a specific cluster is always required in the given endpoint - """ - cluster_info = self.FindClusterCode(name) - if not cluster_info: - return - - name, cluster_code = cluster_info - - self._cluster_validation_rule.RequireClusterInEndpoint(ClusterRequirement( - endpoint_id=code, - cluster_code=cluster_code, - cluster_name=name, - )) - - def RejectClusterInEndpoint(self, name: str, code: int): - """Mark that a specific cluster is always rejected in the given endpoint - """ - cluster_info = self.FindClusterCode(name) - if not cluster_info: - return - - name, cluster_code = cluster_info - - self._cluster_validation_rule.RejectClusterInEndpoint(ClusterRequirement( - endpoint_id=code, - cluster_code=cluster_code, - cluster_name=name, - )) - - def LoadXml(self, path: str): - """Load XML data from the given path and add it to - internal processing. Adds attribute requirement rules - as needed. - """ - for cluster in ClustersInXmlFile(path): - decoded = DecodeClusterFromXml(cluster) - - if not decoded: - continue - - self._cluster_codes[decoded.name] = decoded.code - - for attr in decoded.required_attributes: - self._required_attributes_rule.RequireAttribute(AttributeRequirement( - code=attr.code, name=attr.name, filter_cluster=decoded.code)) - - for cmd in decoded.required_commands: - self._required_commands_rule.RequireCommand( - ClusterCommandRequirement( - cluster_code=decoded.code, - command_code=cmd.code, - command_name=cmd.name - )) - - -class LintRulesTransformer(Transformer): - """ - A transformer capable to transform data parsed by Lark according to - lint_rules_grammar.lark. - """ - - def __init__(self, file_name: str): - self.context = LintRulesContext() - self.file_name = file_name - - def positive_integer(self, tokens): - """Numbers in the grammar are integers or hex numbers. - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - - return parseNumberString(tokens[0].value) - - @v_args(inline=True) - def negative_integer(self, value): - return -value - - @v_args(inline=True) - def integer(self, value): - return value - - def id(self, tokens): - """An id is a string containing an identifier - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - return tokens[0].value - - def ESCAPED_STRING(self, s): - # handle escapes, skip the start and end quotes - return s.value[1:-1].encode('utf-8').decode('unicode-escape') - - def start(self, instructions): - # At this point processing is considered done, return all - # linter rules that were found - return self.context.GetLinterRules() - - def instruction(self, instruction): - return Discard - - def all_endpoint_rule(self, attributes): - for attribute in attributes: - self.context.RequireAttribute(attribute) - - return Discard - - @v_args(inline=True) - def load_xml(self, path): - if not os.path.isabs(path): - path = os.path.abspath(os.path.join( - os.path.dirname(self.file_name), path)) - - self.context.LoadXml(path) - - @v_args(inline=True) - def required_global_attribute(self, name, code): - return AttributeRequirement(code=code, name=name) - - @v_args(inline=True) - def specific_endpoint_rule(self, code, *requirements): - for requirement in requirements: - if requirement.action == ClusterActionEnum.REQUIRE: - self.context.RequireClusterInEndpoint(requirement.id, code) - elif requirement.action == ClusterActionEnum.REJECT: - self.context.RejectClusterInEndpoint(requirement.id, code) - else: - raise Exception("Unexpected requirement action %r" % - requirement.action) - - return Discard - - @v_args(inline=True) - def required_server_cluster(self, id): - return ServerClusterRequirement(ClusterActionEnum.REQUIRE, id) - - @v_args(inline=True) - def rejected_server_cluster(self, id): - return ServerClusterRequirement(ClusterActionEnum.REJECT, id) - - -class Parser: - def __init__(self, parser, file_name: str): - self.parser = parser - self.file_name = file_name - - def parse(self): - data = LintRulesTransformer(self.file_name).transform( - self.parser.parse(open(self.file_name, "rt").read())) - return data - - -def CreateParser(file_name: str): - """ - Generates a parser that will process a ".matter" file into a IDL - """ - return Parser( - Lark.open('lint_rules_grammar.lark', rel_to=__file__, parser='lalr', propagate_positions=True), file_name=file_name) - - -if __name__ == '__main__': - # This Parser is generally not intended to be run as a stand-alone binary. - # The ability to run is for debug and to print out the parsed AST. - import click - - # Supported log levels, mapping string values required for argument - # parsing into logging constants - __LOG_LEVELS__ = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warn': logging.WARN, - 'fatal': logging.FATAL, - } - - @click.command() - @click.option( - '--log-level', - default='INFO', - type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), - help='Determines the verbosity of script output.') - @click.argument('filename') - def main(log_level, filename=None): - logging.basicConfig( - level=__LOG_LEVELS__[log_level], - format='%(asctime)s %(levelname)-7s %(message)s', - ) - - logging.info("Starting to parse ...") - data = CreateParser(filename).parse() - logging.info("Parse completed") - - logging.info("Data:") - logging.info("%r" % data) - - main(auto_envvar_prefix='CHIP') diff --git a/scripts/py_matter_idl/matter_idl/lint/types.py b/scripts/py_matter_idl/matter_idl/lint/types.py deleted file mode 100644 index 1b148ac430c47a..00000000000000 --- a/scripts/py_matter_idl/matter_idl/lint/types.py +++ /dev/null @@ -1,347 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from typing import List, MutableMapping, Optional - -from matter_idl.matter_idl_types import ClusterSide, Idl, ParseMetaData - - -class MissingIdlError(Exception): - def __init__(self): - super().__init__("Missing IDL data") - - -@dataclass -class LocationInFile: - file_name: str - line: Optional[int] - column: Optional[int] - - def __init__(self, file_name: str, meta: ParseMetaData): - self.file_name = file_name - self.line = meta.line - self.column = meta.column - - -@dataclass -class LintError: - """Represents a lint error, potentially at a specific location in a file""" - - message: str - location: Optional[LocationInFile] = field(default=None) - - def __init__(self, text: str, location: Optional[LocationInFile] = None): - self.message = text - if location: - self.message += " at %s:%d:%d" % (location.file_name, - location.line, location.column) - - def __str__(self): - return self.message - - -class LintRule(ABC): - """Validates a linter rule on an idl""" - - def __init__(self, name): - self.name = name - - @abstractmethod - def LintIdl(self, idl: Idl) -> List[LintError]: - """Runs the linter on the given IDL and returns back any errors it may find""" - pass - - -@dataclass -class AttributeRequirement: - """Contains information about a required attribute""" - code: int # required attributes are searched by codes - name: str # the name of this attribute. Expect it to be exposed properly - - # Optional filters to apply to specific locations - filter_cluster: Optional[int] = field(default=None) - - -@dataclass -class ClusterRequirement: - endpoint_id: int - cluster_code: int - cluster_name: str - - -class ErrorAccumulatingRule(LintRule): - """Contains a lint error list and helps helpers to add to such a list of rules.""" - - def __init__(self, name): - super(ErrorAccumulatingRule, self).__init__(name) - self._lint_errors = [] - self._idl = None - - def _AddLintError(self, text, location): - self._lint_errors.append( - LintError("%s: %s" % (self.name, text), location)) - - def _ParseLocation(self, meta: Optional[ParseMetaData]) -> Optional[LocationInFile]: - """Create a location in the current file that is being parsed. """ - if not meta or not self._idl or not self._idl.parse_file_name: - return None - return LocationInFile(self._idl.parse_file_name, meta) - - def LintIdl(self, idl: Idl) -> List[LintError]: - self._idl = idl - self._lint_errors = [] - self._LintImpl() - return self._lint_errors - - @abstractmethod - def _LintImpl(self): - """Implements actual linting of the IDL. - - Uses the underlying _idl for validation. - """ - pass - - -class ClusterValidationRule(ErrorAccumulatingRule): - def __init__(self, name): - super().__init__(name) - self._mandatory_clusters: List[ClusterRequirement] = [] - self._rejected_clusters: List[ClusterRequirement] = [] - - def __repr__(self): - result = "ClusterValidationRule{\n" - - if self._mandatory_clusters: - result += " mandatory_clusters:\n" - for cluster in self._mandatory_clusters: - result += " - %r\n" % cluster - - if self._rejected_clusters: - result += " rejected_clusters:\n" - for cluster in self._rejected_clusters: - result += " - %r\n" % cluster - - result += "}" - - return result - - def RequireClusterInEndpoint(self, requirement: ClusterRequirement): - self._mandatory_clusters.append(requirement) - - def RejectClusterInEndpoint(self, requirement: ClusterRequirement): - self._rejected_clusters.append(requirement) - - def _ClusterCode(self, name: str, location: Optional[LocationInFile]): - """Finds the server cluster definition with the given name. - - On error returns None and _lint_errors is updated internlly - """ - if not self._idl: - raise MissingIdlError() - - cluster_definition = [ - c for c in self._idl.clusters if c.name == name and c.side == ClusterSide.SERVER - ] - if not cluster_definition: - self._AddLintError( - "Cluster definition for %s not found" % name, location) - return None - - if len(cluster_definition) > 1: - self._AddLintError( - "Multiple cluster definitions found for %s" % name, location) - return None - - return cluster_definition[0].code - - def _LintImpl(self): - if not self._idl: - raise MissingIdlError() - - for endpoint in self._idl.endpoints: - cluster_codes = set() - for cluster in endpoint.server_clusters: - cluster_code = self._ClusterCode( - cluster.name, self._ParseLocation(cluster.parse_meta)) - if not cluster_code: - continue - - cluster_codes.add(cluster_code) - - for requirement in self._mandatory_clusters: - if requirement.endpoint_id != endpoint.number: - continue - - if requirement.cluster_code not in cluster_codes: - self._AddLintError("Endpoint %d DOES NOT expose cluster %s (%d)" % - (requirement.endpoint_id, requirement.cluster_name, requirement.cluster_code), location=None) - - for requirement in self._rejected_clusters: - if requirement.endpoint_id != endpoint.number: - continue - - if requirement.cluster_code in cluster_codes: - self._AddLintError("Endpoint %d EXPOSES cluster %s (%d)" % - (requirement.endpoint_id, requirement.cluster_name, requirement.cluster_code), location=None) - - -class RequiredAttributesRule(ErrorAccumulatingRule): - def __init__(self, name): - super().__init__(name) - self._mandatory_attributes: List[AttributeRequirement] = [] - - def __repr__(self): - result = "RequiredAttributesRule{\n" - - if self._mandatory_attributes: - result += " mandatory_attributes:\n" - for attr in self._mandatory_attributes: - result += " - %r\n" % attr - - result += "}" - return result - - def RequireAttribute(self, attr: AttributeRequirement): - """Mark an attribute required""" - self._mandatory_attributes.append(attr) - - def _ServerClusterDefinition(self, name: str, location: Optional[LocationInFile]): - """Finds the server cluster definition with the given name. - - On error returns None and _lint_errors is updated internlly - """ - if not self._idl: - raise MissingIdlError() - - cluster_definition = [ - c for c in self._idl.clusters if c.name == name and c.side == ClusterSide.SERVER - ] - if not cluster_definition: - self._AddLintError( - "Cluster definition for %s not found" % name, location) - return None - - if len(cluster_definition) > 1: - self._AddLintError( - "Multiple cluster definitions found for %s" % name, location) - return None - - return cluster_definition[0] - - def _LintImpl(self): - if not self._idl: - raise MissingIdlError() - - for endpoint in self._idl.endpoints: - - cluster_codes = set() - - for cluster in endpoint.server_clusters: - cluster_definition = self._ServerClusterDefinition( - cluster.name, self._ParseLocation(cluster.parse_meta)) - if not cluster_definition: - continue - - cluster_codes.add(cluster_definition.code) - - # Cluster contains enabled attributes by name - # cluster_definition contains the definition of the attributes themseves - # - # Join the two to receive attribute codes - name_to_code_map = {} - for attr in cluster_definition.attributes: - name_to_code_map[attr.definition.name] = attr.definition.code - - attribute_codes = set() - # For all the instantiated attributes, figure out their code - for attr in cluster.attributes: - if attr.name not in name_to_code_map: - self._AddLintError("Could not find attribute defintion (no code) for %s:%s" % - (cluster.name, attr.name), self._ParseLocation(cluster.parse_meta)) - continue - - attribute_codes.add(name_to_code_map[attr.name]) - - # Linting codes now - for check in self._mandatory_attributes: - if check.filter_cluster is not None and check.filter_cluster != cluster_definition.code: - continue - - if check.code not in attribute_codes: - self._AddLintError("EP%d:%s does not expose %s(%d) attribute" % - (endpoint.number, cluster.name, - check.name, check.code), - self._ParseLocation(cluster.parse_meta)) - - -@dataclass -class ClusterCommandRequirement: - cluster_code: int - command_code: int - command_name: str - - -class RequiredCommandsRule(ErrorAccumulatingRule): - def __init__(self, name): - super(RequiredCommandsRule, self).__init__(name) - - # Maps cluster id to mandatory cluster requirement - self._mandatory_commands: MutableMapping[int, - List[ClusterCommandRequirement]] = {} - - def __repr__(self): - result = "RequiredCommandsRule{\n" - - if self._mandatory_commands: - result += " mandatory_commands:\n" - for key, value in self._mandatory_commands.items(): - result += " - cluster %d:\n" % key - for requirement in value: - result += " - %r\n" % requirement - - result += "}" - return result - - def RequireCommand(self, cmd: ClusterCommandRequirement): - """Mark a command required""" - - if cmd.cluster_code in self._mandatory_commands: - self._mandatory_commands[cmd.cluster_code].append(cmd) - else: - self._mandatory_commands[cmd.cluster_code] = [cmd] - - def _LintImpl(self): - if not self._idl: - raise MissingIdlError() - - for cluster in self._idl.clusters: - if cluster.side != ClusterSide.SERVER: - continue # only validate server-side: - - if cluster.code not in self._mandatory_commands: - continue # no known mandatory commands - - defined_commands = set([c.code for c in cluster.commands]) - - for requirement in self._mandatory_commands[cluster.code]: - if requirement.command_code in defined_commands: - continue # command exists - - self._AddLintError( - "Cluster %s does not define mandatory command %s(%d)" % ( - cluster.name, requirement.command_name, requirement.command_code), - self._ParseLocation(cluster.parse_meta) - ) diff --git a/scripts/py_matter_idl/matter_idl/matter_grammar.lark b/scripts/py_matter_idl/matter_idl/matter_grammar.lark deleted file mode 100644 index 6116e7cbf08071..00000000000000 --- a/scripts/py_matter_idl/matter_idl/matter_grammar.lark +++ /dev/null @@ -1,113 +0,0 @@ -struct: struct_qualities "struct"i id "{" (struct_field ";")* "}" -struct_quality: "fabric_scoped"i -> struct_fabric_scoped -struct_qualities: struct_quality* - -enum: "enum"i id ":" type "{" constant_entry* "}" -bitmap: "bitmap"i id ":" type "{" constant_entry* "}" - -?access_privilege: "view"i -> view_privilege - | "operate"i -> operate_privilege - | "manage"i -> manage_privilege - | "administer"i -> administer_privilege - -?attribute_access_type: "read"i -> read_access - | "write"i -> write_access - -event_access: "access" "(" ("read" ":" access_privilege)? ")" - -event_with_access: "event" event_access? id - -event: event_qualities event_priority event_with_access "=" positive_integer "{" (struct_field ";")* "}" - -event_quality: "fabric_sensitive" -> event_fabric_sensitive -event_qualities: event_quality* - -?event_priority: "critical"i -> critical_priority - | "info"i -> info_priority - | "debug"i -> debug_priority - -attribute_access_entry: attribute_access_type ":" access_privilege - -attribute_access: "access"i "(" (attribute_access_entry ("," attribute_access_entry)* )? ")" - -attribute_with_access: attribute_access? struct_field - -attribute: attribute_qualities "attribute"i attribute_with_access ";" -attribute_quality: "readonly"i -> attr_readonly - | "nosubscribe"i -> attr_nosubscribe - | "timedwrite"i -> attr_timed -attribute_qualities: attribute_quality* -> attribute_qualities - -request_struct: "request"i struct - -// Response structures must have a response id -response_struct: "response"i "struct"i id "=" positive_integer "{" (struct_field ";") * "}" - -command_quality: "timed"i -> timed_command - | "fabric"i -> fabric_scoped_command -command_qualities: command_quality* - -command_access: "access"i "(" ("invoke"i ":" access_privilege)? ")" - -command_with_access: "command"i command_access? id - -command: command_qualities command_with_access "(" id? ")" ":" id "=" positive_integer ";" - -cluster: cluster_side "cluster"i id "=" positive_integer "{" (enum|bitmap|event|attribute|struct|request_struct|response_struct|command)* "}" -?cluster_side: "server"i -> server_cluster - | "client"i -> client_cluster - -endpoint: "endpoint"i positive_integer "{" endpoint_content* "}" -?endpoint_content: endpoint_cluster_binding | endpoint_server_cluster | endpoint_device_type - -endpoint_device_type: "device" "type" id "=" positive_integer "," "version" positive_integer ";" -endpoint_cluster_binding: "binding"i "cluster"i id ";" -endpoint_server_cluster: "server"i "cluster"i id "{" endpoint_cluster_entry* "}" - - -endpoint_attribute_storage: "ram"i -> ram_attribute - | "persist"i -> persist_attribute - | "callback"i -> callback_attribute - -?endpoint_cluster_entry: endpoint_emitted_event | endpoint_attribute_instantiation - -endpoint_emitted_event: "emits"i "event"i id ";" -endpoint_attribute_instantiation: endpoint_attribute_storage "attribute"i id default_value? ";" - -bool_default: "true"i -> bool_default_true - | "false"i -> bool_default_false -?default_value: "default"i "=" (integer | ESCAPED_STRING | bool_default) - -constant_entry: id "=" positive_integer ";" -positive_integer: POSITIVE_INTEGER | HEX_INTEGER -negative_integer: "-" positive_integer - -integer: positive_integer | negative_integer - -struct_field: member_attribute* field - -member_attribute: "optional"i -> optional - | "nullable"i -> nullable - | "fabric_sensitive"i -> fabric_sensitive - -field: data_type id list_marker? "=" positive_integer -list_marker: "[" "]" - -data_type: type ("<" positive_integer ">")? - -id: ID -type: ID - -POSITIVE_INTEGER: /\d+/ -HEX_INTEGER: /0x[A-Fa-f0-9]+/ -ID: /[a-zA-Z_][a-zA-Z0-9_]*/ - -idl: (struct|enum|cluster|endpoint)* - -%import common.ESCAPED_STRING -%import common.WS -%import common.C_COMMENT -%import common.CPP_COMMENT -%ignore WS -%ignore C_COMMENT -%ignore CPP_COMMENT diff --git a/scripts/py_matter_idl/matter_idl/matter_idl_parser.py b/scripts/py_matter_idl/matter_idl/matter_idl_parser.py deleted file mode 100755 index f4ba7059bf605d..00000000000000 --- a/scripts/py_matter_idl/matter_idl/matter_idl_parser.py +++ /dev/null @@ -1,574 +0,0 @@ -#!/usr/bin/env python - -import functools -import logging -from typing import Optional - -from lark import Lark -from lark.lexer import Token -from lark.visitors import Transformer, v_args - -try: - from matter_idl.matter_idl_types import AccessPrivilege -except ModuleNotFoundError: - import os - import sys - sys.path.append(os.path.dirname( - os.path.dirname(os.path.abspath(__file__)))) - - from matter_idl.matter_idl_types import AccessPrivilege - -from matter_idl.matter_idl_types import (Attribute, AttributeInstantiation, AttributeOperation, AttributeQuality, AttributeStorage, - Bitmap, Cluster, ClusterSide, Command, CommandQuality, ConstantEntry, DataType, DeviceType, - Endpoint, Enum, Event, EventPriority, EventQuality, Field, FieldQuality, Idl, - ParseMetaData, ServerClusterInstantiation, Struct, StructQuality, StructTag) - - -def UnionOfAllFlags(flags_list): - if not flags_list: - return None - return functools.reduce(lambda a, b: a | b, flags_list) - - -class PrefixCppDocComment: - def __init__(self, token): - self.start_pos = token.start_pos - # Assume CPP comments: /**...*/ - self.value_len = len(token.value) # includes /***/ AND whitespace - self.value = token.value[3:-2].strip() - - def appply_to_idl(self, idl: Idl, content: str): - if self.start_pos is None: - return - - actual_pos = self.start_pos + self.value_len - while content[actual_pos] in ' \t\n\r': - actual_pos += 1 - - # A doc comment will apply to any supported element assuming it immediately - # preceeds id (skipping whitespace) - for item in self.supported_types(idl): - meta = item.parse_meta - if meta and meta.start_pos == actual_pos: - item.description = self.value - return - - def supported_types(self, idl: Idl): - """List all types supported by doc comments.""" - for cluster in idl.clusters: - yield cluster - - for command in cluster.commands: - yield command - - def __repr__(self): - return ("PREFIXDoc: %r at %r" % (self.value, self.start_pos)) - - -class AddServerClusterToEndpointTransform: - """Provides an 'apply' method that can be run on endpoints - to add a server cluster to the given endpoint. - """ - - def __init__(self, cluster: ServerClusterInstantiation): - self.cluster = cluster - - def apply(self, endpoint): - endpoint.server_clusters.append(self.cluster) - - -class AddBindingToEndpointTransform: - """Provides an 'apply' method that can be run on endpoints - to add a cluster binding to the given endpoint. - """ - - def __init__(self, name): - self.name = name - - def apply(self, endpoint): - endpoint.client_bindings.append(self.name) - - -class AddDeviceTypeToEndpointTransform: - """Provides an 'apply' method that can be run on endpoints - to add a device type to it - """ - - def __init__(self, device_type: DeviceType): - self.device_type = device_type - - def apply(self, endpoint): - endpoint.device_types.append(self.device_type) - - -class MatterIdlTransformer(Transformer): - """ - A transformer capable to transform data parsed by Lark according to - matter_grammar.lark. - - Generally transforms a ".matter" file into an Abstract Syntax Tree (AST). - End result will be a `matter_idl_types.Idl` value that represents the - entire parsed .matter file. - - The content of this file closely resembles the .lark input file and its - purpose is to convert LARK tokens (that ar generally inputted by name) - into underlying python types. - - Some documentation to get started is available at - https://lark-parser.readthedocs.io/en/latest/visitors.html#transformer - - TLDR would be: - When the ".lark" defines a token like `foo: number`, the transformer - has the option to define a method called `foo` which will take the - parsed input (as strings unless transformed) and interpret them. - - Actual parametes to the methods depend on the rules multiplicity and/or - optionally. - """ - - def __init__(self, skip_meta): - self.skip_meta = skip_meta - self.doc_comments = [] - self._cluster_start_pos = None - - def positive_integer(self, tokens): - """Numbers in the grammar are integers or hex numbers. - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - - n = tokens[0].value - if n.startswith('0x'): - return int(n[2:], 16) - else: - return int(n) - - @v_args(inline=True) - def negative_integer(self, value): - return -value - - @v_args(inline=True) - def integer(self, value): - return value - - def bool_default_true(self, _): - return True - - def bool_default_false(self, _): - return False - - def id(self, tokens): - """An id is a string containing an identifier - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - return tokens[0].value - - def type(self, tokens): - """A type is just a string for the type - """ - if len(tokens) != 1: - raise Exception("Unexpected argument counts") - return tokens[0].value - - def data_type(self, tokens): - if len(tokens) == 1: - return DataType(name=tokens[0]) - # Just a string for data type - elif len(tokens) == 2: - return DataType(name=tokens[0], max_length=tokens[1]) - else: - raise Exception("Unexpected size for data type") - - @v_args(inline=True) - def constant_entry(self, id, number): - return ConstantEntry(name=id, code=number) - - @v_args(inline=True) - def enum(self, id, type, *entries): - return Enum(name=id, base_type=type, entries=list(entries)) - - @v_args(inline=True) - def bitmap(self, id, type, *entries): - return Bitmap(name=id, base_type=type, entries=list(entries)) - - def field(self, args): - data_type, name = args[0], args[1] - is_list = (len(args) == 4) - code = args[-1] - - return Field(data_type=data_type, name=name, code=code, is_list=is_list) - - def optional(self, _): - return FieldQuality.OPTIONAL - - def nullable(self, _): - return FieldQuality.NULLABLE - - def fabric_sensitive(self, _): - return FieldQuality.FABRIC_SENSITIVE - - def attr_readonly(self, _): - return AttributeQuality.READABLE - - def attr_nosubscribe(self, _): - return AttributeQuality.NOSUBSCRIBE - - def attr_timed(self, _): - return AttributeQuality.TIMED_WRITE - - def attribute_qualities(self, qualities): - return UnionOfAllFlags(qualities) or AttributeQuality.NONE - - def struct_fabric_scoped(self, _): - return StructQuality.FABRIC_SCOPED - - def struct_qualities(self, qualities): - return UnionOfAllFlags(qualities) or StructQuality.NONE - - def critical_priority(self, _): - return EventPriority.CRITICAL - - def info_priority(self, _): - return EventPriority.INFO - - def debug_priority(self, _): - return EventPriority.DEBUG - - def event_fabric_sensitive(self, _): - return EventQuality.FABRIC_SENSITIVE - - def event_qualities(selt, qualities): - return UnionOfAllFlags(qualities) or EventQuality.NONE - - def timed_command(self, _): - return CommandQuality.TIMED_INVOKE - - def fabric_scoped_command(self, _): - return CommandQuality.FABRIC_SCOPED - - def command_qualities(self, attrs): - return UnionOfAllFlags(attrs) or CommandQuality.NONE - - def struct_field(self, args): - # Last argument is the named_member, the rest - # are qualities - field = args[-1] - field.qualities = UnionOfAllFlags(args[:-1]) or FieldQuality.NONE - return field - - @v_args(meta=True) - def server_cluster(self, meta, unused_args): - self._cluster_start_pos = meta and meta.start_pos - return ClusterSide.SERVER - - @v_args(meta=True, inline=True) - def client_cluster(self, meta, *unused_args): - self._cluster_start_pos = meta and meta.start_pos - return ClusterSide.CLIENT - - def command_access(self, privilege): - return privilege[0] - - def command_with_access(self, args): - # Arguments - # - optional access for invoke - # - event identifier (name) - init_args = { - "name": args[-1] - } - if len(args) > 1: - init_args["invokeacl"] = args[0] - - return init_args - - # NOTE: awkward inline because the order of 'meta, children' vs 'children, meta' was flipped - # between lark versions in https://github.com/lark-parser/lark/pull/993 - @v_args(meta=True, inline=True) - def command(self, meta, *args): - # The command takes 4 arguments if no input argument, 5 if input - # argument is provided - args = list(args) # convert from tuple - if len(args) != 5: - args.insert(2, None) - - meta = None if self.skip_meta else ParseMetaData(meta) - - cmd = Command( - parse_meta=meta, - qualities=args[0], - input_param=args[2], output_param=args[3], code=args[4], - **args[1], - ) - - return cmd - - def event_access(self, privilege): - return privilege[0] - - def event_with_access(self, args): - # Arguments - # - optional access for read - # - event identifier (name) - init_args = { - "name": args[-1] - } - if len(args) > 1: - init_args["readacl"] = args[0] - - return init_args - - def event(self, args): - return Event(qualities=args[0], priority=args[1], code=args[3], fields=args[4:], **args[2]) - - def view_privilege(self, args): - return AccessPrivilege.VIEW - - def operate_privilege(self, args): - return AccessPrivilege.OPERATE - - def manage_privilege(self, args): - return AccessPrivilege.MANAGE - - def administer_privilege(self, args): - return AccessPrivilege.ADMINISTER - - def read_access(self, args): - return AttributeOperation.READ - - def write_access(self, args): - return AttributeOperation.WRITE - - @v_args(inline=True) - def attribute_access_entry(self, operation, access): - return (operation, access) - - def attribute_access(self, value): - # return value as-is to not need to deal with trees in `attribute_with_access` - return value - - def attribute_with_access(self, args): - # Input arguments are: - # - acl (optional list of pairs operation + access) - # - field definition - acl = {} - if len(args) > 1: - for operation, access in args[0]: - if operation == AttributeOperation.READ: - acl['readacl'] = access - elif operation == AttributeOperation.WRITE: - acl['writeacl'] = access - else: - raise Exception( - "Unknown attribute operation: %r" % operation) - - return (args[-1], acl) - - def ram_attribute(self, _): - return AttributeStorage.RAM - - def persist_attribute(self, _): - return AttributeStorage.PERSIST - - def callback_attribute(self, _): - return AttributeStorage.CALLBACK - - @v_args(meta=True, inline=True) - def endpoint_attribute_instantiation(self, meta, storage, id, default=None): - meta = None if self.skip_meta else ParseMetaData(meta) - return AttributeInstantiation(parse_meta=meta, name=id, storage=storage, default=default) - - @v_args(meta=True, inline=True) - def endpoint_emitted_event(self, meta, id): - meta = None if self.skip_meta else ParseMetaData(meta) - return id - - def ESCAPED_STRING(self, s): - # handle escapes, skip the start and end quotes - return s.value[1:-1].encode('utf-8').decode('unicode-escape') - - @v_args(inline=True) - def attribute(self, qualities, definition_tuple): - (definition, acl) = definition_tuple - - # until we support write only (and need a bit of a reshuffle) - # if the 'attr_readonly == READABLE' is not in the list, we make things - # read/write - if AttributeQuality.READABLE not in qualities: - qualities |= AttributeQuality.READABLE - qualities |= AttributeQuality.WRITABLE - - return Attribute(definition=definition, qualities=qualities, **acl) - - @v_args(inline=True) - def struct(self, qualities, id, *fields): - return Struct(name=id, qualities=qualities, fields=list(fields)) - - @v_args(inline=True) - def request_struct(self, value): - value.tag = StructTag.REQUEST - return value - - @v_args(inline=True) - def response_struct(self, id, code, *fields): - return Struct(name=id, tag=StructTag.RESPONSE, code=code, fields=list(fields)) - - @v_args(inline=True) - def endpoint(self, number, *transforms): - endpoint = Endpoint(number=number) - - for t in transforms: - t.apply(endpoint) - - return endpoint - - @v_args(inline=True) - def endpoint_device_type(self, name, code, version): - return AddDeviceTypeToEndpointTransform(DeviceType(name=name, code=code, version=version)) - - @v_args(inline=True) - def endpoint_cluster_binding(self, id): - return AddBindingToEndpointTransform(id) - - @v_args(meta=True, inline=True) - def endpoint_server_cluster(self, meta, id, *content): - meta = None if self.skip_meta else ParseMetaData(meta) - - attributes = [] - events = set() - - for item in content: - if isinstance(item, AttributeInstantiation): - attributes.append(item) - else: - events.add(item) - return AddServerClusterToEndpointTransform( - ServerClusterInstantiation(parse_meta=meta, name=id, attributes=attributes, events_emitted=events)) - - @v_args(inline=True, meta=True) - def cluster(self, meta, side, name, code, *content): - meta = None if self.skip_meta else ParseMetaData(meta) - - # shift actual starting position where the doc comment would start - if meta and self._cluster_start_pos: - meta.start_pos = self._cluster_start_pos - - result = Cluster(parse_meta=meta, side=side, name=name, code=code) - - for item in content: - if type(item) == Enum: - result.enums.append(item) - elif type(item) == Bitmap: - result.bitmaps.append(item) - elif type(item) == Event: - result.events.append(item) - elif type(item) == Attribute: - result.attributes.append(item) - elif type(item) == Struct: - result.structs.append(item) - elif type(item) == Command: - result.commands.append(item) - else: - raise Exception("UNKNOWN cluster content item: %r" % item) - - return result - - def idl(self, items): - idl = Idl() - - for item in items: - if type(item) == Enum: - idl.enums.append(item) - elif type(item) == Struct: - idl.structs.append(item) - elif type(item) == Cluster: - idl.clusters.append(item) - elif type(item) == Endpoint: - idl.endpoints.append(item) - else: - raise Exception("UNKNOWN idl content item: %r" % item) - - return idl - - def prefix_doc_comment(self): - print("TODO: prefix") - - # Processing of (potential-doc)-comments: - def c_comment(self, token: Token): - """Processes comments starting with "/*" """ - if token.value.startswith("/**"): - self.doc_comments.append(PrefixCppDocComment(token)) - - -class ParserWithLines: - def __init__(self, skip_meta: bool): - self.transformer = MatterIdlTransformer(skip_meta) - - # NOTE: LALR parser is fast. While Earley could parse more ambigous grammars, - # earley is much slower: - # - 0.39s LALR parsing of all-clusters-app.matter - # - 2.26s Earley parsing of the same thing. - # For this reason, every attempt should be made to make the grammar context free - self.parser = Lark.open( - 'matter_grammar.lark', rel_to=__file__, start='idl', parser='lalr', propagate_positions=True, - # separate callbacks to ignore from regular parsing (no tokens) - # while still getting notified about them - lexer_callbacks={ - 'C_COMMENT': self.transformer.c_comment, - } - ) - - def parse(self, file: str, file_name: Optional[str] = None): - idl = self.transformer.transform(self.parser.parse(file)) - idl.parse_file_name = file_name - - for comment in self.transformer.doc_comments: - comment.appply_to_idl(idl, file) - - return idl - - -def CreateParser(skip_meta: bool = False): - """ - Generates a parser that will process a ".matter" file into a IDL - """ - return ParserWithLines(skip_meta) - - -if __name__ == '__main__': - # This Parser is generally not intended to be run as a stand-alone binary. - # The ability to run is for debug and to print out the parsed AST. - import pprint - - import click - - # Supported log levels, mapping string values required for argument - # parsing into logging constants - __LOG_LEVELS__ = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warn': logging.WARN, - 'fatal': logging.FATAL, - } - - @click.command() - @click.option( - '--log-level', - default='INFO', - type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), - help='Determines the verbosity of script output.') - @click.argument('filename') - def main(log_level, filename=None): - logging.basicConfig( - level=__LOG_LEVELS__[log_level], - format='%(asctime)s %(levelname)-7s %(message)s', - ) - - logging.info("Starting to parse ...") - data = CreateParser().parse(open(filename).read(), file_name=filename) - logging.info("Parse completed") - - logging.info("Data:") - pprint.pp(data) - - main(auto_envvar_prefix='CHIP') diff --git a/scripts/py_matter_idl/matter_idl/matter_idl_types.py b/scripts/py_matter_idl/matter_idl/matter_idl_types.py deleted file mode 100644 index eb86e3ec4b99fc..00000000000000 --- a/scripts/py_matter_idl/matter_idl/matter_idl_types.py +++ /dev/null @@ -1,275 +0,0 @@ -import enum -from dataclasses import dataclass, field -from typing import List, Optional, Set, Union - -from lark.tree import Meta - - -# Information about parsing location for specific items -# Helpful when referencing data items in logs when processing -@dataclass -class ParseMetaData: - line: Optional[int] - column: Optional[int] - start_pos: Optional[int] - - def __init__(self, meta: Optional[Meta] = None, line: Optional[int] = None, column: Optional[int] = None, start_pos: Optional[int] = None): - if meta: - self.line = getattr(meta, 'line', None) - self.column = getattr(meta, 'column', None) - self.start_pos = getattr(meta, 'start_pos', None) - else: - self.line = line - self.column = column - self.start_pos = start_pos - - -class StructQuality(enum.Flag): - NONE = 0 - FABRIC_SCOPED = enum.auto() - - -class FieldQuality(enum.Flag): - NONE = 0 - OPTIONAL = enum.auto() - NULLABLE = enum.auto() - FABRIC_SENSITIVE = enum.auto() - - -class CommandQuality(enum.Flag): - NONE = 0 - TIMED_INVOKE = enum.auto() - FABRIC_SCOPED = enum.auto() - - -class AttributeQuality(enum.Flag): - NONE = 0 - READABLE = enum.auto() - WRITABLE = enum.auto() - NOSUBSCRIBE = enum.auto() - TIMED_WRITE = enum.auto() - - -class AttributeStorage(enum.Enum): - RAM = enum.auto() - PERSIST = enum.auto() - CALLBACK = enum.auto() - - -class EventPriority(enum.Enum): - DEBUG = enum.auto() - INFO = enum.auto() - CRITICAL = enum.auto() - - -class EventQuality(enum.Flag): - NONE = 0 - FABRIC_SENSITIVE = enum.auto() - - -class ClusterSide(enum.Enum): - CLIENT = enum.auto() - SERVER = enum.auto() - - -class StructTag(enum.Enum): - REQUEST = enum.auto() - RESPONSE = enum.auto() - - -class EndpointContentType(enum.Enum): - SERVER_CLUSTER = enum.auto() - CLIENT_BINDING = enum.auto() - - -class AccessPrivilege(enum.Enum): - VIEW = enum.auto() - OPERATE = enum.auto() - MANAGE = enum.auto() - ADMINISTER = enum.auto() - - -class AttributeOperation(enum.Enum): - READ = enum.auto() - WRITE = enum.auto() - - -@dataclass -class DataType: - name: str - - # Applies for strings (char or binary) - min_length: Optional[int] = None - max_length: Optional[int] = None - - # Applies for numbers - min_value: Optional[int] = None - max_value: Optional[int] = None - - -@dataclass -class Field: - data_type: DataType - code: int - name: str - is_list: bool = False - qualities: FieldQuality = FieldQuality.NONE - - @property - def is_optional(self): - return FieldQuality.OPTIONAL & self.qualities - - @property - def is_nullable(self): - return FieldQuality.NULLABLE & self.qualities - - -@dataclass -class Attribute: - definition: Field - qualities: AttributeQuality = AttributeQuality.NONE - readacl: AccessPrivilege = AccessPrivilege.VIEW - writeacl: AccessPrivilege = AccessPrivilege.OPERATE - default: Optional[Union[str, int]] = None - - @property - def is_readable(self): - return AttributeQuality.READABLE & self.qualities - - @property - def is_writable(self): - return AttributeQuality.WRITABLE & self.qualities - - @property - def is_subscribable(self): - return not (AttributeQuality.NOSUBSCRIBE & self.qualities) - - @property - def requires_timed_write(self): - return AttributeQuality.TIMED_WRITE & self.qualities - - -@dataclass -class Struct: - name: str - fields: List[Field] - tag: Optional[StructTag] = None - code: Optional[int] = None # for responses only - qualities: StructQuality = StructQuality.NONE - - -@dataclass -class Event: - priority: EventPriority - name: str - code: int - fields: List[Field] - readacl: AccessPrivilege = AccessPrivilege.VIEW - qualities: EventQuality = EventQuality.NONE - - @property - def is_fabric_sensitive(self): - return EventQuality.FABRIC_SENSITIVE & self.qualities - - -@dataclass -class ConstantEntry: - name: str - code: int - - -@dataclass -class Enum: - name: str - base_type: str - entries: List[ConstantEntry] - - -@dataclass -class Bitmap: - name: str - base_type: str - entries: List[ConstantEntry] - - -@dataclass -class Command: - name: str - code: int - input_param: Optional[str] - output_param: str - qualities: CommandQuality = CommandQuality.NONE - invokeacl: AccessPrivilege = AccessPrivilege.OPERATE - description: Optional[str] = None - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - @property - def is_timed_invoke(self): - return CommandQuality.TIMED_INVOKE & self.qualities - - -@dataclass -class Cluster: - side: ClusterSide - name: str - code: int - enums: List[Enum] = field(default_factory=list) - bitmaps: List[Bitmap] = field(default_factory=list) - events: List[Event] = field(default_factory=list) - attributes: List[Attribute] = field(default_factory=list) - structs: List[Struct] = field(default_factory=list) - commands: List[Command] = field(default_factory=list) - description: Optional[str] = None - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - -@dataclass -class AttributeInstantiation: - name: str - storage: AttributeStorage - default: Optional[Union[str, int, bool]] = None - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - -@dataclass -class ServerClusterInstantiation: - name: str - attributes: List[AttributeInstantiation] = field(default_factory=list) - events_emitted: Set[str] = field(default_factory=set) - - # Parsing meta data missing only when skip meta data is requested - parse_meta: Optional[ParseMetaData] = field(default=None) - - -@dataclass -class DeviceType: - name: str - code: int - version: int - - -@dataclass -class Endpoint: - number: int - device_types: List[DeviceType] = field(default_factory=list) - server_clusters: List[ServerClusterInstantiation] = field( - default_factory=list) - client_bindings: List[str] = field(default_factory=list) - - -@dataclass -class Idl: - # Enums and structs represent globally used items - enums: List[Enum] = field(default_factory=list) - structs: List[Struct] = field(default_factory=list) - clusters: List[Cluster] = field(default_factory=list) - endpoints: List[Endpoint] = field(default_factory=list) - - # IDL file name is available only if parsing provides a file name - parse_file_name: Optional[str] = field(default=None) diff --git a/scripts/py_matter_idl/matter_idl/test_generators.py b/scripts/py_matter_idl/matter_idl/test_generators.py deleted file mode 100755 index 31f95bbdfff0ac..00000000000000 --- a/scripts/py_matter_idl/matter_idl/test_generators.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import sys -import unittest -from dataclasses import dataclass, field -from typing import List - -import yaml - -try: - from matter_idl.matter_idl_parser import CreateParser -except ImportError: - - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.matter_idl_parser import CreateParser - -from matter_idl.generators import GeneratorStorage -from matter_idl.generators.cpp.application import CppApplicationGenerator -from matter_idl.generators.cpp.tlvmeta import TLVMetaDataGenerator -from matter_idl.generators.java import JavaClassGenerator, JavaJNIGenerator -from matter_idl.matter_idl_types import Idl - -TESTS_DIR = os.path.join(os.path.dirname(__file__), "tests") -REGENERATE_GOLDEN_IMAGES = False - - -@dataclass -class ExpectedOutput: - file_name: str - golden_path: str - - -@dataclass -class GeneratorTestCase: - input_idl: str - outputs: List[ExpectedOutput] = field(default_factory=list) - - def add_outputs(self, yaml_outputs_dict): - for file_name, golden_path in yaml_outputs_dict.items(): - self.outputs.append(ExpectedOutput( - file_name=file_name, golden_path=golden_path)) - - -class TestCaseStorage(GeneratorStorage): - def __init__(self, test_case: GeneratorTestCase, checker: unittest.TestCase): - super().__init__() - self.test_case = test_case - self.checker = checker - self.checked_files = set() - - def get_existing_data_path(self, relative_path: str): - for expected in self.test_case.outputs: - if expected.file_name == relative_path: - return os.path.join(TESTS_DIR, expected.golden_path) - - self.checker.fail("Expected output %s not found" % relative_path) - return None - - def get_existing_data(self, relative_path: str): - self.checked_files.add(relative_path) - - path = self.get_existing_data_path(relative_path) - if path: - with open(path, 'rt') as golden: - return golden.read() - - # This will attempt a new write, causing a unit test failure - self.checker.fail("Expected output %s not found" % relative_path) - return None - - def write_new_data(self, relative_path: str, content: str): - if REGENERATE_GOLDEN_IMAGES: - print("RE-GENERATING %r" % relative_path) - # Expect writing only on regeneration - with open(self.get_existing_data_path(relative_path), 'wt') as golden: - golden.write(content) - return - - # This is a unit test failure: we do NOT expect - # to write any new data - - # This will display actual diffs in the output files - self.checker.assertEqual( - self.get_existing_data(relative_path), content, "Content of %s" % relative_path) - - # Even if no diff, to be build system friendly, we do NOT expect any - # actual data writes. - raise AssertionError("Unexpected write to %s" % relative_path) - - -@dataclass -class GeneratorTest: - generator_name: str - test_cases: List[GeneratorTestCase] = field(default_factory=list) - - def add_test_cases(self, yaml_test_case_dict): - for idl_path, outputs in yaml_test_case_dict.items(): - test_case = GeneratorTestCase(input_idl=idl_path) - test_case.add_outputs(outputs) - self.test_cases.append(test_case) - - def _create_generator(self, storage: GeneratorStorage, idl: Idl): - if self.generator_name.lower() == 'java-jni': - return JavaJNIGenerator(storage, idl) - if self.generator_name.lower() == 'java-class': - return JavaClassGenerator(storage, idl) - if self.generator_name.lower() == 'cpp-app': - return CppApplicationGenerator(storage, idl) - if self.generator_name.lower() == 'cpp-tlvmeta': - return TLVMetaDataGenerator(storage, idl, table_name="clusters_meta") - if self.generator_name.lower() == 'custom-example-proto': - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '../examples'))) - from matter_idl_plugin import CustomGenerator - return CustomGenerator(storage, idl, package='com.matter.example.proto') - else: - raise Exception("Unknown generator for testing: %s", - self.generator_name.lower()) - - def run_test_cases(self, checker: unittest.TestCase): - for test in self.test_cases: - with checker.subTest(idl=test.input_idl): - storage = TestCaseStorage(test, checker) - with open(os.path.join(TESTS_DIR, test.input_idl), 'rt') as stream: - idl = CreateParser().parse(stream.read()) - - generator = self._create_generator(storage, idl) - generator.render(dry_run=False) - - checker.assertEqual(storage.checked_files, set( - map(lambda x: x.file_name, test.outputs))) - - -def build_tests(yaml_data) -> List[GeneratorTest]: - """ - Transforms the YAML dictonary (Dict[str, Dict[str, Dict[str,str]]]) into - a generator test structure. - """ - result = [] - - for key, test_cases in yaml_data.items(): - generator = GeneratorTest(generator_name=key) - generator.add_test_cases(test_cases) - result.append(generator) - - return result - - -class TestGenerators(unittest.TestCase): - def test_generators(self): - self.maxDiff = None - with open(os.path.join(TESTS_DIR, "available_tests.yaml"), 'rt') as stream: - yaml_data = yaml.safe_load(stream) - - for test in build_tests(yaml_data): - with self.subTest(generator=test.generator_name): - test.run_test_cases(self) - - -if __name__ == '__main__': - if 'IDL_GOLDEN_REGENERATE' in os.environ: - # run with `IDL_GOLDEN_REGENERATE=1` to cause a regeneration of test - # data. Then one can use `git diff` to see if the deltas make sense - REGENERATE_GOLDEN_IMAGES = True - unittest.main() diff --git a/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py b/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py deleted file mode 100755 index 2a3cfea87e76b1..00000000000000 --- a/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py +++ /dev/null @@ -1,601 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -try: - from matter_idl.matter_idl_parser import CreateParser -except ModuleNotFoundError: - import os - import sys - sys.path.append(os.path.dirname( - os.path.dirname(os.path.abspath(__file__)))) - - from matter_idl.matter_idl_parser import CreateParser - -import unittest - -from matter_idl.matter_idl_types import (AccessPrivilege, Attribute, AttributeInstantiation, AttributeQuality, AttributeStorage, - Bitmap, Cluster, ClusterSide, Command, CommandQuality, ConstantEntry, DataType, DeviceType, - Endpoint, Enum, Event, EventPriority, EventQuality, Field, FieldQuality, Idl, - ParseMetaData, ServerClusterInstantiation, Struct, StructQuality, StructTag) - - -def parseText(txt, skip_meta=True): - return CreateParser(skip_meta=skip_meta).parse(txt) - - -class TestParser(unittest.TestCase): - - def test_skips_comments(self): - actual = parseText(""" - // this is a single line comment - // repeated - - /* This is a C++ comment - and also whitespace should be ignored - */ - """) - expected = Idl() - - self.assertEqual(actual, expected) - - def test_global_enum(self): - actual = parseText(""" - enum GlobalEnum : ENUM8 { - kValue1 = 1; - kOther = 0x12; /* hex numbers tested sporadically */ - } - """) - - expected = Idl(enums=[ - Enum(name='GlobalEnum', base_type='ENUM8', - entries=[ - ConstantEntry(name="kValue1", code=1), - ConstantEntry(name="kOther", code=0x12), - ])] - ) - self.assertEqual(actual, expected) - - def test_global_struct(self): - actual = parseText(""" - struct Something { - CHAR_STRING astring = 1; - optional CLUSTER_ID idlist[] = 2; - nullable int valueThatIsNullable = 0x123; - char_string<123> sized_string = 222; - } - """) - - expected = Idl(structs=[ - Struct(name='Something', - fields=[ - Field( - data_type=DataType(name="CHAR_STRING"), code=1, name="astring", ), - Field(data_type=DataType(name="CLUSTER_ID"), code=2, name="idlist", - is_list=True, qualities=FieldQuality.OPTIONAL), - Field(data_type=DataType(name="int"), code=0x123, - name="valueThatIsNullable", qualities=FieldQuality.NULLABLE), - Field(data_type=DataType(name="char_string", max_length=123), - code=222, name="sized_string"), - ])] - ) - self.assertEqual(actual, expected) - - def test_fabric_scoped_struct(self): - actual = parseText(""" - fabric_scoped struct FabricStruct { - CHAR_STRING astring = 1; - optional CLUSTER_ID idlist[] = 2; - nullable fabric_sensitive int nullablesensitive = 0x123; - } - """) - - expected = Idl(structs=[ - Struct(name='FabricStruct', - qualities=StructQuality.FABRIC_SCOPED, - fields=[ - Field( - data_type=DataType(name="CHAR_STRING"), code=1, name="astring", ), - Field(data_type=DataType(name="CLUSTER_ID"), code=2, name="idlist", - is_list=True, qualities=FieldQuality.OPTIONAL), - Field(data_type=DataType(name="int"), code=0x123, name="nullablesensitive", - qualities=FieldQuality.NULLABLE | FieldQuality.FABRIC_SENSITIVE), - ])] - ) - self.assertEqual(actual, expected) - - def test_cluster_attribute(self): - actual = parseText(""" - server cluster MyCluster = 0x321 { - readonly attribute int8u roAttr = 1; - attribute int32u rwAttr[] = 123; - readonly nosubscribe attribute int8s nosub[] = 0xaa; - readonly attribute nullable int8s isNullable = 0xab; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=0x321, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE, definition=Field( - data_type=DataType(name="int8u"), code=1, name="roAttr")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int32u"), code=123, name="rwAttr", is_list=True)), - Attribute(qualities=AttributeQuality.NOSUBSCRIBE | AttributeQuality.READABLE, definition=Field( - data_type=DataType(name="int8s"), code=0xAA, name="nosub", is_list=True)), - Attribute(qualities=AttributeQuality.READABLE, definition=Field( - data_type=DataType(name="int8s"), code=0xAB, name="isNullable", qualities=FieldQuality.NULLABLE)), - ] - )]) - self.assertEqual(actual, expected) - - def test_doc_comments(self): - actual = parseText(""" - /** Documentation for MyCluster */ - server cluster MyCluster = 0x321 { - } - - /** Documentation for MyCluster #2 */ - client cluster MyCluster = 0x321 { - /* NOT a doc comment */ - command WithoutArg(): DefaultSuccess = 123; - - /** Some command doc comment */ - command InOutStuff(InParam): OutParam = 222; - } - """, skip_meta=False) - - # meta_data may not match but is required for doc comments. Clean it up - - # Metadata parsing varies line/column, so only check doc comments - self.assertEqual( - actual.clusters[0].description, "Documentation for MyCluster") - self.assertEqual( - actual.clusters[1].description, "Documentation for MyCluster #2") - self.assertIsNone(actual.clusters[1].commands[0].description) - self.assertEqual( - actual.clusters[1].commands[1].description, "Some command doc comment") - - def test_sized_attribute(self): - actual = parseText(""" - server cluster MyCluster = 1 { - attribute char_string<11> attr1 = 1; - attribute octet_string<33> attr2[] = 2; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=1, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="char_string", max_length=11), code=1, name="attr1")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="octet_string", max_length=33), code=2, name="attr2", is_list=True)), - ] - )]) - self.assertEqual(actual, expected) - - def test_timed_attributes(self): - actual = parseText(""" - server cluster MyCluster = 1 { - attribute int32u attr1 = 1; - timedwrite attribute int32u attr2 = 2; - attribute int32u attr3 = 3; - timedwrite attribute octet_string<44> attr4[] = 4; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=1, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int32u"), code=1, name="attr1")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE | AttributeQuality.TIMED_WRITE, definition=Field( - data_type=DataType(name="int32u"), code=2, name="attr2")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int32u"), code=3, name="attr3")), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE | AttributeQuality.TIMED_WRITE, definition=Field( - data_type=DataType(name="octet_string", max_length=44), code=4, name="attr4", is_list=True)), - ] - )]) - self.assertEqual(actual, expected) - - def test_attribute_access(self): - actual = parseText(""" - server cluster MyCluster = 1 { - attribute int8s attr1 = 1; - attribute access() int8s attr2 = 2; - attribute access(read: manage) int8s attr3 = 3; - attribute access(write: administer) int8s attr4 = 4; - attribute access(read: operate, write: manage) int8s attr5 = 5; - } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="MyCluster", - code=1, - attributes=[ - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=1, name="attr1"), - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=2, name="attr2"), - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=3, name="attr3"), - readacl=AccessPrivilege.MANAGE - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=4, name="attr4"), - writeacl=AccessPrivilege.ADMINISTER - ), - Attribute(qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, definition=Field( - data_type=DataType(name="int8s"), code=5, name="attr5"), - readacl=AccessPrivilege.OPERATE, - writeacl=AccessPrivilege.MANAGE - ), - ] - )]) - self.assertEqual(actual, expected) - - def test_cluster_commands(self): - actual = parseText(""" - server cluster WithCommands = 1 { - struct FreeStruct {} - request struct InParam {} - response struct OutParam = 223 {} - - command WithoutArg(): DefaultSuccess = 123; - command InOutStuff(InParam): OutParam = 222; - timed command TimedCommand(InParam): DefaultSuccess = 0xab; - fabric command FabricScopedCommand(InParam): DefaultSuccess = 0xac; - fabric Timed command FabricScopedTimedCommand(InParam): DefaultSuccess = 0xad; - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="WithCommands", - code=1, - structs=[ - Struct(name="FreeStruct", fields=[]), - Struct(name="InParam", fields=[], - tag=StructTag.REQUEST), - Struct(name="OutParam", fields=[], - tag=StructTag.RESPONSE, code=223), - ], - commands=[ - Command(name="WithoutArg", code=123, - input_param=None, output_param="DefaultSuccess"), - Command(name="InOutStuff", code=222, - input_param="InParam", output_param="OutParam"), - Command(name="TimedCommand", code=0xab, - input_param="InParam", output_param="DefaultSuccess", - qualities=CommandQuality.TIMED_INVOKE), - Command(name="FabricScopedCommand", code=0xac, - input_param="InParam", output_param="DefaultSuccess", - qualities=CommandQuality.FABRIC_SCOPED), - Command(name="FabricScopedTimedCommand", code=0xad, - input_param="InParam", output_param="DefaultSuccess", - qualities=CommandQuality.TIMED_INVOKE | CommandQuality.FABRIC_SCOPED), - ], - )]) - self.assertEqual(actual, expected) - - def test_cluster_command_access(self): - actual = parseText(""" - server cluster WithCommands = 1 { - request struct InParam {} - response struct OutParam = 4 {} - - command WithoutArg(): DefaultSuccess = 1; - timed command access(invoke: manage) TimedCommand(InParam): OutParam = 2; - command access(invoke: administer) OutOnly(): OutParam = 3; - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, - name="WithCommands", - code=1, - structs=[ - Struct(name="InParam", fields=[], - tag=StructTag.REQUEST), - Struct(name="OutParam", fields=[], - tag=StructTag.RESPONSE, code=4), - ], - commands=[ - Command(name="WithoutArg", code=1, - invokeacl=AccessPrivilege.OPERATE, - input_param=None, output_param="DefaultSuccess"), - Command(name="TimedCommand", code=2, - input_param="InParam", output_param="OutParam", - invokeacl=AccessPrivilege.MANAGE, - qualities=CommandQuality.TIMED_INVOKE), - Command(name="OutOnly", code=3, - input_param=None, output_param="OutParam", - invokeacl=AccessPrivilege.ADMINISTER, - ), - ], - )]) - self.assertEqual(actual, expected) - - def test_cluster_enum(self): - actual = parseText(""" - client cluster WithEnums = 0xab { - enum TestEnum : ENUM16 { - A = 0x123; - B = 0x234; - } - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="WithEnums", - code=0xab, - enums=[ - Enum(name="TestEnum", base_type="ENUM16", - entries=[ - ConstantEntry(name="A", code=0x123), - ConstantEntry(name="B", code=0x234), - ])], - )]) - self.assertEqual(actual, expected) - - def test_cluster_bitmap(self): - actual = parseText(""" - client cluster Test = 0xab { - bitmap TestBitmap : BITMAP32 { - kFirst = 0x1; - kSecond = 0x2; - } - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="Test", - code=0xab, - bitmaps=[ - Bitmap(name="TestBitmap", base_type="BITMAP32", - entries=[ - ConstantEntry(name="kFirst", code=0x1), - ConstantEntry(name="kSecond", code=0x2), - ])], - )]) - self.assertEqual(actual, expected) - - def test_cluster_events(self): - actual = parseText(""" - client cluster EventTester = 0x123 { - critical event StartUp = 0 { - INT32U softwareVersion = 0; - } - info event Hello = 1 {} - debug event GoodBye = 2 {} - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="EventTester", - code=0x123, - events=[ - Event(priority=EventPriority.CRITICAL, name="StartUp", code=0, fields=[ - Field(data_type=DataType(name="INT32U"), - code=0, name="softwareVersion"), - ]), - Event(priority=EventPriority.INFO, - name="Hello", code=1, fields=[]), - Event(priority=EventPriority.DEBUG, - name="GoodBye", code=2, fields=[]), - ])]) - self.assertEqual(actual, expected) - - def test_cluster_event_acl(self): - actual = parseText(""" - client cluster EventTester = 0x123 { - info event Hello = 1 {} - debug event access(read: manage) GoodBye = 2 {} - debug event access(read: administer) AdminEvent = 3 {} - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="EventTester", - code=0x123, - events=[ - Event(priority=EventPriority.INFO, readacl=AccessPrivilege.VIEW, - name="Hello", code=1, fields=[]), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.MANAGE, - name="GoodBye", code=2, fields=[]), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.ADMINISTER, - name="AdminEvent", code=3, fields=[]), - ])]) - self.assertEqual(actual, expected) - - def test_fabric_sensitive_event(self): - actual = parseText(""" - client cluster EventTester = 0x123 { - fabric_sensitive info event Hello = 1 {} - fabric_sensitive debug event access(read: manage) GoodBye = 2 {} - fabric_sensitive debug event access(read: administer) AdminEvent = 3 {} - } - """) - expected = Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name="EventTester", - code=0x123, - events=[ - Event(priority=EventPriority.INFO, readacl=AccessPrivilege.VIEW, - name="Hello", code=1, fields=[], qualities=EventQuality.FABRIC_SENSITIVE), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.MANAGE, - name="GoodBye", code=2, fields=[], qualities=EventQuality.FABRIC_SENSITIVE), - Event(priority=EventPriority.DEBUG, readacl=AccessPrivilege.ADMINISTER, - name="AdminEvent", code=3, fields=[], qualities=EventQuality.FABRIC_SENSITIVE), - ])]) - self.assertEqual(actual, expected) - - def test_parsing_metadata_for_cluster(self): - actual = CreateParser(skip_meta=False).parse(""" -server cluster A = 1 { /* Test comment */ } - -// some empty lines and then indented - client cluster B = 2 { } - """) - - expected = Idl(clusters=[ - Cluster(parse_meta=ParseMetaData(line=2, column=1, start_pos=1), - side=ClusterSide.SERVER, name="A", code=1), - Cluster(parse_meta=ParseMetaData(line=5, column=4, start_pos=87), - side=ClusterSide.CLIENT, name="B", code=2), - ]) - self.assertEqual(actual, expected) - - def test_multiple_clusters(self): - actual = parseText(""" - server cluster A = 1 { /* Test comment */ } - client cluster B = 2 { } - client cluster C = 3 { } - """) - - expected = Idl(clusters=[ - Cluster(side=ClusterSide.SERVER, name="A", code=1), - Cluster(side=ClusterSide.CLIENT, name="B", code=2), - Cluster(side=ClusterSide.CLIENT, name="C", code=3), - ]) - self.assertEqual(actual, expected) - - def test_endpoints(self): - actual = parseText(""" - endpoint 12 { - device type foo = 123, version 1; - device type bar = 0xFF, version 2; - - server cluster Foo { } - server cluster Bar { } - binding cluster Bar; - binding cluster Test; - } - """) - - expected = Idl(endpoints=[Endpoint(number=12, - device_types=[ - DeviceType( - name="foo", code=123, version=1), - DeviceType( - name="bar", code=0xFF, version=2), - ], - server_clusters=[ - ServerClusterInstantiation( - name="Foo"), - ServerClusterInstantiation( - name="Bar"), - ], - client_bindings=["Bar", "Test"],) - ]) - self.assertEqual(actual, expected) - - def test_cluster_instantiation(self): - actual = parseText(""" - endpoint 3 { - server cluster Example { - ram attribute inRamZero; - ram attribute inRamWithDefault default=123; - persist attribute inNVMNoDef; - persist attribute inNVMStr default="abc"; - persist attribute inNVMWithDefault default = -33; - callback attribute hasCallbackBool default = true; - } - } - """) - - expected = Idl(endpoints=[Endpoint(number=3, - server_clusters=[ - ServerClusterInstantiation(name="Example", attributes=[ - AttributeInstantiation( - name='inRamZero', storage=AttributeStorage.RAM), - AttributeInstantiation(name='inRamWithDefault', - storage=AttributeStorage.RAM, default=123), - AttributeInstantiation( - name='inNVMNoDef', storage=AttributeStorage.PERSIST), - AttributeInstantiation( - name='inNVMStr', storage=AttributeStorage.PERSIST, default="abc"), - AttributeInstantiation(name='inNVMWithDefault', - storage=AttributeStorage.PERSIST, default=-33), - AttributeInstantiation(name='hasCallbackBool', - storage=AttributeStorage.CALLBACK, default=True), - ]), - ], - client_bindings=[],) - ]) - self.assertEqual(actual, expected) - - def test_multi_endpoints(self): - actual = parseText(""" - endpoint 1 {} - endpoint 2 {} - endpoint 0xa {} - endpoint 100 {} - """) - - expected = Idl(endpoints=[ - Endpoint(number=1), - Endpoint(number=2), - Endpoint(number=10), - Endpoint(number=100), - ]) - self.assertEqual(actual, expected) - - def test_emits_events(self): - actual = parseText(""" - endpoint 1 { - server cluster Example {} - } - endpoint 2 { - server cluster Example { - emits event FooBar; - emits event SomeNewEvent; - } - server cluster AnotherExample { - emits event StartUp; - emits event ShutDown; - } - } - """) - - expected = Idl(endpoints=[ - Endpoint(number=1, server_clusters=[ - ServerClusterInstantiation(name="Example")]), - Endpoint(number=2, server_clusters=[ - ServerClusterInstantiation(name="Example", events_emitted={ - "FooBar", "SomeNewEvent"}), - ServerClusterInstantiation(name="AnotherExample", events_emitted={ - "StartUp", "ShutDown"}), - ]) - ]) - - self.assertEqual(actual, expected) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/py_matter_idl/matter_idl/test_xml_parser.py b/scripts/py_matter_idl/matter_idl/test_xml_parser.py deleted file mode 100755 index d8c7bb0a6c5dc1..00000000000000 --- a/scripts/py_matter_idl/matter_idl/test_xml_parser.py +++ /dev/null @@ -1,399 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import io -import unittest -from typing import List, Union - -try: - from matter_idl.zapxml import ParseSource, ParseXmls -except ImportError: - import os - import sys - - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.zapxml import ParseSource, ParseXmls - -from matter_idl.matter_idl_types import (AccessPrivilege, Attribute, AttributeQuality, Bitmap, Cluster, ClusterSide, Command, - ConstantEntry, DataType, Enum, Event, EventPriority, EventQuality, Field, FieldQuality, - Idl, Struct, StructQuality, StructTag) - - -def XmlToIdl(what: Union[str, List[str]]) -> Idl: - if not isinstance(what, list): - what = [what] - - sources = [] - for idx, txt in enumerate(what): - sources.append(ParseSource(source=io.StringIO( - txt), name=("Input %d" % (idx + 1)))) - - return ParseXmls(sources, include_meta_data=False) - - -class TestXmlParser(unittest.TestCase): - - def testEmptyInput(self): - idl = XmlToIdl('') - self.assertEqual(idl, Idl()) - - def testCluster(self): - idl = XmlToIdl(''' - - - - Test - 0x1234 - Test - - SomeCharStringAttribute - - SomeIntAttribute - - - AttributeWithAccess - - - - - - This is just a test: client to server - - - - - - - Reply from server - - - - - - ''') - self.assertEqual(idl, - Idl(clusters=[ - Cluster( - side=ClusterSide.CLIENT, - name='Test', - code=0x1234, - description="Test", - attributes=[ - Attribute(definition=Field( - data_type=DataType( - name='CHAR_STRING', min_length=2, max_length=10), - code=10, - name='SomeCharStringAttribute', - qualities=FieldQuality.NULLABLE), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, writeacl=AccessPrivilege.OPERATE), - - Attribute(definition=Field( - data_type=DataType( - name='INT32U', min_value=0, max_value=2), - code=11, - name='SomeIntAttribute', - qualities=FieldQuality.NULLABLE), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, writeacl=AccessPrivilege.OPERATE), - - Attribute(definition=Field( - data_type=DataType( - name='INT8U', min_value=0, max_value=10), - code=22, name='AttributeWithAccess', - qualities=FieldQuality.OPTIONAL), - qualities=AttributeQuality.READABLE | AttributeQuality.WRITABLE, - readacl=AccessPrivilege.OPERATE, - writeacl=AccessPrivilege.MANAGE) - ], - structs=[ - Struct(name='GetSomeDataRequest', - fields=[ - Field(data_type=DataType( - name='INT8U'), code=0, name='firstInput'), - Field(data_type=DataType( - name='INT16U'), code=1, name='secondInput') - ], - tag=StructTag.REQUEST), - Struct(name='GetSomeDataResponse', - fields=[ - Field(data_type=DataType(name='INT8U'), code=0, - name='dataPoint1'), - Field(data_type=DataType(name='INT8U'), code=1, name='dataPoint2', - qualities=FieldQuality.OPTIONAL) - ], - tag=StructTag.RESPONSE, code=0x44) - ], - commands=[ - Command(name='GetSomeData', code=33, - input_param='GetSomeDataRequest', output_param='GetSomeDataResponse', - description='This is just a test: client to server', - invokeacl=AccessPrivilege.ADMINISTER) - ]) - ])) - - def testBitmap(self): - idl = XmlToIdl(''' - - Test10x0001 - Test20x0002 - - - - - - - - - - ''') - bitmap = Bitmap( - name='MyBitmap', - base_type='BITMAP32', - entries=[ - ConstantEntry(name='BitmapMask1', code=1), - ConstantEntry(name='BitmapMask2', code=2), - ConstantEntry(name='BitmapMask3', code=4) - ]) - - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name='Test1', code=1, bitmaps=[bitmap]), - Cluster(side=ClusterSide.CLIENT, - name='Test2', code=2, bitmaps=[bitmap]), - ])) - - def testFabricScopedAndSensitive(self): - idl = XmlToIdl(''' - - - Test - 0x0001 - - - This is a test event - - - - - - - - - - - - - - - - ''') - self.assertEqual(idl, - Idl(clusters=[Cluster(side=ClusterSide.CLIENT, - name='Test', - code=1, - events=[Event(priority=EventPriority.INFO, - name='FabricEvent', - code=0x1234, - fields=[Field(data_type=DataType(name='node_id'), - code=1, - name='AdminNodeID', - qualities=FieldQuality.NULLABLE)], - readacl=AccessPrivilege.ADMINISTER, - qualities=EventQuality.FABRIC_SENSITIVE)], - structs=[Struct(name='FabricStruct', - fields=[Field(data_type=DataType(name='int32u'), - code=1, - name='Field1', - qualities=FieldQuality.FABRIC_SENSITIVE), - Field(data_type=DataType(name='int32u'), - code=3, - name='Field3', - qualities=FieldQuality.FABRIC_SENSITIVE), - Field(data_type=DataType(name='int32u', - min_length=None, - max_length=None, - min_value=None, - max_value=None), - code=10, - name='Field10')], - qualities=StructQuality.FABRIC_SCOPED)], - )])) - - def testEnum(self): - idl = XmlToIdl(''' - - Test110 - Test220 - - - - - - - - - - - - - - - - - - - ''') - e1 = Enum( - name='GlobalEnum', - base_type="ENUM8", - entries=[ - ConstantEntry(name="First", code=0), - ConstantEntry(name="Second", code=1), - ] - ) - e2 = Enum( - name='OneCluster', - base_type="ENUM8", - entries=[ - ConstantEntry(name="Three", code=3), - ] - ) - e3 = Enum( - name='TwoClusters', - base_type="ENUM8", - entries=[ - ConstantEntry(name="Big", code=100), - ConstantEntry(name="Bigger", code=2000), - ] - ) - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name='Test1', code=10, enums=[e2, e3]), - Cluster(side=ClusterSide.CLIENT, - name='Test2', code=20, enums=[e3])], - enums=[e1], - )) - - def testStruct(self): - idl = XmlToIdl(''' - - Test10x000A - - Test2 - 20 - - - FabricAttribute - - - - - - - - - - - - ''') - struct = Struct( - name='SomeStruct', - qualities=StructQuality.FABRIC_SCOPED, - fields=[ - Field(data_type=DataType(name='int16u'), - code=0, name='FirstMember'), - Field(data_type=DataType(name='int32u'), - code=1, name='SecondMember') - ] - ) - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, - name='Test1', code=10, structs=[struct]), - Cluster(side=ClusterSide.CLIENT, name='Test2', code=20, - structs=[struct], - attributes=[ - Attribute( - definition=Field( - data_type=DataType( - name='SomeStruct'), - code=123, - name='FabricAttribute', - qualities=FieldQuality.NULLABLE - ), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE)]), ])) - - def testSkipsNotProcessedFields(self): - # Zap has extra fields that are generally not processed - # This includes such fields and ansures we do not consider them - idl = XmlToIdl(''' - - - - - Window Covering - Closures - 0x0102 - WINDOW_COVERING_CLUSTER - Provides an interface for controlling and adjusting automatic window coverings. - - - - - - - - - true - true - - - - Type - - - ''') - self.assertEqual(idl, - Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, name='WindowCovering', code=0x102, - description='Provides an interface for controlling and adjusting automatic window coverings. ', - structs=[], - attributes=[ - Attribute( - definition=Field( - data_type=DataType( - name='Type', min_value=0, max_value=9), - code=0, - name='Type', - ), - qualities=AttributeQuality.READABLE, - readacl=AccessPrivilege.VIEW, - writeacl=AccessPrivilege.OPERATE)]), ])) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/py_matter_idl/matter_idl/tests/available_tests.yaml b/scripts/py_matter_idl/matter_idl/tests/available_tests.yaml deleted file mode 100644 index de117835790d10..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/available_tests.yaml +++ /dev/null @@ -1,88 +0,0 @@ -# These are the available tests for generators -# -# General format is: -# -# -# : -# -# Where -# - generator is the type of generator to use -# - input_file is the input IDL -# - output_file/golden_path are the expected output file names -# and the expected content for those output files. -java-jni: - inputs/simple_attribute.matter: - jni/MyClusterClient-ReadImpl.cpp: outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp - jni/MyClusterClient-InvokeSubscribeImpl.cpp: outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp - jni/CHIPCallbackTypes.h: outputs/simple_attribute/jni/CHIPCallbackTypes.h - jni/CHIPReadCallbacks.h: outputs/simple_attribute/jni/CHIPReadReadCallbacks.h - jni/CHIPGlobalCallbacks.cpp: outputs/shared/jni/CHIPGlobalCallbacks.cpp - - inputs/global_struct_attribute.matter: - jni/DemoClusterClient-ReadImpl.cpp: outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp - jni/DemoClusterClient-InvokeSubscribeImpl.cpp: outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp - jni/CHIPCallbackTypes.h: outputs/global_struct_attribute/jni/CHIPCallbackTypes.h - jni/CHIPReadCallbacks.h: outputs/global_struct_attribute/jni/CHIPReadReadCallbacks.h - jni/CHIPGlobalCallbacks.cpp: outputs/shared/jni/CHIPGlobalCallbacks.cpp - - inputs/cluster_struct_attribute.matter: - jni/DemoClusterClient-ReadImpl.cpp: outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp - jni/DemoClusterClient-InvokeSubscribeImpl.cpp: outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp - jni/CHIPCallbackTypes.h: outputs/cluster_struct_attribute/jni/CHIPCallbackTypes.h - jni/CHIPReadCallbacks.h: outputs/cluster_struct_attribute/jni/CHIPReadReadCallbacks.h - jni/CHIPGlobalCallbacks.cpp: outputs/shared/jni/CHIPGlobalCallbacks.cpp - - inputs/several_clusters.matter: - jni/FirstClient-ReadImpl.cpp: outputs/several_clusters/jni/FirstClient-ReadImpl.cpp - jni/SecondClient-ReadImpl.cpp: outputs/several_clusters/jni/SecondClient-ReadImpl.cpp - jni/ThirdClient-ReadImpl.cpp: outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp - jni/FirstClient-InvokeSubscribeImpl.cpp: outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp - jni/SecondClient-InvokeSubscribeImpl.cpp: outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp - jni/ThirdClient-InvokeSubscribeImpl.cpp: outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp - jni/CHIPCallbackTypes.h: outputs/several_clusters/jni/CHIPCallbackTypes.h - jni/CHIPReadCallbacks.h: outputs/several_clusters/jni/CHIPReadReadCallbacks.h - jni/CHIPGlobalCallbacks.cpp: outputs/shared/jni/CHIPGlobalCallbacks.cpp - - inputs/optional_argument.matter: - jni/MyClusterClient-ReadImpl.cpp: outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp - jni/MyClusterClient-InvokeSubscribeImpl.cpp: outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp - jni/CHIPCallbackTypes.h: outputs/optional_argument/jni/CHIPCallbackTypes.h - jni/CHIPReadCallbacks.h: outputs/optional_argument/jni/CHIPReadReadCallbacks.h - jni/CHIPGlobalCallbacks.cpp: outputs/shared/jni/CHIPGlobalCallbacks.cpp - -java-class: - inputs/several_clusters.matter: - java/chip/devicecontroller/cluster/structs/SecondClusterFabricDescriptorStruct.kt: outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt - java/chip/devicecontroller/ClusterWriteMapping.java: outputs/several_clusters/java/ClusterWriteMapping.java - java/chip/devicecontroller/ClusterReadMapping.java: outputs/several_clusters/java/ClusterReadMapping.java - java/chip/devicecontroller/ClusterIDMapping.java: outputs/several_clusters/java/ClusterIDMapping.java - -cpp-app: - inputs/several_clusters.matter: - app/PluginApplicationCallbacks.h: outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h - app/callback-stub.cpp: outputs/several_clusters/cpp-app/callback-stub.cpp - - inputs/large_all_clusters_app.matter: - app/PluginApplicationCallbacks.h: outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h - app/callback-stub.cpp: outputs/large_all_clusters_app/cpp-app/callback-stub.cpp - - inputs/large_lighting_app.matter: - app/PluginApplicationCallbacks.h: outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h - app/callback-stub.cpp: outputs/large_lighting_app/cpp-app/callback-stub.cpp - -cpp-tlvmeta: - inputs/cluster_with_commands.matter: - tlv/meta/clusters_meta.cpp: outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.cpp - tlv/meta/clusters_meta.h: outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.h - inputs/cluster_struct_attribute.matter: - tlv/meta/clusters_meta.cpp: outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.cpp - tlv/meta/clusters_meta.h: outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.h - -custom-example-proto: - inputs/several_clusters.matter: - proto/first_cluster.proto: outputs/proto/first_cluster.proto - proto/second_cluster.proto: outputs/proto/second_cluster.proto - proto/third_cluster.proto: outputs/proto/third_cluster.proto - - inputs/large_all_clusters_app.matter: - proto/ota_software_update_provider_cluster.proto: outputs/proto/ota_software_update_provider_cluster.proto diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter deleted file mode 100644 index 4edee6bd80b69a..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter +++ /dev/null @@ -1,11 +0,0 @@ -client cluster DemoCluster = 10 { - request struct ArmFailSafeRequest { - INT16U expiryLengthSeconds = 0; - INT64U breadcrumb = 1; - INT32U timeoutMs = 2; - } - - attribute ArmFailSafeRequest singleFailSafe = 5; - attribute ArmFailSafeRequest armFailsafes[] = 100; -} - diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_with_commands.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_with_commands.matter deleted file mode 100644 index d978642f26ef1b..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_with_commands.matter +++ /dev/null @@ -1,43 +0,0 @@ - -server cluster OnOff = 6 { - enum OnOffDelayedAllOffEffectVariant : ENUM8 { - kFadeToOffIn0p8Seconds = 0; - kNoFade = 1; - k50PercentDimDownIn0p8SecondsThenFadeToOffIn12Seconds = 2; - } - - enum OnOffDyingLightEffectVariant : ENUM8 { - k20PercenterDimUpIn0p5SecondsThenFadeToOffIn1Second = 0; - } - - enum OnOffEffectIdentifier : ENUM8 { - kDelayedAllOff = 0; - kDyingLight = 1; - } - - enum OnOffStartUpOnOff : ENUM8 { - kOff = 0; - kOn = 1; - kTogglePreviousOnOff = 2; - } - - bitmap OnOffControl : BITMAP8 { - kAcceptOnlyWhenOn = 0x1; - } - - bitmap OnOffFeature : BITMAP32 { - kLighting = 0x1; - } - - bitmap ScenesFeature : BITMAP32 { - kSceneNames = 0x1; - } - - readonly attribute boolean onOff = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command Off(): DefaultSuccess = 0; - command On(): DefaultSuccess = 1; - command Toggle(): DefaultSuccess = 2; -} diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter deleted file mode 100644 index bb325d28501d67..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter +++ /dev/null @@ -1,9 +0,0 @@ -struct LabelStruct { - CHAR_STRING<16> label = 0; - CHAR_STRING<16> value = 1; -} - -client cluster DemoCluster = 0x12 { - attribute LabelStruct singleLabel = 0x20; - attribute LabelStruct someLabels[] = 0x21; -} diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter deleted file mode 100644 index cc0c601f7dd505..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter +++ /dev/null @@ -1,4865 +0,0 @@ -// This IDL was generated automatically by ZAP. -// It is for view/code review purposes only. - -struct LabelStruct { - char_string<16> label = 0; - char_string<16> value = 1; -} - -server cluster Identify = 3 { - enum IdentifyEffectIdentifier : ENUM8 { - kBlink = 0; - kBreathe = 1; - kOkay = 2; - kChannelChange = 11; - kFinishEffect = 254; - kStopEffect = 255; - } - - enum IdentifyEffectVariant : ENUM8 { - kDefault = 0; - } - - enum IdentifyIdentifyType : ENUM8 { - kNone = 0; - kVisibleLight = 1; - kVisibleLED = 2; - kAudibleBeep = 3; - kDisplay = 4; - kActuator = 5; - } - - attribute int16u identifyTime = 0; - readonly attribute enum8 identifyType = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct IdentifyRequest { - INT16U identifyTime = 0; - } - - request struct TriggerEffectRequest { - IdentifyEffectIdentifier effectIdentifier = 0; - IdentifyEffectVariant effectVariant = 1; - } - - command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; - command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; -} - -server cluster Groups = 4 { - bitmap GroupClusterFeature : BITMAP32 { - kGroupNames = 0x1; - } - - readonly attribute bitmap8 nameSupport = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AddGroupRequest { - group_id groupId = 0; - CHAR_STRING groupName = 1; - } - - request struct ViewGroupRequest { - group_id groupId = 0; - } - - request struct GetGroupMembershipRequest { - group_id groupList[] = 0; - } - - request struct RemoveGroupRequest { - group_id groupId = 0; - } - - request struct AddGroupIfIdentifyingRequest { - group_id groupId = 0; - CHAR_STRING groupName = 1; - } - - response struct AddGroupResponse = 0 { - ENUM8 status = 0; - group_id groupId = 1; - } - - response struct ViewGroupResponse = 1 { - ENUM8 status = 0; - group_id groupId = 1; - CHAR_STRING groupName = 2; - } - - response struct GetGroupMembershipResponse = 2 { - nullable INT8U capacity = 0; - group_id groupList[] = 1; - } - - response struct RemoveGroupResponse = 3 { - ENUM8 status = 0; - group_id groupId = 1; - } - - fabric command access(invoke: manage) AddGroup(AddGroupRequest): AddGroupResponse = 0; - fabric command ViewGroup(ViewGroupRequest): ViewGroupResponse = 1; - fabric command GetGroupMembership(GetGroupMembershipRequest): GetGroupMembershipResponse = 2; - fabric command access(invoke: manage) RemoveGroup(RemoveGroupRequest): RemoveGroupResponse = 3; - fabric command access(invoke: manage) RemoveAllGroups(): DefaultSuccess = 4; - fabric command access(invoke: manage) AddGroupIfIdentifying(AddGroupIfIdentifyingRequest): DefaultSuccess = 5; -} - -server cluster Scenes = 5 { - bitmap ScenesCopyMode : BITMAP8 { - kCopyAllScenes = 0x1; - } - - struct ExtensionFieldSet { - cluster_id clusterId = 0; - AttributeValuePair attributeValueList[] = 1; - } - - struct AttributeValuePair { - optional attrib_id attributeId = 0; - int8u attributeValue[] = 1; - } - - readonly attribute int8u sceneCount = 0; - readonly attribute int8u currentScene = 1; - readonly attribute group_id currentGroup = 2; - readonly attribute boolean sceneValid = 3; - readonly attribute bitmap8 nameSupport = 4; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AddSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; - INT16U transitionTime = 2; - CHAR_STRING sceneName = 3; - ExtensionFieldSet extensionFieldSets[] = 4; - } - - request struct ViewSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; - } - - request struct RemoveSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; - } - - request struct RemoveAllScenesRequest { - group_id groupId = 0; - } - - request struct StoreSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; - } - - request struct RecallSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; - optional nullable INT16U transitionTime = 2; - } - - request struct GetSceneMembershipRequest { - group_id groupId = 0; - } - - response struct AddSceneResponse = 0 { - ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; - } - - response struct ViewSceneResponse = 1 { - ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; - optional INT16U transitionTime = 3; - optional CHAR_STRING sceneName = 4; - optional ExtensionFieldSet extensionFieldSets[] = 5; - } - - response struct RemoveSceneResponse = 2 { - ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; - } - - response struct RemoveAllScenesResponse = 3 { - ENUM8 status = 0; - group_id groupId = 1; - } - - response struct StoreSceneResponse = 4 { - ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; - } - - response struct GetSceneMembershipResponse = 6 { - ENUM8 status = 0; - nullable INT8U capacity = 1; - group_id groupId = 2; - optional INT8U sceneList[] = 3; - } - - fabric command access(invoke: manage) AddScene(AddSceneRequest): AddSceneResponse = 0; - fabric command ViewScene(ViewSceneRequest): ViewSceneResponse = 1; - fabric command access(invoke: manage) RemoveScene(RemoveSceneRequest): RemoveSceneResponse = 2; - fabric command access(invoke: manage) RemoveAllScenes(RemoveAllScenesRequest): RemoveAllScenesResponse = 3; - fabric command access(invoke: manage) StoreScene(StoreSceneRequest): StoreSceneResponse = 4; - fabric command RecallScene(RecallSceneRequest): DefaultSuccess = 5; - fabric command GetSceneMembership(GetSceneMembershipRequest): GetSceneMembershipResponse = 6; -} - -server cluster OnOff = 6 { - enum OnOffDelayedAllOffEffectVariant : ENUM8 { - kFadeToOffIn0p8Seconds = 0; - kNoFade = 1; - k50PercentDimDownIn0p8SecondsThenFadeToOffIn12Seconds = 2; - } - - enum OnOffDyingLightEffectVariant : ENUM8 { - k20PercenterDimUpIn0p5SecondsThenFadeToOffIn1Second = 0; - } - - enum OnOffEffectIdentifier : ENUM8 { - kDelayedAllOff = 0; - kDyingLight = 1; - } - - enum OnOffStartUpOnOff : ENUM8 { - kOff = 0; - kOn = 1; - kTogglePreviousOnOff = 2; - } - - bitmap OnOffControl : BITMAP8 { - kAcceptOnlyWhenOn = 0x1; - } - - bitmap OnOffFeature : BITMAP32 { - kLighting = 0x1; - } - - bitmap ScenesFeature : BITMAP32 { - kSceneNames = 0x1; - } - - readonly attribute boolean onOff = 0; - readonly attribute boolean globalSceneControl = 16384; - attribute int16u onTime = 16385; - attribute int16u offWaitTime = 16386; - attribute access(write: manage) nullable OnOffStartUpOnOff startUpOnOff = 16387; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct OffWithEffectRequest { - OnOffEffectIdentifier effectId = 0; - OnOffDelayedAllOffEffectVariant effectVariant = 1; - } - - request struct OnWithTimedOffRequest { - OnOffControl onOffControl = 0; - int16u onTime = 1; - int16u offWaitTime = 2; - } - - command Off(): DefaultSuccess = 0; - command On(): DefaultSuccess = 1; - command Toggle(): DefaultSuccess = 2; - command OffWithEffect(OffWithEffectRequest): DefaultSuccess = 64; - command OnWithRecallGlobalScene(): DefaultSuccess = 65; - command OnWithTimedOff(OnWithTimedOffRequest): DefaultSuccess = 66; -} - -server cluster OnOffSwitchConfiguration = 7 { - readonly attribute enum8 switchType = 0; - attribute enum8 switchActions = 16; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster LevelControl = 8 { - enum MoveMode : ENUM8 { - kUp = 0; - kDown = 1; - } - - enum StepMode : ENUM8 { - kUp = 0; - kDown = 1; - } - - bitmap LevelControlFeature : BITMAP32 { - kOnOff = 0x1; - kLighting = 0x2; - kFrequency = 0x4; - } - - readonly attribute nullable int8u currentLevel = 0; - readonly attribute int16u remainingTime = 1; - readonly attribute int8u minLevel = 2; - readonly attribute int8u maxLevel = 3; - readonly attribute int16u currentFrequency = 4; - readonly attribute int16u minFrequency = 5; - readonly attribute int16u maxFrequency = 6; - attribute bitmap8 options = 15; - attribute int16u onOffTransitionTime = 16; - attribute nullable int8u onLevel = 17; - attribute nullable int16u onTransitionTime = 18; - attribute nullable int16u offTransitionTime = 19; - attribute nullable int8u defaultMoveRate = 20; - attribute access(write: manage) nullable int8u startUpCurrentLevel = 16384; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct MoveToLevelRequest { - INT8U level = 0; - nullable INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct MoveRequest { - MoveMode moveMode = 0; - nullable INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepRequest { - StepMode stepMode = 0; - INT8U stepSize = 1; - nullable INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct StopRequest { - BITMAP8 optionsMask = 0; - BITMAP8 optionsOverride = 1; - } - - request struct MoveToLevelWithOnOffRequest { - INT8U level = 0; - nullable INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct MoveWithOnOffRequest { - MoveMode moveMode = 0; - nullable INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepWithOnOffRequest { - StepMode stepMode = 0; - INT8U stepSize = 1; - nullable INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct StopWithOnOffRequest { - BITMAP8 optionsMask = 0; - BITMAP8 optionsOverride = 1; - } - - command MoveToLevel(MoveToLevelRequest): DefaultSuccess = 0; - command Move(MoveRequest): DefaultSuccess = 1; - command Step(StepRequest): DefaultSuccess = 2; - command Stop(StopRequest): DefaultSuccess = 3; - command MoveToLevelWithOnOff(MoveToLevelWithOnOffRequest): DefaultSuccess = 4; - command MoveWithOnOff(MoveWithOnOffRequest): DefaultSuccess = 5; - command StepWithOnOff(StepWithOnOffRequest): DefaultSuccess = 6; - command StopWithOnOff(StopWithOnOffRequest): DefaultSuccess = 7; -} - -server cluster BinaryInputBasic = 15 { - attribute boolean outOfService = 81; - attribute boolean presentValue = 85; - readonly attribute bitmap8 statusFlags = 111; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster Descriptor = 29 { - struct DeviceTypeStruct { - devtype_id type = 0; - int16u revision = 1; - } - - readonly attribute DeviceTypeStruct deviceTypeList[] = 0; - readonly attribute CLUSTER_ID serverList[] = 1; - readonly attribute CLUSTER_ID clientList[] = 2; - readonly attribute ENDPOINT_NO partsList[] = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster Binding = 30 { - fabric_scoped struct TargetStruct { - optional node_id node = 1; - optional group_id group = 2; - optional endpoint_no endpoint = 3; - optional cluster_id cluster = 4; - fabric_idx fabricIndex = 254; - } - - attribute TargetStruct binding[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster AccessControl = 31 { - enum AuthMode : ENUM8 { - kPase = 1; - kCase = 2; - kGroup = 3; - } - - enum ChangeTypeEnum : ENUM8 { - kChanged = 0; - kAdded = 1; - kRemoved = 2; - } - - enum Privilege : ENUM8 { - kView = 1; - kProxyView = 2; - kOperate = 3; - kManage = 4; - kAdminister = 5; - } - - fabric_scoped struct AccessControlEntry { - fabric_sensitive Privilege privilege = 1; - fabric_sensitive AuthMode authMode = 2; - nullable fabric_sensitive int64u subjects[] = 3; - nullable fabric_sensitive Target targets[] = 4; - fabric_idx fabricIndex = 254; - } - - struct Target { - nullable cluster_id cluster = 0; - nullable endpoint_no endpoint = 1; - nullable devtype_id deviceType = 2; - } - - fabric_scoped struct ExtensionEntry { - fabric_sensitive octet_string<128> data = 1; - fabric_idx fabricIndex = 254; - } - - fabric_sensitive info event access(read: administer) AccessControlEntryChanged = 0 { - nullable node_id adminNodeID = 1; - nullable INT16U adminPasscodeID = 2; - ChangeTypeEnum changeType = 3; - nullable AccessControlEntry latestValue = 4; - fabric_idx fabricIndex = 254; - } - - fabric_sensitive info event access(read: administer) AccessControlExtensionChanged = 1 { - nullable node_id adminNodeID = 1; - nullable INT16U adminPasscodeID = 2; - ChangeTypeEnum changeType = 3; - nullable ExtensionEntry latestValue = 4; - fabric_idx fabricIndex = 254; - } - - attribute access(read: administer, write: administer) AccessControlEntry acl[] = 0; - attribute access(read: administer, write: administer) ExtensionEntry extension[] = 1; - readonly attribute int16u subjectsPerAccessControlEntry = 2; - readonly attribute int16u targetsPerAccessControlEntry = 3; - readonly attribute int16u accessControlEntriesPerFabric = 4; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster Actions = 37 { - enum ActionErrorEnum : ENUM8 { - kUnknown = 0; - kInterrupted = 1; - } - - enum ActionStateEnum : ENUM8 { - kInactive = 0; - kActive = 1; - kPaused = 2; - kDisabled = 3; - } - - enum ActionTypeEnum : ENUM8 { - kOther = 0; - kScene = 1; - kSequence = 2; - kAutomation = 3; - kException = 4; - kNotification = 5; - kAlarm = 6; - } - - enum EndpointListTypeEnum : ENUM8 { - kOther = 0; - kRoom = 1; - kZone = 2; - } - - bitmap CommandBits : BITMAP16 { - kInstantAction = 0x1; - kInstantActionWithTransition = 0x2; - kStartAction = 0x4; - kStartActionWithDuration = 0x8; - kStopAction = 0x10; - kPauseAction = 0x20; - kPauseActionWithDuration = 0x40; - kResumeAction = 0x80; - kEnableAction = 0x100; - kEnableActionWithDuration = 0x200; - kDisableAction = 0x400; - kDisableActionWithDuration = 0x800; - } - - struct ActionStruct { - int16u actionID = 0; - char_string<32> name = 1; - ActionTypeEnum type = 2; - int16u endpointListID = 3; - CommandBits supportedCommands = 4; - ActionStateEnum state = 5; - } - - struct EndpointListStruct { - int16u endpointListID = 0; - char_string<32> name = 1; - EndpointListTypeEnum type = 2; - endpoint_no endpoints[] = 3; - } - - info event StateChanged = 0 { - INT16U actionID = 0; - INT32U invokeID = 1; - ActionStateEnum newState = 2; - } - - info event ActionFailed = 1 { - INT16U actionID = 0; - INT32U invokeID = 1; - ActionStateEnum newState = 2; - ActionErrorEnum error = 3; - } - - readonly attribute ActionStruct actionList[] = 0; - readonly attribute EndpointListStruct endpointLists[] = 1; - readonly attribute long_char_string<512> setupURL = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster BasicInformation = 40 { - struct CapabilityMinimaStruct { - int16u caseSessionsPerFabric = 0; - int16u subscriptionsPerFabric = 1; - } - - critical event StartUp = 0 { - INT32U softwareVersion = 0; - } - - critical event ShutDown = 1 { - } - - info event Leave = 2 { - fabric_idx fabricIndex = 0; - } - - info event ReachableChanged = 3 { - boolean reachableNewValue = 0; - } - - readonly attribute int16u dataModelRevision = 0; - readonly attribute char_string<32> vendorName = 1; - readonly attribute vendor_id vendorID = 2; - readonly attribute char_string<32> productName = 3; - readonly attribute int16u productID = 4; - attribute access(write: manage) char_string<32> nodeLabel = 5; - attribute access(write: administer) char_string<2> location = 6; - readonly attribute int16u hardwareVersion = 7; - readonly attribute char_string<64> hardwareVersionString = 8; - readonly attribute int32u softwareVersion = 9; - readonly attribute char_string<64> softwareVersionString = 10; - readonly attribute char_string<16> manufacturingDate = 11; - readonly attribute char_string<32> partNumber = 12; - readonly attribute long_char_string<256> productURL = 13; - readonly attribute char_string<64> productLabel = 14; - readonly attribute char_string<32> serialNumber = 15; - attribute access(write: manage) boolean localConfigDisabled = 16; - readonly attribute boolean reachable = 17; - readonly attribute char_string<32> uniqueID = 18; - readonly attribute CapabilityMinimaStruct capabilityMinima = 19; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -client cluster OtaSoftwareUpdateProvider = 41 { - enum OTAApplyUpdateAction : ENUM8 { - kProceed = 0; - kAwaitNextAction = 1; - kDiscontinue = 2; - } - - enum OTADownloadProtocol : ENUM8 { - kBDXSynchronous = 0; - kBDXAsynchronous = 1; - kHttps = 2; - kVendorSpecific = 3; - } - - enum OTAQueryStatus : ENUM8 { - kUpdateAvailable = 0; - kBusy = 1; - kNotAvailable = 2; - kDownloadProtocolNotSupported = 3; - } - - readonly attribute int16u clusterRevision = 65533; - - request struct QueryImageRequest { - vendor_id vendorId = 0; - INT16U productId = 1; - INT32U softwareVersion = 2; - OTADownloadProtocol protocolsSupported[] = 3; - optional INT16U hardwareVersion = 4; - optional CHAR_STRING<2> location = 5; - optional BOOLEAN requestorCanConsent = 6; - optional OCTET_STRING<512> metadataForProvider = 7; - } - - request struct ApplyUpdateRequestRequest { - OCTET_STRING<32> updateToken = 0; - INT32U newVersion = 1; - } - - request struct NotifyUpdateAppliedRequest { - OCTET_STRING<32> updateToken = 0; - INT32U softwareVersion = 1; - } - - response struct ApplyUpdateResponse = 3 { - OTAApplyUpdateAction action = 0; - INT32U delayedActionTime = 1; - } - - command QueryImage(QueryImageRequest): QueryImageResponse = 0; - command ApplyUpdateRequest(ApplyUpdateRequestRequest): ApplyUpdateResponse = 2; - command NotifyUpdateApplied(NotifyUpdateAppliedRequest): DefaultSuccess = 4; -} - -server cluster OtaSoftwareUpdateRequestor = 42 { - enum OTAAnnouncementReason : ENUM8 { - kSimpleAnnouncement = 0; - kUpdateAvailable = 1; - kUrgentUpdateAvailable = 2; - } - - enum OTAChangeReasonEnum : ENUM8 { - kUnknown = 0; - kSuccess = 1; - kFailure = 2; - kTimeOut = 3; - kDelayByProvider = 4; - } - - enum OTAUpdateStateEnum : ENUM8 { - kUnknown = 0; - kIdle = 1; - kQuerying = 2; - kDelayedOnQuery = 3; - kDownloading = 4; - kApplying = 5; - kDelayedOnApply = 6; - kRollingBack = 7; - kDelayedOnUserConsent = 8; - } - - fabric_scoped struct ProviderLocation { - node_id providerNodeID = 1; - endpoint_no endpoint = 2; - fabric_idx fabricIndex = 254; - } - - info event StateTransition = 0 { - OTAUpdateStateEnum previousState = 0; - OTAUpdateStateEnum newState = 1; - OTAChangeReasonEnum reason = 2; - nullable INT32U targetSoftwareVersion = 3; - } - - critical event VersionApplied = 1 { - INT32U softwareVersion = 0; - INT16U productID = 1; - } - - info event DownloadError = 2 { - INT32U softwareVersion = 0; - INT64U bytesDownloaded = 1; - nullable INT8U progressPercent = 2; - nullable INT64S platformCode = 3; - } - - attribute ProviderLocation defaultOtaProviders[] = 0; - readonly attribute boolean updatePossible = 1; - readonly attribute OTAUpdateStateEnum updateState = 2; - readonly attribute nullable int8u updateStateProgress = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AnnounceOtaProviderRequest { - node_id providerNodeId = 0; - vendor_id vendorId = 1; - OTAAnnouncementReason announcementReason = 2; - optional OCTET_STRING<512> metadataForNode = 3; - endpoint_no endpoint = 4; - } - - command AnnounceOtaProvider(AnnounceOtaProviderRequest): DefaultSuccess = 0; -} - -server cluster LocalizationConfiguration = 43 { - attribute char_string<35> activeLocale = 0; - readonly attribute CHAR_STRING supportedLocales[] = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster TimeFormatLocalization = 44 { - enum CalendarType : ENUM8 { - kBuddhist = 0; - kChinese = 1; - kCoptic = 2; - kEthiopian = 3; - kGregorian = 4; - kHebrew = 5; - kIndian = 6; - kIslamic = 7; - kJapanese = 8; - kKorean = 9; - kPersian = 10; - kTaiwanese = 11; - } - - enum HourFormat : ENUM8 { - k12hr = 0; - k24hr = 1; - } - - attribute HourFormat hourFormat = 0; - attribute CalendarType activeCalendarType = 1; - readonly attribute CalendarType supportedCalendarTypes[] = 2; - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster UnitLocalization = 45 { - enum TempUnit : ENUM8 { - kFahrenheit = 0; - kCelsius = 1; - kKelvin = 2; - } - - bitmap UnitLocalizationFeature : BITMAP32 { - kTemperatureUnit = 0x1; - } - - attribute TempUnit temperatureUnit = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster PowerSourceConfiguration = 46 { - readonly attribute INT8U sources[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster PowerSource = 47 { - enum BatChargeFault : ENUM8 { - kUnspecfied = 0; - kAmbientTooHot = 1; - kAmbientTooCold = 2; - kBatteryTooHot = 3; - kBatteryTooCold = 4; - kBatteryAbsent = 5; - kBatteryOverVoltage = 6; - kBatteryUnderVoltage = 7; - kChargerOverVoltage = 8; - kChargerUnderVoltage = 9; - kSafetyTimeout = 10; - } - - enum BatChargeLevel : ENUM8 { - kOk = 0; - kWarning = 1; - kCritical = 2; - } - - enum BatChargeState : ENUM8 { - kUnknown = 0; - kIsCharging = 1; - kIsAtFullCharge = 2; - kIsNotCharging = 3; - } - - enum BatFault : ENUM8 { - kUnspecfied = 0; - kOverTemp = 1; - kUnderTemp = 2; - } - - enum BatReplaceability : ENUM8 { - kUnspecified = 0; - kNotReplaceable = 1; - kUserReplaceable = 2; - kFactoryReplaceable = 3; - } - - enum PowerSourceStatus : ENUM8 { - kUnspecfied = 0; - kActive = 1; - kStandby = 2; - kUnavailable = 3; - } - - enum WiredCurrentType : ENUM8 { - kAc = 0; - kDc = 1; - } - - enum WiredFault : ENUM8 { - kUnspecfied = 0; - kOverVoltage = 1; - kUnderVoltage = 2; - } - - bitmap PowerSourceFeature : BITMAP32 { - kWired = 0x1; - kBattery = 0x2; - kRechargeable = 0x4; - kReplaceable = 0x8; - } - - readonly attribute PowerSourceStatus status = 0; - readonly attribute int8u order = 1; - readonly attribute char_string<60> description = 2; - readonly attribute BatChargeLevel batChargeLevel = 14; - readonly attribute boolean batReplacementNeeded = 15; - readonly attribute BatReplaceability batReplaceability = 16; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster GeneralCommissioning = 48 { - enum CommissioningError : ENUM8 { - kOk = 0; - kValueOutsideRange = 1; - kInvalidAuthentication = 2; - kNoFailSafe = 3; - kBusyWithOtherAdmin = 4; - } - - enum RegulatoryLocationType : ENUM8 { - kIndoor = 0; - kOutdoor = 1; - kIndoorOutdoor = 2; - } - - struct BasicCommissioningInfo { - int16u failSafeExpiryLengthSeconds = 0; - int16u maxCumulativeFailsafeSeconds = 1; - } - - attribute access(write: administer) int64u breadcrumb = 0; - readonly attribute BasicCommissioningInfo basicCommissioningInfo = 1; - readonly attribute RegulatoryLocationType regulatoryConfig = 2; - readonly attribute RegulatoryLocationType locationCapability = 3; - readonly attribute boolean supportsConcurrentConnection = 4; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct ArmFailSafeRequest { - INT16U expiryLengthSeconds = 0; - INT64U breadcrumb = 1; - } - - request struct SetRegulatoryConfigRequest { - RegulatoryLocationType newRegulatoryConfig = 0; - CHAR_STRING countryCode = 1; - INT64U breadcrumb = 2; - } - - response struct ArmFailSafeResponse = 1 { - CommissioningError errorCode = 0; - CHAR_STRING debugText = 1; - } - - response struct SetRegulatoryConfigResponse = 3 { - CommissioningError errorCode = 0; - CHAR_STRING debugText = 1; - } - - response struct CommissioningCompleteResponse = 5 { - CommissioningError errorCode = 0; - CHAR_STRING debugText = 1; - } - - command access(invoke: administer) ArmFailSafe(ArmFailSafeRequest): ArmFailSafeResponse = 0; - command access(invoke: administer) SetRegulatoryConfig(SetRegulatoryConfigRequest): SetRegulatoryConfigResponse = 2; - fabric command access(invoke: administer) CommissioningComplete(): CommissioningCompleteResponse = 4; -} - -server cluster NetworkCommissioning = 49 { - enum NetworkCommissioningStatus : ENUM8 { - kSuccess = 0; - kOutOfRange = 1; - kBoundsExceeded = 2; - kNetworkIDNotFound = 3; - kDuplicateNetworkID = 4; - kNetworkNotFound = 5; - kRegulatoryError = 6; - kAuthFailure = 7; - kUnsupportedSecurity = 8; - kOtherConnectionFailure = 9; - kIPV6Failed = 10; - kIPBindFailed = 11; - kUnknownError = 12; - } - - enum WiFiBand : ENUM8 { - k2g4 = 0; - k3g65 = 1; - k5g = 2; - k6g = 3; - k60g = 4; - } - - bitmap NetworkCommissioningFeature : BITMAP32 { - kWiFiNetworkInterface = 0x1; - kThreadNetworkInterface = 0x2; - kEthernetNetworkInterface = 0x4; - } - - bitmap WiFiSecurity : BITMAP8 { - kUnencrypted = 0x1; - kWepPersonal = 0x2; - kWpaPersonal = 0x4; - kWpa2Personal = 0x8; - kWpa3Personal = 0x10; - } - - struct NetworkInfo { - octet_string<32> networkID = 0; - boolean connected = 1; - } - - struct WiFiInterfaceScanResult { - WiFiSecurity security = 0; - octet_string<32> ssid = 1; - octet_string<6> bssid = 2; - int16u channel = 3; - WiFiBand wiFiBand = 4; - int8s rssi = 5; - } - - struct ThreadInterfaceScanResult { - int16u panId = 0; - int64u extendedPanId = 1; - char_string<16> networkName = 2; - int16u channel = 3; - int8u version = 4; - octet_string<8> extendedAddress = 5; - int8s rssi = 6; - int8u lqi = 7; - } - - readonly attribute access(read: administer) int8u maxNetworks = 0; - readonly attribute access(read: administer) NetworkInfo networks[] = 1; - readonly attribute int8u scanMaxTimeSeconds = 2; - readonly attribute int8u connectMaxTimeSeconds = 3; - attribute access(write: administer) boolean interfaceEnabled = 4; - readonly attribute access(read: administer) nullable NetworkCommissioningStatus lastNetworkingStatus = 5; - readonly attribute access(read: administer) nullable octet_string<32> lastNetworkID = 6; - readonly attribute access(read: administer) nullable int32s lastConnectErrorValue = 7; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct ScanNetworksRequest { - optional nullable OCTET_STRING<32> ssid = 0; - optional INT64U breadcrumb = 1; - } - - request struct AddOrUpdateWiFiNetworkRequest { - OCTET_STRING<32> ssid = 0; - OCTET_STRING<64> credentials = 1; - optional INT64U breadcrumb = 2; - } - - request struct AddOrUpdateThreadNetworkRequest { - OCTET_STRING<254> operationalDataset = 0; - optional INT64U breadcrumb = 1; - } - - request struct RemoveNetworkRequest { - OCTET_STRING<32> networkID = 0; - optional INT64U breadcrumb = 1; - } - - request struct ConnectNetworkRequest { - OCTET_STRING<32> networkID = 0; - optional INT64U breadcrumb = 1; - } - - request struct ReorderNetworkRequest { - OCTET_STRING<32> networkID = 0; - INT8U networkIndex = 1; - optional INT64U breadcrumb = 2; - } - - response struct ScanNetworksResponse = 1 { - NetworkCommissioningStatus networkingStatus = 0; - optional CHAR_STRING debugText = 1; - optional WiFiInterfaceScanResult wiFiScanResults[] = 2; - optional ThreadInterfaceScanResult threadScanResults[] = 3; - } - - response struct NetworkConfigResponse = 5 { - NetworkCommissioningStatus networkingStatus = 0; - optional CHAR_STRING<512> debugText = 1; - optional INT8U networkIndex = 2; - } - - response struct ConnectNetworkResponse = 7 { - NetworkCommissioningStatus networkingStatus = 0; - optional CHAR_STRING debugText = 1; - nullable INT32S errorValue = 2; - } - - command access(invoke: administer) ScanNetworks(ScanNetworksRequest): ScanNetworksResponse = 0; - command access(invoke: administer) AddOrUpdateWiFiNetwork(AddOrUpdateWiFiNetworkRequest): NetworkConfigResponse = 2; - command access(invoke: administer) AddOrUpdateThreadNetwork(AddOrUpdateThreadNetworkRequest): NetworkConfigResponse = 3; - command access(invoke: administer) RemoveNetwork(RemoveNetworkRequest): NetworkConfigResponse = 4; - command access(invoke: administer) ConnectNetwork(ConnectNetworkRequest): ConnectNetworkResponse = 6; - command access(invoke: administer) ReorderNetwork(ReorderNetworkRequest): NetworkConfigResponse = 8; -} - -server cluster DiagnosticLogs = 50 { - enum LogsIntent : ENUM8 { - kEndUserSupport = 0; - kNetworkDiag = 1; - kCrashLogs = 2; - } - - enum LogsStatus : ENUM8 { - kSuccess = 0; - kExhausted = 1; - kNoLogs = 2; - kBusy = 3; - kDenied = 4; - } - - enum LogsTransferProtocol : ENUM8 { - kResponsePayload = 0; - kBdx = 1; - } - - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct RetrieveLogsRequestRequest { - LogsIntent intent = 0; - LogsTransferProtocol requestedProtocol = 1; - OCTET_STRING<32> transferFileDesignator = 2; - } - - command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; -} - -server cluster GeneralDiagnostics = 51 { - enum BootReasonType : ENUM8 { - kUnspecified = 0; - kPowerOnReboot = 1; - kBrownOutReset = 2; - kSoftwareWatchdogReset = 3; - kHardwareWatchdogReset = 4; - kSoftwareUpdateCompleted = 5; - kSoftwareReset = 6; - } - - enum HardwareFaultType : ENUM8 { - kUnspecified = 0; - kRadio = 1; - kSensor = 2; - kResettableOverTemp = 3; - kNonResettableOverTemp = 4; - kPowerSource = 5; - kVisualDisplayFault = 6; - kAudioOutputFault = 7; - kUserInterfaceFault = 8; - kNonVolatileMemoryError = 9; - kTamperDetected = 10; - } - - enum InterfaceType : ENUM8 { - kUnspecified = 0; - kWiFi = 1; - kEthernet = 2; - kCellular = 3; - kThread = 4; - } - - enum NetworkFaultType : ENUM8 { - kUnspecified = 0; - kHardwareFailure = 1; - kNetworkJammed = 2; - kConnectionFailed = 3; - } - - enum RadioFaultType : ENUM8 { - kUnspecified = 0; - kWiFiFault = 1; - kCellularFault = 2; - kThreadFault = 3; - kNFCFault = 4; - kBLEFault = 5; - kEthernetFault = 6; - } - - struct NetworkInterfaceType { - char_string<32> name = 0; - boolean isOperational = 1; - nullable boolean offPremiseServicesReachableIPv4 = 2; - nullable boolean offPremiseServicesReachableIPv6 = 3; - octet_string<8> hardwareAddress = 4; - octet_string IPv4Addresses[] = 5; - octet_string IPv6Addresses[] = 6; - InterfaceType type = 7; - } - - critical event HardwareFaultChange = 0 { - HardwareFaultType current[] = 0; - HardwareFaultType previous[] = 1; - } - - critical event RadioFaultChange = 1 { - RadioFaultType current[] = 0; - RadioFaultType previous[] = 1; - } - - critical event NetworkFaultChange = 2 { - NetworkFaultType current[] = 0; - NetworkFaultType previous[] = 1; - } - - critical event BootReason = 3 { - BootReasonType bootReason = 0; - } - - readonly attribute NetworkInterfaceType networkInterfaces[] = 0; - readonly attribute int16u rebootCount = 1; - readonly attribute int64u upTime = 2; - readonly attribute int32u totalOperationalHours = 3; - readonly attribute enum8 bootReasons = 4; - readonly attribute ENUM8 activeHardwareFaults[] = 5; - readonly attribute ENUM8 activeRadioFaults[] = 6; - readonly attribute ENUM8 activeNetworkFaults[] = 7; - readonly attribute boolean testEventTriggersEnabled = 8; - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct TestEventTriggerRequest { - OCTET_STRING<16> enableKey = 0; - INT64U eventTrigger = 1; - } - - command access(invoke: manage) TestEventTrigger(TestEventTriggerRequest): DefaultSuccess = 0; -} - -server cluster SoftwareDiagnostics = 52 { - bitmap SoftwareDiagnosticsFeature : BITMAP32 { - kWaterMarks = 0x1; - } - - struct ThreadMetrics { - int64u id = 0; - optional char_string<8> name = 1; - optional int32u stackFreeCurrent = 2; - optional int32u stackFreeMinimum = 3; - optional int32u stackSize = 4; - } - - info event SoftwareFault = 0 { - INT64U id = 0; - optional CHAR_STRING name = 1; - optional OCTET_STRING faultRecording = 2; - } - - readonly attribute ThreadMetrics threadMetrics[] = 0; - readonly attribute int64u currentHeapFree = 1; - readonly attribute int64u currentHeapUsed = 2; - readonly attribute int64u currentHeapHighWatermark = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetWatermarks(): DefaultSuccess = 0; -} - -server cluster ThreadNetworkDiagnostics = 53 { - enum NetworkFault : ENUM8 { - kUnspecified = 0; - kLinkDown = 1; - kHardwareFailure = 2; - kNetworkJammed = 3; - } - - enum RoutingRole : ENUM8 { - kUnspecified = 0; - kUnassigned = 1; - kSleepyEndDevice = 2; - kEndDevice = 3; - kReed = 4; - kRouter = 5; - kLeader = 6; - } - - enum ThreadConnectionStatus : ENUM8 { - kConnected = 0; - kNotConnected = 1; - } - - bitmap ThreadNetworkDiagnosticsFeature : BITMAP32 { - kPacketCounts = 0x1; - kErrorCounts = 0x2; - kMLECounts = 0x4; - kMACCounts = 0x8; - } - - struct NeighborTable { - int64u extAddress = 0; - int32u age = 1; - int16u rloc16 = 2; - int32u linkFrameCounter = 3; - int32u mleFrameCounter = 4; - int8u lqi = 5; - nullable int8s averageRssi = 6; - nullable int8s lastRssi = 7; - int8u frameErrorRate = 8; - int8u messageErrorRate = 9; - boolean rxOnWhenIdle = 10; - boolean fullThreadDevice = 11; - boolean fullNetworkData = 12; - boolean isChild = 13; - } - - struct RouteTable { - int64u extAddress = 0; - int16u rloc16 = 1; - int8u routerId = 2; - int8u nextHop = 3; - int8u pathCost = 4; - int8u LQIIn = 5; - int8u LQIOut = 6; - int8u age = 7; - boolean allocated = 8; - boolean linkEstablished = 9; - } - - struct SecurityPolicy { - int16u rotationTime = 0; - bitmap16 flags = 1; - } - - struct OperationalDatasetComponents { - boolean activeTimestampPresent = 0; - boolean pendingTimestampPresent = 1; - boolean masterKeyPresent = 2; - boolean networkNamePresent = 3; - boolean extendedPanIdPresent = 4; - boolean meshLocalPrefixPresent = 5; - boolean delayPresent = 6; - boolean panIdPresent = 7; - boolean channelPresent = 8; - boolean pskcPresent = 9; - boolean securityPolicyPresent = 10; - boolean channelMaskPresent = 11; - } - - info event ConnectionStatus = 0 { - ThreadConnectionStatus connectionStatus = 0; - } - - info event NetworkFaultChange = 1 { - NetworkFault current[] = 0; - NetworkFault previous[] = 1; - } - - readonly attribute nullable int16u channel = 0; - readonly attribute nullable RoutingRole routingRole = 1; - readonly attribute nullable char_string<16> networkName = 2; - readonly attribute nullable int16u panId = 3; - readonly attribute nullable int64u extendedPanId = 4; - readonly attribute nullable octet_string<17> meshLocalPrefix = 5; - readonly attribute int64u overrunCount = 6; - readonly attribute NeighborTable neighborTableList[] = 7; - readonly attribute RouteTable routeTableList[] = 8; - readonly attribute nullable int32u partitionId = 9; - readonly attribute nullable int8u weighting = 10; - readonly attribute nullable int8u dataVersion = 11; - readonly attribute nullable int8u stableDataVersion = 12; - readonly attribute nullable int8u leaderRouterId = 13; - readonly attribute int16u detachedRoleCount = 14; - readonly attribute int16u childRoleCount = 15; - readonly attribute int16u routerRoleCount = 16; - readonly attribute int16u leaderRoleCount = 17; - readonly attribute int16u attachAttemptCount = 18; - readonly attribute int16u partitionIdChangeCount = 19; - readonly attribute int16u betterPartitionAttachAttemptCount = 20; - readonly attribute int16u parentChangeCount = 21; - readonly attribute int32u txTotalCount = 22; - readonly attribute int32u txUnicastCount = 23; - readonly attribute int32u txBroadcastCount = 24; - readonly attribute int32u txAckRequestedCount = 25; - readonly attribute int32u txAckedCount = 26; - readonly attribute int32u txNoAckRequestedCount = 27; - readonly attribute int32u txDataCount = 28; - readonly attribute int32u txDataPollCount = 29; - readonly attribute int32u txBeaconCount = 30; - readonly attribute int32u txBeaconRequestCount = 31; - readonly attribute int32u txOtherCount = 32; - readonly attribute int32u txRetryCount = 33; - readonly attribute int32u txDirectMaxRetryExpiryCount = 34; - readonly attribute int32u txIndirectMaxRetryExpiryCount = 35; - readonly attribute int32u txErrCcaCount = 36; - readonly attribute int32u txErrAbortCount = 37; - readonly attribute int32u txErrBusyChannelCount = 38; - readonly attribute int32u rxTotalCount = 39; - readonly attribute int32u rxUnicastCount = 40; - readonly attribute int32u rxBroadcastCount = 41; - readonly attribute int32u rxDataCount = 42; - readonly attribute int32u rxDataPollCount = 43; - readonly attribute int32u rxBeaconCount = 44; - readonly attribute int32u rxBeaconRequestCount = 45; - readonly attribute int32u rxOtherCount = 46; - readonly attribute int32u rxAddressFilteredCount = 47; - readonly attribute int32u rxDestAddrFilteredCount = 48; - readonly attribute int32u rxDuplicatedCount = 49; - readonly attribute int32u rxErrNoFrameCount = 50; - readonly attribute int32u rxErrUnknownNeighborCount = 51; - readonly attribute int32u rxErrInvalidSrcAddrCount = 52; - readonly attribute int32u rxErrSecCount = 53; - readonly attribute int32u rxErrFcsCount = 54; - readonly attribute int32u rxErrOtherCount = 55; - readonly attribute nullable int64u activeTimestamp = 56; - readonly attribute nullable int64u pendingTimestamp = 57; - readonly attribute nullable int32u delay = 58; - readonly attribute nullable SecurityPolicy securityPolicy = 59; - readonly attribute nullable octet_string<4> channelPage0Mask = 60; - readonly attribute nullable OperationalDatasetComponents operationalDatasetComponents = 61; - readonly attribute NetworkFault activeNetworkFaultsList[] = 62; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetCounts(): DefaultSuccess = 0; -} - -server cluster WiFiNetworkDiagnostics = 54 { - enum AssociationFailureCause : ENUM8 { - kUnknown = 0; - kAssociationFailed = 1; - kAuthenticationFailed = 2; - kSsidNotFound = 3; - } - - enum SecurityType : ENUM8 { - kUnspecified = 0; - kNone = 1; - kWep = 2; - kWpa = 3; - kWpa2 = 4; - kWpa3 = 5; - } - - enum WiFiConnectionStatus : ENUM8 { - kConnected = 0; - kNotConnected = 1; - } - - enum WiFiVersionType : ENUM8 { - k80211a = 0; - k80211b = 1; - k80211g = 2; - k80211n = 3; - k80211ac = 4; - k80211ax = 5; - } - - info event Disconnection = 0 { - INT16U reasonCode = 0; - } - - info event AssociationFailure = 1 { - AssociationFailureCause associationFailure = 0; - INT16U status = 1; - } - - info event ConnectionStatus = 2 { - WiFiConnectionStatus connectionStatus = 0; - } - - readonly attribute nullable octet_string<6> bssid = 0; - readonly attribute nullable SecurityType securityType = 1; - readonly attribute nullable WiFiVersionType wiFiVersion = 2; - readonly attribute nullable int16u channelNumber = 3; - readonly attribute nullable int8s rssi = 4; - readonly attribute nullable int32u beaconLostCount = 5; - readonly attribute nullable int32u beaconRxCount = 6; - readonly attribute nullable int32u packetMulticastRxCount = 7; - readonly attribute nullable int32u packetMulticastTxCount = 8; - readonly attribute nullable int32u packetUnicastRxCount = 9; - readonly attribute nullable int32u packetUnicastTxCount = 10; - readonly attribute nullable int64u currentMaxRate = 11; - readonly attribute nullable int64u overrunCount = 12; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetCounts(): DefaultSuccess = 0; -} - -server cluster EthernetNetworkDiagnostics = 55 { - enum PHYRateType : ENUM8 { - k10m = 0; - k100m = 1; - k1000m = 2; - k25g = 3; - k5g = 4; - k10g = 5; - k40g = 6; - k100g = 7; - k200g = 8; - k400g = 9; - } - - readonly attribute nullable PHYRateType PHYRate = 0; - readonly attribute nullable boolean fullDuplex = 1; - readonly attribute int64u packetRxCount = 2; - readonly attribute int64u packetTxCount = 3; - readonly attribute int64u txErrCount = 4; - readonly attribute int64u collisionCount = 5; - readonly attribute int64u overrunCount = 6; - readonly attribute nullable boolean carrierDetect = 7; - readonly attribute int64u timeSinceReset = 8; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetCounts(): DefaultSuccess = 0; -} - -server cluster Switch = 59 { - bitmap SwitchFeature : BITMAP32 { - kLatchingSwitch = 0x1; - kMomentarySwitch = 0x2; - kMomentarySwitchRelease = 0x4; - kMomentarySwitchLongPress = 0x8; - kMomentarySwitchMultiPress = 0x10; - } - - info event SwitchLatched = 0 { - INT8U newPosition = 0; - } - - info event InitialPress = 1 { - INT8U newPosition = 0; - } - - info event LongPress = 2 { - INT8U newPosition = 0; - } - - info event ShortRelease = 3 { - INT8U previousPosition = 0; - } - - info event LongRelease = 4 { - INT8U previousPosition = 0; - } - - info event MultiPressOngoing = 5 { - INT8U newPosition = 0; - INT8U currentNumberOfPressesCounted = 1; - } - - info event MultiPressComplete = 6 { - INT8U newPosition = 0; - INT8U totalNumberOfPressesCounted = 1; - } - - readonly attribute int8u numberOfPositions = 0; - readonly attribute int8u currentPosition = 1; - readonly attribute int8u multiPressMax = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster AdministratorCommissioning = 60 { - enum CommissioningWindowStatus : ENUM8 { - kWindowNotOpen = 0; - kEnhancedWindowOpen = 1; - kBasicWindowOpen = 2; - } - - enum StatusCode : ENUM8 { - kBusy = 2; - kPAKEParameterError = 3; - kWindowNotOpen = 4; - } - - readonly attribute CommissioningWindowStatus windowStatus = 0; - readonly attribute nullable fabric_idx adminFabricIndex = 1; - readonly attribute nullable int16u adminVendorId = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct OpenCommissioningWindowRequest { - INT16U commissioningTimeout = 0; - OCTET_STRING PAKEVerifier = 1; - INT16U discriminator = 2; - INT32U iterations = 3; - OCTET_STRING salt = 4; - } - - request struct OpenBasicCommissioningWindowRequest { - INT16U commissioningTimeout = 0; - } - - timed command access(invoke: administer) OpenCommissioningWindow(OpenCommissioningWindowRequest): DefaultSuccess = 0; - timed command access(invoke: administer) OpenBasicCommissioningWindow(OpenBasicCommissioningWindowRequest): DefaultSuccess = 1; - timed command access(invoke: administer) RevokeCommissioning(): DefaultSuccess = 2; -} - -server cluster OperationalCredentials = 62 { - enum OperationalCertStatus : ENUM8 { - kSuccess = 0; - kInvalidPublicKey = 1; - kInvalidNodeOpId = 2; - kInvalidNOC = 3; - kMissingCsr = 4; - kTableFull = 5; - kInvalidAdminSubject = 6; - kFabricConflict = 9; - kLabelConflict = 10; - kInvalidFabricIndex = 11; - } - - fabric_scoped struct NOCStruct { - fabric_sensitive octet_string noc = 1; - nullable fabric_sensitive octet_string icac = 2; - fabric_idx fabricIndex = 254; - } - - fabric_scoped struct FabricDescriptor { - octet_string<65> rootPublicKey = 1; - vendor_id vendorId = 2; - fabric_id fabricId = 3; - node_id nodeId = 4; - char_string<32> label = 5; - fabric_idx fabricIndex = 254; - } - - readonly attribute access(read: administer) NOCStruct NOCs[] = 0; - readonly attribute FabricDescriptor fabrics[] = 1; - readonly attribute int8u supportedFabrics = 2; - readonly attribute int8u commissionedFabrics = 3; - readonly attribute OCTET_STRING trustedRootCertificates[] = 4; - readonly attribute int8u currentFabricIndex = 5; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AttestationRequestRequest { - OCTET_STRING attestationNonce = 0; - } - - request struct CertificateChainRequestRequest { - INT8U certificateType = 0; - } - - request struct CSRRequestRequest { - OCTET_STRING CSRNonce = 0; - optional boolean isForUpdateNOC = 1; - } - - request struct AddNOCRequest { - OCTET_STRING NOCValue = 0; - optional OCTET_STRING ICACValue = 1; - OCTET_STRING IPKValue = 2; - Int64u caseAdminSubject = 3; - VENDOR_ID adminVendorId = 4; - } - - request struct UpdateNOCRequest { - OCTET_STRING NOCValue = 0; - optional OCTET_STRING ICACValue = 1; - } - - request struct UpdateFabricLabelRequest { - CHAR_STRING<32> label = 0; - } - - request struct RemoveFabricRequest { - fabric_idx fabricIndex = 0; - } - - request struct AddTrustedRootCertificateRequest { - OCTET_STRING rootCertificate = 0; - } - - response struct AttestationResponse = 1 { - OCTET_STRING attestationElements = 0; - OCTET_STRING signature = 1; - } - - response struct CertificateChainResponse = 3 { - OCTET_STRING certificate = 0; - } - - response struct CSRResponse = 5 { - OCTET_STRING NOCSRElements = 0; - OCTET_STRING attestationSignature = 1; - } - - response struct NOCResponse = 8 { - OperationalCertStatus statusCode = 0; - optional fabric_idx fabricIndex = 1; - optional CHAR_STRING debugText = 2; - } - - command access(invoke: administer) AttestationRequest(AttestationRequestRequest): AttestationResponse = 0; - command access(invoke: administer) CertificateChainRequest(CertificateChainRequestRequest): CertificateChainResponse = 2; - command access(invoke: administer) CSRRequest(CSRRequestRequest): CSRResponse = 4; - command access(invoke: administer) AddNOC(AddNOCRequest): NOCResponse = 6; - fabric command access(invoke: administer) UpdateNOC(UpdateNOCRequest): NOCResponse = 7; - fabric command access(invoke: administer) UpdateFabricLabel(UpdateFabricLabelRequest): NOCResponse = 9; - command access(invoke: administer) RemoveFabric(RemoveFabricRequest): NOCResponse = 10; - command access(invoke: administer) AddTrustedRootCertificate(AddTrustedRootCertificateRequest): DefaultSuccess = 11; -} - -server cluster GroupKeyManagement = 63 { - enum GroupKeySecurityPolicy : ENUM8 { - kTrustFirst = 0; - kCacheAndSync = 1; - } - - fabric_scoped struct GroupKeyMapStruct { - group_id groupId = 1; - int16u groupKeySetID = 2; - fabric_idx fabricIndex = 254; - } - - fabric_scoped struct GroupInfoMapStruct { - group_id groupId = 1; - endpoint_no endpoints[] = 2; - optional char_string<16> groupName = 3; - fabric_idx fabricIndex = 254; - } - - struct GroupKeySetStruct { - int16u groupKeySetID = 0; - GroupKeySecurityPolicy groupKeySecurityPolicy = 1; - nullable octet_string<16> epochKey0 = 2; - nullable epoch_us epochStartTime0 = 3; - nullable octet_string<16> epochKey1 = 4; - nullable epoch_us epochStartTime1 = 5; - nullable octet_string<16> epochKey2 = 6; - nullable epoch_us epochStartTime2 = 7; - } - - attribute access(write: manage) GroupKeyMapStruct groupKeyMap[] = 0; - readonly attribute GroupInfoMapStruct groupTable[] = 1; - readonly attribute int16u maxGroupsPerFabric = 2; - readonly attribute int16u maxGroupKeysPerFabric = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct KeySetWriteRequest { - GroupKeySetStruct groupKeySet = 0; - } - - request struct KeySetReadRequest { - INT16U groupKeySetID = 0; - } - - request struct KeySetRemoveRequest { - INT16U groupKeySetID = 0; - } - - request struct KeySetReadAllIndicesRequest { - INT16U groupKeySetIDs[] = 0; - } - - response struct KeySetReadResponse = 2 { - GroupKeySetStruct groupKeySet = 0; - } - - response struct KeySetReadAllIndicesResponse = 5 { - INT16U groupKeySetIDs[] = 0; - } - - fabric command access(invoke: administer) KeySetWrite(KeySetWriteRequest): DefaultSuccess = 0; - fabric command access(invoke: administer) KeySetRead(KeySetReadRequest): KeySetReadResponse = 1; - fabric command access(invoke: administer) KeySetRemove(KeySetRemoveRequest): DefaultSuccess = 3; - fabric command access(invoke: administer) KeySetReadAllIndices(KeySetReadAllIndicesRequest): KeySetReadAllIndicesResponse = 4; -} - -server cluster FixedLabel = 64 { - readonly attribute LabelStruct labelList[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster UserLabel = 65 { - attribute access(write: manage) LabelStruct labelList[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster BooleanState = 69 { - info event StateChange = 0 { - boolean stateValue = 0; - } - - readonly attribute boolean stateValue = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ModeSelect = 80 { - bitmap ModeSelectFeature : BITMAP32 { - kDeponoff = 0x1; - } - - struct ModeOptionStruct { - char_string<32> label = 0; - int8u mode = 1; - SemanticTag semanticTags[] = 2; - } - - struct SemanticTag { - enum16 mfgCode = 0; - enum16 value = 1; - } - - readonly attribute char_string<32> description = 0; - readonly attribute nullable enum16 standardNamespace = 1; - readonly attribute ModeOptionStruct supportedModes[] = 2; - readonly attribute int8u currentMode = 3; - attribute nullable int8u startUpMode = 4; - attribute nullable int8u onMode = 5; - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - readonly attribute int8u manufacturerExtension = 4293984257; - - request struct ChangeToModeRequest { - INT8U newMode = 0; - } - - command ChangeToMode(ChangeToModeRequest): DefaultSuccess = 0; -} - -server cluster DoorLock = 257 { - enum DlAlarmCode : ENUM8 { - kLockJammed = 0; - kLockFactoryReset = 1; - kLockRadioPowerCycled = 3; - kWrongCodeEntryLimit = 4; - kFrontEsceutcheonRemoved = 5; - kDoorForcedOpen = 6; - kDoorAjar = 7; - kForcedUser = 8; - } - - enum DlCredentialRule : ENUM8 { - kSingle = 0; - kDouble = 1; - kTri = 2; - } - - enum DlCredentialType : ENUM8 { - kProgrammingPIN = 0; - kPin = 1; - kRfid = 2; - kFingerprint = 3; - kFingerVein = 4; - kFace = 5; - } - - enum DlDataOperationType : ENUM8 { - kAdd = 0; - kClear = 1; - kModify = 2; - } - - enum DlDoorState : ENUM8 { - kDoorOpen = 0; - kDoorClosed = 1; - kDoorJammed = 2; - kDoorForcedOpen = 3; - kDoorUnspecifiedError = 4; - kDoorAjar = 5; - } - - enum DlLockDataType : ENUM8 { - kUnspecified = 0; - kProgrammingCode = 1; - kUserIndex = 2; - kWeekDaySchedule = 3; - kYearDaySchedule = 4; - kHolidaySchedule = 5; - kPin = 6; - kRfid = 7; - kFingerprint = 8; - } - - enum DlLockOperationType : ENUM8 { - kLock = 0; - kUnlock = 1; - kNonAccessUserEvent = 2; - kForcedUserEvent = 3; - } - - enum DlLockState : ENUM8 { - kNotFullyLocked = 0; - kLocked = 1; - kUnlocked = 2; - } - - enum DlLockType : ENUM8 { - kDeadBolt = 0; - kMagnetic = 1; - kOther = 2; - kMortise = 3; - kRim = 4; - kLatchBolt = 5; - kCylindricalLock = 6; - kTubularLock = 7; - kInterconnectedLock = 8; - kDeadLatch = 9; - kDoorFurniture = 10; - } - - enum DlOperatingMode : ENUM8 { - kNormal = 0; - kVacation = 1; - kPrivacy = 2; - kNoRemoteLockUnlock = 3; - kPassage = 4; - } - - enum DlOperationError : ENUM8 { - kUnspecified = 0; - kInvalidCredential = 1; - kDisabledUserDenied = 2; - kRestricted = 3; - kInsufficientBattery = 4; - } - - enum DlOperationSource : ENUM8 { - kUnspecified = 0; - kManual = 1; - kProprietaryRemote = 2; - kKeypad = 3; - kAuto = 4; - kButton = 5; - kSchedule = 6; - kRemote = 7; - kRfid = 8; - kBiometric = 9; - } - - enum DlStatus : ENUM8 { - kSuccess = 0; - kFailure = 1; - kDuplicate = 2; - kOccupied = 3; - kInvalidField = 133; - kResourceExhausted = 137; - kNotFound = 139; - } - - enum DlUserStatus : ENUM8 { - kAvailable = 0; - kOccupiedEnabled = 1; - kOccupiedDisabled = 3; - } - - enum DlUserType : ENUM8 { - kUnrestrictedUser = 0; - kYearDayScheduleUser = 1; - kWeekDayScheduleUser = 2; - kProgrammingUser = 3; - kNonAccessUser = 4; - kForcedUser = 5; - kDisposableUser = 6; - kExpiringUser = 7; - kScheduleRestrictedUser = 8; - kRemoteOnlyUser = 9; - } - - enum DoorLockOperationEventCode : ENUM8 { - kUnknownOrMfgSpecific = 0; - kLock = 1; - kUnlock = 2; - kLockInvalidPinOrId = 3; - kLockInvalidSchedule = 4; - kUnlockInvalidPinOrId = 5; - kUnlockInvalidSchedule = 6; - kOneTouchLock = 7; - kKeyLock = 8; - kKeyUnlock = 9; - kAutoLock = 10; - kScheduleLock = 11; - kScheduleUnlock = 12; - kManualLock = 13; - kManualUnlock = 14; - } - - enum DoorLockProgrammingEventCode : ENUM8 { - kUnknownOrMfgSpecific = 0; - kMasterCodeChanged = 1; - kPinAdded = 2; - kPinDeleted = 3; - kPinChanged = 4; - kIdAdded = 5; - kIdDeleted = 6; - } - - enum DoorLockSetPinOrIdStatus : ENUM8 { - kSuccess = 0; - kGeneralFailure = 1; - kMemoryFull = 2; - kDuplicateCodeError = 3; - } - - enum DoorLockUserStatus : ENUM8 { - kAvailable = 0; - kOccupiedEnabled = 1; - kOccupiedDisabled = 3; - kNotSupported = 255; - } - - enum DoorLockUserType : ENUM8 { - kUnrestricted = 0; - kYearDayScheduleUser = 1; - kWeekDayScheduleUser = 2; - kMasterUser = 3; - kNonAccessUser = 4; - kNotSupported = 255; - } - - bitmap DlCredentialRuleMask : BITMAP8 { - kSingle = 0x1; - kDual = 0x2; - kTri = 0x4; - } - - bitmap DlCredentialRulesSupport : BITMAP8 { - kSingle = 0x1; - kDual = 0x2; - kTri = 0x4; - } - - bitmap DlDaysMaskMap : BITMAP8 { - kSunday = 0x1; - kMonday = 0x2; - kTuesday = 0x4; - kWednesday = 0x8; - kThursday = 0x10; - kFriday = 0x20; - kSaturday = 0x40; - } - - bitmap DlDefaultConfigurationRegister : BITMAP16 { - kEnableLocalProgrammingEnabled = 0x1; - kKeypadInterfaceDefaultAccessEnabled = 0x2; - kRemoteInterfaceDefaultAccessIsEnabled = 0x4; - kSoundEnabled = 0x20; - kAutoRelockTimeSet = 0x40; - kLEDSettingsSet = 0x80; - } - - bitmap DlKeypadOperationEventMask : BITMAP16 { - kUnknown = 0x1; - kLock = 0x2; - kUnlock = 0x4; - kLockInvalidPIN = 0x8; - kLockInvalidSchedule = 0x10; - kUnlockInvalidCode = 0x20; - kUnlockInvalidSchedule = 0x40; - kNonAccessUserOpEvent = 0x80; - } - - bitmap DlKeypadProgrammingEventMask : BITMAP16 { - kUnknown = 0x1; - kProgrammingPINChanged = 0x2; - kPINAdded = 0x4; - kPINCleared = 0x8; - kPINChanged = 0x10; - } - - bitmap DlLocalProgrammingFeatures : BITMAP8 { - kAddUsersCredentialsSchedulesLocally = 0x1; - kModifyUsersCredentialsSchedulesLocally = 0x2; - kClearUsersCredentialsSchedulesLocally = 0x4; - kAdjustLockSettingsLocally = 0x8; - } - - bitmap DlManualOperationEventMask : BITMAP16 { - kUnknown = 0x1; - kThumbturnLock = 0x2; - kThumbturnUnlock = 0x4; - kOneTouchLock = 0x8; - kKeyLock = 0x10; - kKeyUnlock = 0x20; - kAutoLock = 0x40; - kScheduleLock = 0x80; - kScheduleUnlock = 0x100; - kManualLock = 0x200; - kManualUnlock = 0x400; - } - - bitmap DlRFIDOperationEventMask : BITMAP16 { - kUnknown = 0x1; - kLock = 0x2; - kUnlock = 0x4; - kLockInvalidRFID = 0x8; - kLockInvalidSchedule = 0x10; - kUnlockInvalidRFID = 0x20; - kUnlockInvalidSchedule = 0x40; - } - - bitmap DlRFIDProgrammingEventMask : BITMAP16 { - kUnknown = 0x1; - kRFIDCodeAdded = 0x20; - kRFIDCodeCleared = 0x40; - } - - bitmap DlRemoteOperationEventMask : BITMAP16 { - kUnknown = 0x1; - kLock = 0x2; - kUnlock = 0x4; - kLockInvalidCode = 0x8; - kLockInvalidSchedule = 0x10; - kUnlockInvalidCode = 0x20; - kUnlockInvalidSchedule = 0x40; - } - - bitmap DlRemoteProgrammingEventMask : BITMAP16 { - kUnknown = 0x1; - kProgrammingPINChanged = 0x2; - kPINAdded = 0x4; - kPINCleared = 0x8; - kPINChanged = 0x10; - kRFIDCodeAdded = 0x20; - kRFIDCodeCleared = 0x40; - } - - bitmap DlSupportedOperatingModes : BITMAP16 { - kNormal = 0x1; - kVacation = 0x2; - kPrivacy = 0x4; - kNoRemoteLockUnlock = 0x8; - kPassage = 0x10; - } - - bitmap DoorLockDayOfWeek : BITMAP8 { - kSunday = 0x1; - kMonday = 0x2; - kTuesday = 0x4; - kWednesday = 0x8; - kThursday = 0x10; - kFriday = 0x20; - kSaturday = 0x40; - } - - bitmap DoorLockFeature : BITMAP32 { - kPINCredentials = 0x1; - kRFIDCredentials = 0x2; - kFingerCredentials = 0x4; - kLogging = 0x8; - kWeekDaySchedules = 0x10; - kDoorPositionSensor = 0x20; - kFaceCredentials = 0x40; - kCredentialsOTA = 0x80; - kUsersManagement = 0x100; - kNotifications = 0x200; - kYearDaySchedules = 0x400; - kHolidaySchedules = 0x800; - } - - struct DlCredential { - DlCredentialType credentialType = 0; - int16u credentialIndex = 1; - } - - critical event DoorLockAlarm = 0 { - DlAlarmCode alarmCode = 0; - } - - critical event DoorStateChange = 1 { - DlDoorState doorState = 0; - } - - critical event LockOperation = 2 { - DlLockOperationType lockOperationType = 0; - DlOperationSource operationSource = 1; - nullable INT16U userIndex = 2; - nullable fabric_idx fabricIndex = 3; - nullable NODE_ID sourceNode = 4; - optional nullable DlCredential credentials[] = 5; - } - - critical event LockOperationError = 3 { - DlLockOperationType lockOperationType = 0; - DlOperationSource operationSource = 1; - DlOperationError operationError = 2; - nullable INT16U userIndex = 3; - nullable fabric_idx fabricIndex = 4; - nullable NODE_ID sourceNode = 5; - optional nullable DlCredential credentials[] = 6; - } - - info event LockUserChange = 4 { - DlLockDataType lockDataType = 0; - DlDataOperationType dataOperationType = 1; - DlOperationSource operationSource = 2; - nullable INT16U userIndex = 3; - nullable fabric_idx fabricIndex = 4; - nullable NODE_ID sourceNode = 5; - nullable INT16U dataIndex = 6; - } - - readonly attribute nullable DlLockState lockState = 0; - readonly attribute DlLockType lockType = 1; - readonly attribute boolean actuatorEnabled = 2; - readonly attribute nullable DlDoorState doorState = 3; - attribute access(write: manage) int32u doorOpenEvents = 4; - attribute access(write: manage) int32u doorClosedEvents = 5; - attribute access(write: manage) int16u openPeriod = 6; - readonly attribute int16u numberOfTotalUsersSupported = 17; - readonly attribute int16u numberOfPINUsersSupported = 18; - readonly attribute int16u numberOfRFIDUsersSupported = 19; - readonly attribute int8u numberOfWeekDaySchedulesSupportedPerUser = 20; - readonly attribute int8u numberOfYearDaySchedulesSupportedPerUser = 21; - readonly attribute int8u numberOfHolidaySchedulesSupported = 22; - readonly attribute int8u maxPINCodeLength = 23; - readonly attribute int8u minPINCodeLength = 24; - readonly attribute int8u maxRFIDCodeLength = 25; - readonly attribute int8u minRFIDCodeLength = 26; - readonly attribute DlCredentialRuleMask credentialRulesSupport = 27; - readonly attribute int8u numberOfCredentialsSupportedPerUser = 28; - attribute access(write: manage) char_string<3> language = 33; - attribute access(write: manage) int32u autoRelockTime = 35; - attribute access(write: manage) int8u soundVolume = 36; - attribute access(write: manage) DlOperatingMode operatingMode = 37; - readonly attribute DlSupportedOperatingModes supportedOperatingModes = 38; - readonly attribute DlDefaultConfigurationRegister defaultConfigurationRegister = 39; - attribute access(write: manage) boolean enableOneTouchLocking = 41; - attribute access(write: manage) boolean enableInsideStatusLED = 42; - attribute access(write: manage) boolean enablePrivacyModeButton = 43; - attribute access(write: administer) int8u wrongCodeEntryLimit = 48; - attribute access(write: administer) int8u userCodeTemporaryDisableTime = 49; - attribute access(write: administer) boolean requirePINforRemoteOperation = 51; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct LockDoorRequest { - optional OCTET_STRING pinCode = 0; - } - - request struct UnlockDoorRequest { - optional OCTET_STRING pinCode = 0; - } - - request struct UnlockWithTimeoutRequest { - INT16U timeout = 0; - optional OCTET_STRING pinCode = 1; - } - - request struct SetWeekDayScheduleRequest { - INT8U weekDayIndex = 0; - INT16U userIndex = 1; - DlDaysMaskMap daysMask = 2; - INT8U startHour = 3; - INT8U startMinute = 4; - INT8U endHour = 5; - INT8U endMinute = 6; - } - - request struct GetWeekDayScheduleRequest { - INT8U weekDayIndex = 0; - INT16U userIndex = 1; - } - - request struct ClearWeekDayScheduleRequest { - INT8U weekDayIndex = 0; - INT16U userIndex = 1; - } - - request struct SetYearDayScheduleRequest { - INT8U yearDayIndex = 0; - INT16U userIndex = 1; - epoch_s localStartTime = 2; - epoch_s localEndTime = 3; - } - - request struct GetYearDayScheduleRequest { - INT8U yearDayIndex = 0; - INT16U userIndex = 1; - } - - request struct SetUserRequest { - DlDataOperationType operationType = 0; - INT16U userIndex = 1; - nullable CHAR_STRING userName = 2; - nullable INT32U userUniqueId = 3; - nullable DlUserStatus userStatus = 4; - nullable DlUserType userType = 5; - nullable DlCredentialRule credentialRule = 6; - } - - request struct GetUserRequest { - INT16U userIndex = 0; - } - - request struct ClearUserRequest { - INT16U userIndex = 0; - } - - request struct SetCredentialRequest { - DlDataOperationType operationType = 0; - DlCredential credential = 1; - LONG_OCTET_STRING credentialData = 2; - nullable INT16U userIndex = 3; - nullable DlUserStatus userStatus = 4; - nullable DlUserType userType = 5; - } - - request struct GetCredentialStatusRequest { - DlCredential credential = 0; - } - - request struct ClearCredentialRequest { - nullable DlCredential credential = 0; - } - - response struct GetUserResponse = 28 { - INT16U userIndex = 0; - nullable CHAR_STRING userName = 1; - nullable INT32U userUniqueId = 2; - nullable DlUserStatus userStatus = 3; - nullable DlUserType userType = 4; - nullable DlCredentialRule credentialRule = 5; - nullable DlCredential credentials[] = 6; - nullable fabric_idx creatorFabricIndex = 7; - nullable fabric_idx lastModifiedFabricIndex = 8; - nullable INT16U nextUserIndex = 9; - } - - response struct SetCredentialResponse = 35 { - DlStatus status = 0; - nullable INT16U userIndex = 1; - nullable INT16U nextCredentialIndex = 2; - } - - response struct GetCredentialStatusResponse = 37 { - boolean credentialExists = 0; - nullable INT16U userIndex = 1; - nullable fabric_idx creatorFabricIndex = 2; - nullable fabric_idx lastModifiedFabricIndex = 3; - nullable INT16U nextCredentialIndex = 4; - } - - timed command LockDoor(LockDoorRequest): DefaultSuccess = 0; - timed command UnlockDoor(UnlockDoorRequest): DefaultSuccess = 1; - timed command UnlockWithTimeout(UnlockWithTimeoutRequest): DefaultSuccess = 3; - command access(invoke: administer) SetWeekDaySchedule(SetWeekDayScheduleRequest): DefaultSuccess = 11; - command access(invoke: administer) GetWeekDaySchedule(GetWeekDayScheduleRequest): GetWeekDayScheduleResponse = 12; - command access(invoke: administer) ClearWeekDaySchedule(ClearWeekDayScheduleRequest): DefaultSuccess = 13; - command access(invoke: administer) SetYearDaySchedule(SetYearDayScheduleRequest): DefaultSuccess = 14; - command access(invoke: administer) GetYearDaySchedule(GetYearDayScheduleRequest): GetYearDayScheduleResponse = 15; - timed command access(invoke: administer) SetUser(SetUserRequest): DefaultSuccess = 26; - command access(invoke: administer) GetUser(GetUserRequest): GetUserResponse = 27; - timed command access(invoke: administer) ClearUser(ClearUserRequest): DefaultSuccess = 29; - timed command access(invoke: administer) SetCredential(SetCredentialRequest): SetCredentialResponse = 34; - command access(invoke: administer) GetCredentialStatus(GetCredentialStatusRequest): GetCredentialStatusResponse = 36; - timed command access(invoke: administer) ClearCredential(ClearCredentialRequest): DefaultSuccess = 38; -} - -server cluster WindowCovering = 258 { - enum EndProductType : ENUM8 { - kRollerShade = 0; - kRomanShade = 1; - kBalloonShade = 2; - kWovenWood = 3; - kPleatedShade = 4; - kCellularShade = 5; - kLayeredShade = 6; - kLayeredShade2D = 7; - kSheerShade = 8; - kTiltOnlyInteriorBlind = 9; - kInteriorBlind = 10; - kVerticalBlindStripCurtain = 11; - kInteriorVenetianBlind = 12; - kExteriorVenetianBlind = 13; - kLateralLeftCurtain = 14; - kLateralRightCurtain = 15; - kCentralCurtain = 16; - kRollerShutter = 17; - kExteriorVerticalScreen = 18; - kAwningTerracePatio = 19; - kAwningVerticalScreen = 20; - kTiltOnlyPergola = 21; - kSwingingShutter = 22; - kSlidingShutter = 23; - kUnknown = 255; - } - - enum Type : ENUM8 { - kRollerShade = 0; - kRollerShade2Motor = 1; - kRollerShadeExterior = 2; - kRollerShadeExterior2Motor = 3; - kDrapery = 4; - kAwning = 5; - kShutter = 6; - kTiltBlindTiltOnly = 7; - kTiltBlindLiftAndTilt = 8; - kProjectorScreen = 9; - kUnknown = 255; - } - - bitmap ConfigStatus : BITMAP8 { - kOperational = 0x1; - kOnlineReserved = 0x2; - kLiftMovementReversed = 0x4; - kLiftPositionAware = 0x8; - kTiltPositionAware = 0x10; - kLiftEncoderControlled = 0x20; - kTiltEncoderControlled = 0x40; - } - - bitmap Feature : BITMAP32 { - kLift = 0x1; - kTilt = 0x2; - kPositionAwareLift = 0x4; - kAbsolutePosition = 0x8; - kPositionAwareTilt = 0x10; - } - - bitmap Mode : BITMAP8 { - kMotorDirectionReversed = 0x1; - kCalibrationMode = 0x2; - kMaintenanceMode = 0x4; - kLedFeedback = 0x8; - } - - bitmap OperationalStatus : BITMAP8 { - kGlobal = 0x3; - kLift = 0xC; - kTilt = 0x30; - } - - bitmap SafetyStatus : BITMAP16 { - kRemoteLockout = 0x1; - kTamperDetection = 0x2; - kFailedCommunication = 0x4; - kPositionFailure = 0x8; - kThermalProtection = 0x10; - kObstacleDetected = 0x20; - kPower = 0x40; - kStopInput = 0x80; - kMotorJammed = 0x100; - kHardwareFailure = 0x200; - kManualOperation = 0x400; - kProtection = 0x800; - } - - readonly attribute Type type = 0; - readonly attribute int16u physicalClosedLimitLift = 1; - readonly attribute int16u physicalClosedLimitTilt = 2; - readonly attribute nullable int16u currentPositionLift = 3; - readonly attribute nullable int16u currentPositionTilt = 4; - readonly attribute int16u numberOfActuationsLift = 5; - readonly attribute int16u numberOfActuationsTilt = 6; - readonly attribute ConfigStatus configStatus = 7; - readonly attribute nullable Percent currentPositionLiftPercentage = 8; - readonly attribute nullable Percent currentPositionTiltPercentage = 9; - readonly attribute OperationalStatus operationalStatus = 10; - readonly attribute nullable Percent100ths targetPositionLiftPercent100ths = 11; - readonly attribute nullable Percent100ths targetPositionTiltPercent100ths = 12; - readonly attribute EndProductType endProductType = 13; - readonly attribute nullable Percent100ths currentPositionLiftPercent100ths = 14; - readonly attribute nullable Percent100ths currentPositionTiltPercent100ths = 15; - readonly attribute int16u installedOpenLimitLift = 16; - readonly attribute int16u installedClosedLimitLift = 17; - readonly attribute int16u installedOpenLimitTilt = 18; - readonly attribute int16u installedClosedLimitTilt = 19; - attribute access(write: manage) Mode mode = 23; - readonly attribute SafetyStatus safetyStatus = 26; - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct GoToLiftValueRequest { - INT16U liftValue = 0; - } - - request struct GoToLiftPercentageRequest { - Percent100ths liftPercent100thsValue = 0; - } - - request struct GoToTiltValueRequest { - INT16U tiltValue = 0; - } - - request struct GoToTiltPercentageRequest { - Percent100ths tiltPercent100thsValue = 0; - } - - command UpOrOpen(): DefaultSuccess = 0; - command DownOrClose(): DefaultSuccess = 1; - command StopMotion(): DefaultSuccess = 2; - command GoToLiftValue(GoToLiftValueRequest): DefaultSuccess = 4; - command GoToLiftPercentage(GoToLiftPercentageRequest): DefaultSuccess = 5; - command GoToTiltValue(GoToTiltValueRequest): DefaultSuccess = 7; - command GoToTiltPercentage(GoToTiltPercentageRequest): DefaultSuccess = 8; -} - -server cluster BarrierControl = 259 { - readonly attribute enum8 barrierMovingState = 1; - readonly attribute bitmap16 barrierSafetyStatus = 2; - readonly attribute bitmap8 barrierCapabilities = 3; - readonly attribute int8u barrierPosition = 10; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct BarrierControlGoToPercentRequest { - INT8U percentOpen = 0; - } - - command BarrierControlGoToPercent(BarrierControlGoToPercentRequest): DefaultSuccess = 0; - command BarrierControlStop(): DefaultSuccess = 1; -} - -server cluster PumpConfigurationAndControl = 512 { - enum PumpControlMode : ENUM8 { - kConstantSpeed = 0; - kConstantPressure = 1; - kProportionalPressure = 2; - kConstantFlow = 3; - kConstantTemperature = 5; - kAutomatic = 7; - } - - enum PumpOperationMode : ENUM8 { - kNormal = 0; - kMinimum = 1; - kMaximum = 2; - kLocal = 3; - } - - bitmap PumpStatus : BITMAP16 { - kDeviceFault = 0x1; - kSupplyfault = 0x2; - kSpeedLow = 0x4; - kSpeedHigh = 0x8; - kLocalOverride = 0x10; - kRunning = 0x20; - kRemotePressure = 0x40; - kRemoteFlow = 0x80; - kRemoteTemperature = 0x100; - } - - info event SupplyVoltageLow = 0 { - } - - info event SupplyVoltageHigh = 1 { - } - - info event PowerMissingPhase = 2 { - } - - info event SystemPressureLow = 3 { - } - - info event SystemPressureHigh = 4 { - } - - critical event DryRunning = 5 { - } - - info event MotorTemperatureHigh = 6 { - } - - critical event PumpMotorFatalFailure = 7 { - } - - info event ElectronicTemperatureHigh = 8 { - } - - critical event PumpBlocked = 9 { - } - - info event SensorFailure = 10 { - } - - info event ElectronicNonFatalFailure = 11 { - } - - critical event ElectronicFatalFailure = 12 { - } - - info event GeneralFault = 13 { - } - - info event Leakage = 14 { - } - - info event AirDetection = 15 { - } - - info event TurbineOperation = 16 { - } - - readonly attribute nullable int16s maxPressure = 0; - readonly attribute nullable int16u maxSpeed = 1; - readonly attribute nullable int16u maxFlow = 2; - readonly attribute nullable int16s minConstPressure = 3; - readonly attribute nullable int16s maxConstPressure = 4; - readonly attribute nullable int16s minCompPressure = 5; - readonly attribute nullable int16s maxCompPressure = 6; - readonly attribute nullable int16u minConstSpeed = 7; - readonly attribute nullable int16u maxConstSpeed = 8; - readonly attribute nullable int16u minConstFlow = 9; - readonly attribute nullable int16u maxConstFlow = 10; - readonly attribute nullable int16s minConstTemp = 11; - readonly attribute nullable int16s maxConstTemp = 12; - readonly attribute PumpStatus pumpStatus = 16; - readonly attribute PumpOperationMode effectiveOperationMode = 17; - readonly attribute PumpControlMode effectiveControlMode = 18; - readonly attribute nullable int16s capacity = 19; - readonly attribute nullable int16u speed = 20; - attribute access(write: manage) nullable int24u lifetimeRunningHours = 21; - readonly attribute nullable int24u power = 22; - attribute access(write: manage) nullable int32u lifetimeEnergyConsumed = 23; - attribute access(write: manage) PumpOperationMode operationMode = 32; - attribute access(write: manage) PumpControlMode controlMode = 33; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster Thermostat = 513 { - enum SetpointAdjustMode : ENUM8 { - kHeatSetpoint = 0; - kCoolSetpoint = 1; - kHeatAndCoolSetpoints = 2; - } - - enum ThermostatControlSequence : ENUM8 { - kCoolingOnly = 0; - kCoolingWithReheat = 1; - kHeatingOnly = 2; - kHeatingWithReheat = 3; - kCoolingAndHeating = 4; - kCoolingAndHeatingWithReheat = 5; - } - - enum ThermostatRunningMode : ENUM8 { - kOff = 0; - kCool = 3; - kHeat = 4; - } - - enum ThermostatSystemMode : ENUM8 { - kOff = 0; - kAuto = 1; - kCool = 3; - kHeat = 4; - kEmergencyHeating = 5; - kPrecooling = 6; - kFanOnly = 7; - } - - bitmap DayOfWeek : BITMAP8 { - kSunday = 0x1; - kMonday = 0x2; - kTuesday = 0x4; - kWednesday = 0x8; - kThursday = 0x10; - kFriday = 0x20; - kSaturday = 0x40; - kAwayOrVacation = 0x80; - } - - bitmap ModeForSequence : BITMAP8 { - kHeatSetpointFieldPresent = 0x1; - kCoolSetpointFieldPresent = 0x2; - } - - bitmap ThermostatFeature : BITMAP32 { - kHeating = 0x1; - kCooling = 0x2; - kOccupancy = 0x4; - kSchedule = 0x8; - kSetback = 0x10; - kAutomode = 0x20; - } - - struct ThermostatScheduleTransition { - int16u transitionTime = 0; - nullable int16s heatSetpoint = 1; - nullable int16s coolSetpoint = 2; - } - - readonly attribute nullable int16s localTemperature = 0; - readonly attribute int16s absMinHeatSetpointLimit = 3; - readonly attribute int16s absMaxHeatSetpointLimit = 4; - readonly attribute int16s absMinCoolSetpointLimit = 5; - readonly attribute int16s absMaxCoolSetpointLimit = 6; - attribute int16s occupiedCoolingSetpoint = 17; - attribute int16s occupiedHeatingSetpoint = 18; - attribute access(write: manage) int16s minHeatSetpointLimit = 21; - attribute access(write: manage) int16s maxHeatSetpointLimit = 22; - attribute access(write: manage) int16s minCoolSetpointLimit = 23; - attribute access(write: manage) int16s maxCoolSetpointLimit = 24; - attribute access(write: manage) int8s minSetpointDeadBand = 25; - attribute access(write: manage) ThermostatControlSequence controlSequenceOfOperation = 27; - attribute access(write: manage) enum8 systemMode = 28; - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct SetpointRaiseLowerRequest { - SetpointAdjustMode mode = 0; - INT8S amount = 1; - } - - command SetpointRaiseLower(SetpointRaiseLowerRequest): DefaultSuccess = 0; -} - -server cluster FanControl = 514 { - enum FanModeSequenceType : ENUM8 { - kOffLowMedHigh = 0; - kOffLowHigh = 1; - kOffLowMedHighAuto = 2; - kOffLowHighAuto = 3; - kOffOnAuto = 4; - kOffOn = 5; - } - - enum FanModeType : ENUM8 { - kOff = 0; - kLow = 1; - kMedium = 2; - kHigh = 3; - kOn = 4; - kAuto = 5; - kSmart = 6; - } - - bitmap FanControlFeature : BITMAP32 { - kMultiSpeed = 0x1; - kAuto = 0x2; - kRocking = 0x4; - kWind = 0x8; - } - - bitmap RockSupportMask : BITMAP8 { - kRockLeftRight = 0x1; - kRockUpDown = 0x2; - kRockRound = 0x4; - } - - bitmap WindSettingMask : BITMAP8 { - kSleepWind = 0x1; - kNaturalWind = 0x2; - } - - bitmap WindSupportMask : BITMAP8 { - kSleepWind = 0x1; - kNaturalWind = 0x2; - } - - attribute FanModeType fanMode = 0; - attribute FanModeSequenceType fanModeSequence = 1; - attribute nullable int8u percentSetting = 2; - readonly attribute int8u percentCurrent = 3; - readonly attribute int8u speedMax = 4; - attribute nullable int8u speedSetting = 5; - readonly attribute int8u speedCurrent = 6; - readonly attribute bitmap8 rockSupport = 7; - attribute bitmap8 rockSetting = 8; - readonly attribute bitmap8 windSupport = 9; - attribute bitmap8 windSetting = 10; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ThermostatUserInterfaceConfiguration = 516 { - attribute enum8 temperatureDisplayMode = 0; - attribute access(write: manage) enum8 keypadLockout = 1; - attribute access(write: manage) enum8 scheduleProgrammingVisibility = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ColorControl = 768 { - enum ColorLoopAction : ENUM8 { - kDeactivate = 0; - kActivateFromColorLoopStartEnhancedHue = 1; - kActivateFromEnhancedCurrentHue = 2; - } - - enum ColorLoopDirection : ENUM8 { - kDecrementHue = 0; - kIncrementHue = 1; - } - - enum ColorMode : ENUM8 { - kCurrentHueAndCurrentSaturation = 0; - kCurrentXAndCurrentY = 1; - kColorTemperature = 2; - } - - enum HueDirection : ENUM8 { - kShortestDistance = 0; - kLongestDistance = 1; - kUp = 2; - kDown = 3; - } - - enum HueMoveMode : ENUM8 { - kStop = 0; - kUp = 1; - kDown = 3; - } - - enum HueStepMode : ENUM8 { - kUp = 1; - kDown = 3; - } - - enum SaturationMoveMode : ENUM8 { - kStop = 0; - kUp = 1; - kDown = 3; - } - - enum SaturationStepMode : ENUM8 { - kUp = 1; - kDown = 3; - } - - bitmap ColorCapabilities : BITMAP16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorControlFeature : BITMAP32 { - kHueAndSaturation = 0x1; - kEnhancedHue = 0x2; - kColorLoop = 0x4; - kXy = 0x8; - kColorTemperature = 0x10; - } - - bitmap ColorLoopUpdateFlags : BITMAP8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; - } - - readonly attribute int8u currentHue = 0; - readonly attribute int8u currentSaturation = 1; - readonly attribute int16u remainingTime = 2; - readonly attribute int16u currentX = 3; - readonly attribute int16u currentY = 4; - readonly attribute enum8 driftCompensation = 5; - readonly attribute char_string<254> compensationText = 6; - readonly attribute int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; - readonly attribute nullable int8u numberOfPrimaries = 16; - readonly attribute int16u primary1X = 17; - readonly attribute int16u primary1Y = 18; - readonly attribute nullable int8u primary1Intensity = 19; - readonly attribute int16u primary2X = 21; - readonly attribute int16u primary2Y = 22; - readonly attribute nullable int8u primary2Intensity = 23; - readonly attribute int16u primary3X = 25; - readonly attribute int16u primary3Y = 26; - readonly attribute nullable int8u primary3Intensity = 27; - readonly attribute int16u primary4X = 32; - readonly attribute int16u primary4Y = 33; - readonly attribute nullable int8u primary4Intensity = 34; - readonly attribute int16u primary5X = 36; - readonly attribute int16u primary5Y = 37; - readonly attribute nullable int8u primary5Intensity = 38; - readonly attribute int16u primary6X = 40; - readonly attribute int16u primary6Y = 41; - readonly attribute nullable int8u primary6Intensity = 42; - attribute access(write: manage) int16u whitePointX = 48; - attribute access(write: manage) int16u whitePointY = 49; - attribute access(write: manage) int16u colorPointRX = 50; - attribute access(write: manage) int16u colorPointRY = 51; - attribute access(write: manage) nullable int8u colorPointRIntensity = 52; - attribute access(write: manage) int16u colorPointGX = 54; - attribute access(write: manage) int16u colorPointGY = 55; - attribute access(write: manage) nullable int8u colorPointGIntensity = 56; - attribute access(write: manage) int16u colorPointBX = 58; - attribute access(write: manage) int16u colorPointBY = 59; - attribute access(write: manage) nullable int8u colorPointBIntensity = 60; - readonly attribute int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; - readonly attribute int8u colorLoopActive = 16386; - readonly attribute int8u colorLoopDirection = 16387; - readonly attribute int16u colorLoopTime = 16388; - readonly attribute int16u colorLoopStartEnhancedHue = 16389; - readonly attribute int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; - readonly attribute int16u colorTempPhysicalMinMireds = 16395; - readonly attribute int16u colorTempPhysicalMaxMireds = 16396; - readonly attribute int16u coupleColorTempToLevelMinMireds = 16397; - attribute access(write: manage) nullable int16u startUpColorTemperatureMireds = 16400; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct MoveToHueRequest { - INT8U hue = 0; - HueDirection direction = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveHueRequest { - HueMoveMode moveMode = 0; - INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepHueRequest { - HueStepMode stepMode = 0; - INT8U stepSize = 1; - INT8U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToSaturationRequest { - INT8U saturation = 0; - INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; - INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; - INT8U stepSize = 1; - INT8U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToHueAndSaturationRequest { - INT8U hue = 0; - INT8U saturation = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToColorRequest { - INT16U colorX = 0; - INT16U colorY = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveColorRequest { - INT16S rateX = 0; - INT16S rateY = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepColorRequest { - INT16S stepX = 0; - INT16S stepY = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToColorTemperatureRequest { - INT16U colorTemperature = 0; - INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct EnhancedMoveToHueRequest { - INT16U enhancedHue = 0; - HueDirection direction = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; - INT16U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; - INT16U stepSize = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct EnhancedMoveToHueAndSaturationRequest { - INT16U enhancedHue = 0; - INT8U saturation = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; - INT16U time = 3; - INT16U startHue = 4; - BITMAP8 optionsMask = 5; - BITMAP8 optionsOverride = 6; - } - - request struct StopMoveStepRequest { - BITMAP8 optionsMask = 0; - BITMAP8 optionsOverride = 1; - } - - request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; - INT16U rate = 1; - INT16U colorTemperatureMinimumMireds = 2; - INT16U colorTemperatureMaximumMireds = 3; - BITMAP8 optionsMask = 4; - BITMAP8 optionsOverride = 5; - } - - request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; - INT16U stepSize = 1; - INT16U transitionTime = 2; - INT16U colorTemperatureMinimumMireds = 3; - INT16U colorTemperatureMaximumMireds = 4; - BITMAP8 optionsMask = 5; - BITMAP8 optionsOverride = 6; - } - - command MoveToHue(MoveToHueRequest): DefaultSuccess = 0; - command MoveHue(MoveHueRequest): DefaultSuccess = 1; - command StepHue(StepHueRequest): DefaultSuccess = 2; - command MoveToSaturation(MoveToSaturationRequest): DefaultSuccess = 3; - command MoveSaturation(MoveSaturationRequest): DefaultSuccess = 4; - command StepSaturation(StepSaturationRequest): DefaultSuccess = 5; - command MoveToHueAndSaturation(MoveToHueAndSaturationRequest): DefaultSuccess = 6; - command MoveToColor(MoveToColorRequest): DefaultSuccess = 7; - command MoveColor(MoveColorRequest): DefaultSuccess = 8; - command StepColor(StepColorRequest): DefaultSuccess = 9; - command MoveToColorTemperature(MoveToColorTemperatureRequest): DefaultSuccess = 10; - command EnhancedMoveToHue(EnhancedMoveToHueRequest): DefaultSuccess = 64; - command EnhancedMoveHue(EnhancedMoveHueRequest): DefaultSuccess = 65; - command EnhancedStepHue(EnhancedStepHueRequest): DefaultSuccess = 66; - command EnhancedMoveToHueAndSaturation(EnhancedMoveToHueAndSaturationRequest): DefaultSuccess = 67; - command ColorLoopSet(ColorLoopSetRequest): DefaultSuccess = 68; - command StopMoveStep(StopMoveStepRequest): DefaultSuccess = 71; - command MoveColorTemperature(MoveColorTemperatureRequest): DefaultSuccess = 75; - command StepColorTemperature(StepColorTemperatureRequest): DefaultSuccess = 76; -} - -server cluster IlluminanceMeasurement = 1024 { - enum LightSensorType : ENUM8 { - kPhotodiode = 0; - kCmos = 1; - } - - readonly attribute nullable int16u measuredValue = 0; - readonly attribute nullable int16u minMeasuredValue = 1; - readonly attribute nullable int16u maxMeasuredValue = 2; - readonly attribute int16u tolerance = 3; - readonly attribute nullable enum8 lightSensorType = 4; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster TemperatureMeasurement = 1026 { - readonly attribute nullable int16s measuredValue = 0; - readonly attribute nullable int16s minMeasuredValue = 1; - readonly attribute nullable int16s maxMeasuredValue = 2; - readonly attribute int16u tolerance = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster PressureMeasurement = 1027 { - bitmap PressureFeature : BITMAP32 { - kExt = 0x1; - } - - readonly attribute nullable int16s measuredValue = 0; - readonly attribute nullable int16s minMeasuredValue = 1; - readonly attribute nullable int16s maxMeasuredValue = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster FlowMeasurement = 1028 { - readonly attribute nullable int16u measuredValue = 0; - readonly attribute nullable int16u minMeasuredValue = 1; - readonly attribute nullable int16u maxMeasuredValue = 2; - readonly attribute int16u tolerance = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster RelativeHumidityMeasurement = 1029 { - readonly attribute nullable int16u measuredValue = 0; - readonly attribute nullable int16u minMeasuredValue = 1; - readonly attribute nullable int16u maxMeasuredValue = 2; - readonly attribute int16u tolerance = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster OccupancySensing = 1030 { - readonly attribute bitmap8 occupancy = 0; - readonly attribute enum8 occupancySensorType = 1; - readonly attribute bitmap8 occupancySensorTypeBitmap = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster WakeOnLan = 1283 { - readonly attribute char_string<32> MACAddress = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster Channel = 1284 { - enum ChannelStatusEnum : ENUM8 { - kSuccess = 0; - kMultipleMatches = 1; - kNoMatches = 2; - } - - enum LineupInfoTypeEnum : ENUM8 { - kMso = 0; - } - - bitmap ChannelFeature : BITMAP32 { - kChannelList = 0x1; - kLineupInfo = 0x2; - } - - struct ChannelInfo { - int16u majorNumber = 0; - int16u minorNumber = 1; - optional char_string<32> name = 2; - optional char_string<32> callSign = 3; - optional char_string<32> affiliateCallSign = 4; - } - - readonly attribute ChannelInfo channelList[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster TargetNavigator = 1285 { - enum TargetNavigatorStatusEnum : ENUM8 { - kSuccess = 0; - kTargetNotFound = 1; - kNotAllowed = 2; - } - - struct TargetInfo { - int8u identifier = 0; - char_string<32> name = 1; - } - - readonly attribute TargetInfo targetList[] = 0; - readonly attribute int8u currentTarget = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct NavigateTargetRequest { - INT8U target = 0; - optional CHAR_STRING data = 1; - } - - response struct NavigateTargetResponse = 1 { - TargetNavigatorStatusEnum status = 0; - optional CHAR_STRING data = 1; - } - - command NavigateTarget(NavigateTargetRequest): NavigateTargetResponse = 0; -} - -server cluster MediaPlayback = 1286 { - enum MediaPlaybackStatusEnum : ENUM8 { - kSuccess = 0; - kInvalidStateForCommand = 1; - kNotAllowed = 2; - kNotActive = 3; - kSpeedOutOfRange = 4; - kSeekOutOfRange = 5; - } - - enum PlaybackStateEnum : ENUM8 { - kPlaying = 0; - kPaused = 1; - kNotPlaying = 2; - kBuffering = 3; - } - - bitmap MediaPlaybackFeature : BITMAP32 { - kAdvancedSeek = 0x1; - kVariableSpeed = 0x2; - } - - readonly attribute PlaybackStateEnum currentState = 0; - readonly attribute nullable epoch_us startTime = 1; - readonly attribute nullable int64u duration = 2; - readonly attribute single playbackSpeed = 4; - readonly attribute nullable int64u seekRangeEnd = 5; - readonly attribute nullable int64u seekRangeStart = 6; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster MediaInput = 1287 { - enum InputTypeEnum : ENUM8 { - kInternal = 0; - kAux = 1; - kCoax = 2; - kComposite = 3; - kHdmi = 4; - kInput = 5; - kLine = 6; - kOptical = 7; - kVideo = 8; - kScart = 9; - kUsb = 10; - kOther = 11; - } - - bitmap MediaInputFeature : BITMAP32 { - kNameUpdates = 0x1; - } - - struct InputInfo { - int8u index = 0; - InputTypeEnum inputType = 1; - char_string<32> name = 2; - char_string<32> description = 3; - } - - readonly attribute InputInfo inputList[] = 0; - readonly attribute int8u currentInput = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct SelectInputRequest { - INT8U index = 0; - } - - request struct RenameInputRequest { - INT8U index = 0; - CHAR_STRING name = 1; - } - - command SelectInput(SelectInputRequest): DefaultSuccess = 0; - command ShowInputStatus(): DefaultSuccess = 1; - command HideInputStatus(): DefaultSuccess = 2; - command RenameInput(RenameInputRequest): DefaultSuccess = 3; -} - -server cluster LowPower = 1288 { - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command Sleep(): DefaultSuccess = 0; -} - -server cluster KeypadInput = 1289 { - enum CecKeyCode : ENUM8 { - kSelect = 0; - kUp = 1; - kDown = 2; - kLeft = 3; - kRight = 4; - kRightUp = 5; - kRightDown = 6; - kLeftUp = 7; - kLeftDown = 8; - kRootMenu = 9; - kSetupMenu = 10; - kContentsMenu = 11; - kFavoriteMenu = 12; - kExit = 13; - kMediaTopMenu = 16; - kMediaContextSensitiveMenu = 17; - kNumberEntryMode = 29; - kNumber11 = 30; - kNumber12 = 31; - kNumber0OrNumber10 = 32; - kNumbers1 = 33; - kNumbers2 = 34; - kNumbers3 = 35; - kNumbers4 = 36; - kNumbers5 = 37; - kNumbers6 = 38; - kNumbers7 = 39; - kNumbers8 = 40; - kNumbers9 = 41; - kDot = 42; - kEnter = 43; - kClear = 44; - kNextFavorite = 47; - kChannelUp = 48; - kChannelDown = 49; - kPreviousChannel = 50; - kSoundSelect = 51; - kInputSelect = 52; - kDisplayInformation = 53; - kHelp = 54; - kPageUp = 55; - kPageDown = 56; - kPower = 64; - kVolumeUp = 65; - kVolumeDown = 66; - kMute = 67; - kPlay = 68; - kStop = 69; - kPause = 70; - kRecord = 71; - kRewind = 72; - kFastForward = 73; - kEject = 74; - kForward = 75; - kBackward = 76; - kStopRecord = 77; - kPauseRecord = 78; - kReserved = 79; - kAngle = 80; - kSubPicture = 81; - kVideoOnDemand = 82; - kElectronicProgramGuide = 83; - kTimerProgramming = 84; - kInitialConfiguration = 85; - kSelectBroadcastType = 86; - kSelectSoundPresentation = 87; - kPlayFunction = 96; - kPausePlayFunction = 97; - kRecordFunction = 98; - kPauseRecordFunction = 99; - kStopFunction = 100; - kMuteFunction = 101; - kRestoreVolumeFunction = 102; - kTuneFunction = 103; - kSelectMediaFunction = 104; - kSelectAvInputFunction = 105; - kSelectAudioInputFunction = 106; - kPowerToggleFunction = 107; - kPowerOffFunction = 108; - kPowerOnFunction = 109; - kF1Blue = 113; - kF2Red = 114; - kF3Green = 115; - kF4Yellow = 116; - kF5 = 117; - kData = 118; - } - - enum KeypadInputStatusEnum : ENUM8 { - kSuccess = 0; - kUnsupportedKey = 1; - kInvalidKeyInCurrentState = 2; - } - - bitmap KeypadInputFeature : BITMAP32 { - kNavigationKeyCodes = 0x1; - kLocationKeys = 0x2; - kNumberKeys = 0x4; - } - - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct SendKeyRequest { - CecKeyCode keyCode = 0; - } - - response struct SendKeyResponse = 1 { - KeypadInputStatusEnum status = 0; - } - - command SendKey(SendKeyRequest): SendKeyResponse = 0; -} - -server cluster ContentLauncher = 1290 { - enum ContentLaunchStatusEnum : ENUM8 { - kSuccess = 0; - kUrlNotAvailable = 1; - kAuthFailed = 2; - } - - enum MetricTypeEnum : ENUM8 { - kPixels = 0; - kPercentage = 1; - } - - enum ParameterEnum : ENUM8 { - kActor = 0; - kChannel = 1; - kCharacter = 2; - kDirector = 3; - kEvent = 4; - kFranchise = 5; - kGenre = 6; - kLeague = 7; - kPopularity = 8; - kProvider = 9; - kSport = 10; - kSportsTeam = 11; - kType = 12; - } - - bitmap ContentLauncherFeature : BITMAP32 { - kContentSearch = 0x1; - kURLPlayback = 0x2; - } - - bitmap SupportedStreamingProtocol : BITMAP32 { - kDash = 0x1; - kHls = 0x2; - } - - struct ContentSearch { - Parameter parameterList[] = 0; - } - - struct Parameter { - ParameterEnum type = 0; - char_string value = 1; - optional AdditionalInfo externalIDList[] = 2; - } - - struct AdditionalInfo { - char_string name = 0; - char_string value = 1; - } - - struct BrandingInformation { - char_string providerName = 0; - optional StyleInformation background = 1; - optional StyleInformation logo = 2; - optional StyleInformation progressBar = 3; - optional StyleInformation splash = 4; - optional StyleInformation waterMark = 5; - } - - struct StyleInformation { - optional char_string imageUrl = 0; - optional char_string color = 1; - optional Dimension size = 2; - } - - struct Dimension { - double width = 0; - double height = 1; - MetricTypeEnum metric = 2; - } - - readonly attribute CHAR_STRING acceptHeader[] = 0; - attribute bitmap32 supportedStreamingProtocols = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster AudioOutput = 1291 { - enum OutputTypeEnum : ENUM8 { - kHdmi = 0; - kBt = 1; - kOptical = 2; - kHeadphone = 3; - kInternal = 4; - kOther = 5; - } - - bitmap AudioOutputFeature : BITMAP32 { - kNameUpdates = 0x1; - } - - struct OutputInfo { - int8u index = 0; - OutputTypeEnum outputType = 1; - char_string<32> name = 2; - } - - readonly attribute OutputInfo outputList[] = 0; - readonly attribute int8u currentOutput = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ApplicationLauncher = 1292 { - enum ApplicationLauncherStatusEnum : ENUM8 { - kSuccess = 0; - kAppNotAvailable = 1; - kSystemBusy = 2; - } - - bitmap ApplicationLauncherFeature : BITMAP32 { - kApplicationPlatform = 0x1; - } - - struct Application { - int16u catalogVendorId = 0; - char_string applicationId = 1; - } - - readonly attribute INT16U catalogList[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ApplicationBasic = 1293 { - enum ApplicationStatusEnum : ENUM8 { - kStopped = 0; - kActiveVisibleFocus = 1; - kActiveHidden = 2; - kActiveVisibleNotFocus = 3; - } - - readonly attribute char_string<32> vendorName = 0; - readonly attribute vendor_id vendorID = 1; - readonly attribute char_string<32> applicationName = 2; - readonly attribute int16u productID = 3; - readonly attribute ApplicationStatusEnum status = 5; - readonly attribute char_string<32> applicationVersion = 6; - readonly attribute vendor_id allowedVendorList[] = 7; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster AccountLogin = 1294 { - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ElectricalMeasurement = 2820 { - readonly attribute bitmap32 measurementType = 0; - readonly attribute int32s totalActivePower = 772; - readonly attribute int16u rmsVoltage = 1285; - readonly attribute int16u rmsVoltageMin = 1286; - readonly attribute int16u rmsVoltageMax = 1287; - readonly attribute int16u rmsCurrent = 1288; - readonly attribute int16u rmsCurrentMin = 1289; - readonly attribute int16u rmsCurrentMax = 1290; - readonly attribute int16s activePower = 1291; - readonly attribute int16s activePowerMin = 1292; - readonly attribute int16s activePowerMax = 1293; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster UnitTesting = 4294048773 { - enum SimpleEnum : ENUM8 { - kUnspecified = 0; - kValueA = 1; - kValueB = 2; - kValueC = 3; - } - - bitmap Bitmap16MaskMap : BITMAP16 { - kMaskVal1 = 0x1; - kMaskVal2 = 0x2; - kMaskVal3 = 0x4; - kMaskVal4 = 0x4000; - } - - bitmap Bitmap32MaskMap : BITMAP32 { - kMaskVal1 = 0x1; - kMaskVal2 = 0x2; - kMaskVal3 = 0x4; - kMaskVal4 = 0x40000000; - } - - bitmap Bitmap64MaskMap : BITMAP64 { - kMaskVal1 = 0x1; - kMaskVal2 = 0x2; - kMaskVal3 = 0x4; - kMaskVal4 = 0x4000000000000000; - } - - bitmap Bitmap8MaskMap : BITMAP8 { - kMaskVal1 = 0x1; - kMaskVal2 = 0x2; - kMaskVal3 = 0x4; - kMaskVal4 = 0x40; - } - - bitmap SimpleBitmap : BITMAP8 { - kValueA = 0x1; - kValueB = 0x2; - kValueC = 0x4; - } - - struct TestListStructOctet { - int64u member1 = 0; - octet_string<32> member2 = 1; - } - - struct NullablesAndOptionalsStruct { - nullable int16u nullableInt = 0; - optional int16u optionalInt = 1; - optional nullable int16u nullableOptionalInt = 2; - nullable char_string nullableString = 3; - optional char_string optionalString = 4; - optional nullable char_string nullableOptionalString = 5; - nullable SimpleStruct nullableStruct = 6; - optional SimpleStruct optionalStruct = 7; - optional nullable SimpleStruct nullableOptionalStruct = 8; - nullable SimpleEnum nullableList[] = 9; - optional SimpleEnum optionalList[] = 10; - optional nullable SimpleEnum nullableOptionalList[] = 11; - } - - struct SimpleStruct { - int8u a = 0; - boolean b = 1; - SimpleEnum c = 2; - octet_string d = 3; - char_string e = 4; - SimpleBitmap f = 5; - single g = 6; - double h = 7; - } - - fabric_scoped struct TestFabricScoped { - fabric_sensitive int8u fabricSensitiveInt8u = 1; - optional fabric_sensitive int8u optionalFabricSensitiveInt8u = 2; - nullable fabric_sensitive int8u nullableFabricSensitiveInt8u = 3; - optional nullable fabric_sensitive int8u nullableOptionalFabricSensitiveInt8u = 4; - fabric_sensitive char_string fabricSensitiveCharString = 5; - fabric_sensitive SimpleStruct fabricSensitiveStruct = 6; - fabric_sensitive int8u fabricSensitiveInt8uList[] = 7; - fabric_idx fabricIndex = 254; - } - - struct NestedStruct { - int8u a = 0; - boolean b = 1; - SimpleStruct c = 2; - } - - struct NestedStructList { - int8u a = 0; - boolean b = 1; - SimpleStruct c = 2; - SimpleStruct d[] = 3; - int32u e[] = 4; - octet_string f[] = 5; - int8u g[] = 6; - } - - info event TestEvent = 1 { - INT8U arg1 = 1; - SimpleEnum arg2 = 2; - BOOLEAN arg3 = 3; - SimpleStruct arg4 = 4; - SimpleStruct arg5[] = 5; - SimpleEnum arg6[] = 6; - } - - fabric_sensitive info event TestFabricScopedEvent = 2 { - fabric_idx fabricIndex = 254; - } - - attribute boolean boolean = 0; - attribute Bitmap8MaskMap bitmap8 = 1; - attribute Bitmap16MaskMap bitmap16 = 2; - attribute Bitmap32MaskMap bitmap32 = 3; - attribute Bitmap64MaskMap bitmap64 = 4; - attribute int8u int8u = 5; - attribute int16u int16u = 6; - attribute int24u int24u = 7; - attribute int32u int32u = 8; - attribute int40u int40u = 9; - attribute int48u int48u = 10; - attribute int56u int56u = 11; - attribute int64u int64u = 12; - attribute int8s int8s = 13; - attribute int16s int16s = 14; - attribute int24s int24s = 15; - attribute int32s int32s = 16; - attribute int40s int40s = 17; - attribute int48s int48s = 18; - attribute int56s int56s = 19; - attribute int64s int64s = 20; - attribute enum8 enum8 = 21; - attribute enum16 enum16 = 22; - attribute single floatSingle = 23; - attribute double floatDouble = 24; - attribute octet_string<10> octetString = 25; - attribute INT8U listInt8u[] = 26; - attribute OCTET_STRING listOctetString[] = 27; - attribute TestListStructOctet listStructOctetString[] = 28; - attribute long_octet_string<1000> longOctetString = 29; - attribute char_string<10> charString = 30; - attribute long_char_string<1000> longCharString = 31; - attribute epoch_us epochUs = 32; - attribute epoch_s epochS = 33; - attribute vendor_id vendorId = 34; - attribute NullablesAndOptionalsStruct listNullablesAndOptionalsStruct[] = 35; - attribute SimpleEnum enumAttr = 36; - attribute SimpleStruct structAttr = 37; - attribute int8u rangeRestrictedInt8u = 38; - attribute int8s rangeRestrictedInt8s = 39; - attribute int16u rangeRestrictedInt16u = 40; - attribute int16s rangeRestrictedInt16s = 41; - attribute LONG_OCTET_STRING listLongOctetString[] = 42; - attribute TestFabricScoped listFabricScoped[] = 43; - attribute boolean timedWriteBoolean = 48; - attribute boolean generalErrorBoolean = 49; - attribute boolean clusterErrorBoolean = 50; - attribute nullable boolean nullableBoolean = 16384; - attribute nullable Bitmap8MaskMap nullableBitmap8 = 16385; - attribute nullable Bitmap16MaskMap nullableBitmap16 = 16386; - attribute nullable Bitmap32MaskMap nullableBitmap32 = 16387; - attribute nullable Bitmap64MaskMap nullableBitmap64 = 16388; - attribute nullable int8u nullableInt8u = 16389; - attribute nullable int16u nullableInt16u = 16390; - attribute nullable int24u nullableInt24u = 16391; - attribute nullable int32u nullableInt32u = 16392; - attribute nullable int40u nullableInt40u = 16393; - attribute nullable int48u nullableInt48u = 16394; - attribute nullable int56u nullableInt56u = 16395; - attribute nullable int64u nullableInt64u = 16396; - attribute nullable int8s nullableInt8s = 16397; - attribute nullable int16s nullableInt16s = 16398; - attribute nullable int24s nullableInt24s = 16399; - attribute nullable int32s nullableInt32s = 16400; - attribute nullable int40s nullableInt40s = 16401; - attribute nullable int48s nullableInt48s = 16402; - attribute nullable int56s nullableInt56s = 16403; - attribute nullable int64s nullableInt64s = 16404; - attribute nullable enum8 nullableEnum8 = 16405; - attribute nullable enum16 nullableEnum16 = 16406; - attribute nullable single nullableFloatSingle = 16407; - attribute nullable double nullableFloatDouble = 16408; - attribute nullable octet_string<10> nullableOctetString = 16409; - attribute nullable char_string<10> nullableCharString = 16414; - attribute nullable SimpleEnum nullableEnumAttr = 16420; - attribute nullable SimpleStruct nullableStruct = 16421; - attribute nullable int8u nullableRangeRestrictedInt8u = 16422; - attribute nullable int8s nullableRangeRestrictedInt8s = 16423; - attribute nullable int16u nullableRangeRestrictedInt16u = 16424; - attribute nullable int16s nullableRangeRestrictedInt16s = 16425; - attribute int8u writeOnlyInt8u = 16426; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct TestAddArgumentsRequest { - INT8U arg1 = 0; - INT8U arg2 = 1; - } - - request struct TestStructArgumentRequestRequest { - SimpleStruct arg1 = 0; - } - - request struct TestNestedStructArgumentRequestRequest { - NestedStruct arg1 = 0; - } - - request struct TestListStructArgumentRequestRequest { - SimpleStruct arg1[] = 0; - } - - request struct TestListInt8UArgumentRequestRequest { - INT8U arg1[] = 0; - } - - request struct TestNestedStructListArgumentRequestRequest { - NestedStructList arg1 = 0; - } - - request struct TestListNestedStructListArgumentRequestRequest { - NestedStructList arg1[] = 0; - } - - request struct TestListInt8UReverseRequestRequest { - INT8U arg1[] = 0; - } - - request struct TestEnumsRequestRequest { - vendor_id arg1 = 0; - SimpleEnum arg2 = 1; - } - - request struct TestNullableOptionalRequestRequest { - optional nullable INT8U arg1 = 0; - } - - request struct SimpleStructEchoRequestRequest { - SimpleStruct arg1 = 0; - } - - request struct TestSimpleOptionalArgumentRequestRequest { - optional BOOLEAN arg1 = 0; - } - - request struct TestEmitTestEventRequestRequest { - INT8U arg1 = 0; - SimpleEnum arg2 = 1; - BOOLEAN arg3 = 2; - } - - request struct TestEmitTestFabricScopedEventRequestRequest { - INT8U arg1 = 0; - } - - response struct TestSpecificResponse = 0 { - INT8U returnValue = 0; - } - - response struct TestAddArgumentsResponse = 1 { - INT8U returnValue = 0; - } - - response struct TestListInt8UReverseResponse = 4 { - INT8U arg1[] = 0; - } - - response struct TestEnumsResponse = 5 { - vendor_id arg1 = 0; - SimpleEnum arg2 = 1; - } - - response struct TestNullableOptionalResponse = 6 { - BOOLEAN wasPresent = 0; - optional BOOLEAN wasNull = 1; - optional INT8U value = 2; - optional nullable INT8U originalValue = 3; - } - - response struct SimpleStructResponse = 9 { - SimpleStruct arg1 = 0; - } - - response struct TestEmitTestEventResponse = 10 { - INT64U value = 0; - } - - response struct TestEmitTestFabricScopedEventResponse = 11 { - INT64U value = 0; - } - - command Test(): DefaultSuccess = 0; - command TestNotHandled(): DefaultSuccess = 1; - command TestSpecific(): TestSpecificResponse = 2; - command TestAddArguments(TestAddArgumentsRequest): TestAddArgumentsResponse = 4; - command TestStructArgumentRequest(TestStructArgumentRequestRequest): BooleanResponse = 7; - command TestNestedStructArgumentRequest(TestNestedStructArgumentRequestRequest): BooleanResponse = 8; - command TestListStructArgumentRequest(TestListStructArgumentRequestRequest): BooleanResponse = 9; - command TestListInt8UArgumentRequest(TestListInt8UArgumentRequestRequest): BooleanResponse = 10; - command TestNestedStructListArgumentRequest(TestNestedStructListArgumentRequestRequest): BooleanResponse = 11; - command TestListNestedStructListArgumentRequest(TestListNestedStructListArgumentRequestRequest): BooleanResponse = 12; - command TestListInt8UReverseRequest(TestListInt8UReverseRequestRequest): TestListInt8UReverseResponse = 13; - command TestEnumsRequest(TestEnumsRequestRequest): TestEnumsResponse = 14; - command TestNullableOptionalRequest(TestNullableOptionalRequestRequest): TestNullableOptionalResponse = 15; - command SimpleStructEchoRequest(SimpleStructEchoRequestRequest): SimpleStructResponse = 17; - timed command TimedInvokeRequest(): DefaultSuccess = 18; - command TestSimpleOptionalArgumentRequest(TestSimpleOptionalArgumentRequestRequest): DefaultSuccess = 19; - command TestEmitTestEventRequest(TestEmitTestEventRequestRequest): TestEmitTestEventResponse = 20; - command TestEmitTestFabricScopedEventRequest(TestEmitTestFabricScopedEventRequestRequest): TestEmitTestFabricScopedEventResponse = 21; -} - -server cluster FaultInjection = 4294048774 { - enum FaultType : ENUM8 { - kUnspecified = 0; - kSystemFault = 1; - kInetFault = 2; - kChipFault = 3; - kCertFault = 4; - } - - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct FailAtFaultRequest { - FaultType type = 0; - INT32U id = 1; - INT32U numCallsToSkip = 2; - INT32U numCallsToFail = 3; - BOOLEAN takeMutex = 4; - } - - request struct FailRandomlyAtFaultRequest { - FaultType type = 0; - INT32U id = 1; - INT8U percentage = 2; - } - - command access(invoke: manage) FailAtFault(FailAtFaultRequest): DefaultSuccess = 0; - command access(invoke: manage) FailRandomlyAtFault(FailRandomlyAtFaultRequest): DefaultSuccess = 1; -} - -endpoint 0 { - device type rootdevice = 22, version 1; - binding cluster OtaSoftwareUpdateProvider; - - server cluster Identify { - ram attribute identifyTime; - ram attribute identifyType; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Descriptor { - callback attribute deviceTypeList; - callback attribute serverList; - callback attribute clientList; - callback attribute partsList; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster Binding { - callback attribute binding; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster AccessControl { - callback attribute acl; - callback attribute extension; - callback attribute subjectsPerAccessControlEntry default = 4; - callback attribute targetsPerAccessControlEntry default = 3; - callback attribute accessControlEntriesPerFabric default = 4; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster BasicInformation { - callback attribute dataModelRevision default = 10; - callback attribute vendorName; - callback attribute vendorID; - callback attribute productName; - callback attribute productID; - persist attribute nodeLabel; - callback attribute location default = "XX"; - callback attribute hardwareVersion; - callback attribute hardwareVersionString; - callback attribute softwareVersion; - callback attribute softwareVersionString; - callback attribute manufacturingDate default = "20210614123456ZZ"; - callback attribute partNumber; - callback attribute productURL; - callback attribute productLabel; - callback attribute serialNumber; - persist attribute localConfigDisabled; - ram attribute reachable default = 1; - callback attribute uniqueID; - callback attribute capabilityMinima; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster OtaSoftwareUpdateRequestor { - callback attribute defaultOtaProviders; - ram attribute updatePossible default = 1; - ram attribute updateState; - ram attribute updateStateProgress; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster LocalizationConfiguration { - persist attribute activeLocale default = "en-US"; - callback attribute supportedLocales; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster TimeFormatLocalization { - persist attribute hourFormat; - persist attribute activeCalendarType; - callback attribute supportedCalendarTypes; - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster UnitLocalization { - persist attribute temperatureUnit; - ram attribute featureMap default = 0x1; - ram attribute clusterRevision default = 1; - } - - server cluster PowerSourceConfiguration { - callback attribute sources; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster PowerSource { - ram attribute status; - ram attribute order default = 3; - ram attribute description default = "B1"; - ram attribute batChargeLevel; - ram attribute batReplacementNeeded; - ram attribute batReplaceability; - ram attribute featureMap default = 2; - ram attribute clusterRevision default = 1; - } - - server cluster GeneralCommissioning { - ram attribute breadcrumb; - callback attribute basicCommissioningInfo; - callback attribute regulatoryConfig; - callback attribute locationCapability; - callback attribute supportsConcurrentConnection default = 1; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster NetworkCommissioning { - ram attribute maxNetworks; - callback attribute networks; - ram attribute scanMaxTimeSeconds; - ram attribute connectMaxTimeSeconds; - ram attribute interfaceEnabled; - ram attribute lastNetworkingStatus; - ram attribute lastNetworkID; - ram attribute lastConnectErrorValue; - ram attribute featureMap default = 2; - ram attribute clusterRevision default = 1; - } - - server cluster DiagnosticLogs { - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster GeneralDiagnostics { - callback attribute networkInterfaces; - callback attribute rebootCount; - callback attribute upTime; - callback attribute totalOperationalHours; - callback attribute bootReasons; - callback attribute activeHardwareFaults; - callback attribute activeRadioFaults; - callback attribute activeNetworkFaults; - callback attribute testEventTriggersEnabled; - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster SoftwareDiagnostics { - callback attribute threadMetrics; - callback attribute currentHeapFree; - callback attribute currentHeapUsed; - callback attribute currentHeapHighWatermark; - ram attribute featureMap default = 1; - ram attribute clusterRevision default = 1; - } - - server cluster ThreadNetworkDiagnostics { - callback attribute channel; - callback attribute routingRole; - callback attribute networkName; - callback attribute panId; - callback attribute extendedPanId; - callback attribute meshLocalPrefix; - callback attribute overrunCount; - callback attribute neighborTableList; - callback attribute routeTableList; - callback attribute partitionId; - callback attribute weighting; - callback attribute dataVersion; - callback attribute stableDataVersion; - callback attribute leaderRouterId; - callback attribute detachedRoleCount; - callback attribute childRoleCount; - callback attribute routerRoleCount; - callback attribute leaderRoleCount; - callback attribute attachAttemptCount; - callback attribute partitionIdChangeCount; - callback attribute betterPartitionAttachAttemptCount; - callback attribute parentChangeCount; - callback attribute txTotalCount; - callback attribute txUnicastCount; - callback attribute txBroadcastCount; - callback attribute txAckRequestedCount; - callback attribute txAckedCount; - callback attribute txNoAckRequestedCount; - callback attribute txDataCount; - callback attribute txDataPollCount; - callback attribute txBeaconCount; - callback attribute txBeaconRequestCount; - callback attribute txOtherCount; - callback attribute txRetryCount; - callback attribute txDirectMaxRetryExpiryCount; - callback attribute txIndirectMaxRetryExpiryCount; - callback attribute txErrCcaCount; - callback attribute txErrAbortCount; - callback attribute txErrBusyChannelCount; - callback attribute rxTotalCount; - callback attribute rxUnicastCount; - callback attribute rxBroadcastCount; - callback attribute rxDataCount; - callback attribute rxDataPollCount; - callback attribute rxBeaconCount; - callback attribute rxBeaconRequestCount; - callback attribute rxOtherCount; - callback attribute rxAddressFilteredCount; - callback attribute rxDestAddrFilteredCount; - callback attribute rxDuplicatedCount; - callback attribute rxErrNoFrameCount; - callback attribute rxErrUnknownNeighborCount; - callback attribute rxErrInvalidSrcAddrCount; - callback attribute rxErrSecCount; - callback attribute rxErrFcsCount; - callback attribute rxErrOtherCount; - callback attribute activeTimestamp; - callback attribute pendingTimestamp; - callback attribute delay; - callback attribute securityPolicy; - callback attribute channelPage0Mask; - callback attribute operationalDatasetComponents; - callback attribute activeNetworkFaultsList; - ram attribute featureMap default = 0x000F; - ram attribute clusterRevision default = 1; - } - - server cluster WiFiNetworkDiagnostics { - callback attribute bssid; - callback attribute securityType; - callback attribute wiFiVersion; - callback attribute channelNumber; - callback attribute rssi; - callback attribute beaconLostCount; - callback attribute beaconRxCount; - callback attribute packetMulticastRxCount; - callback attribute packetMulticastTxCount; - callback attribute packetUnicastRxCount; - callback attribute packetUnicastTxCount; - callback attribute currentMaxRate; - callback attribute overrunCount; - ram attribute featureMap default = 3; - ram attribute clusterRevision default = 1; - } - - server cluster EthernetNetworkDiagnostics { - callback attribute PHYRate; - callback attribute fullDuplex; - callback attribute packetRxCount; - callback attribute packetTxCount; - callback attribute txErrCount; - callback attribute collisionCount; - callback attribute overrunCount; - callback attribute carrierDetect; - callback attribute timeSinceReset; - ram attribute featureMap default = 3; - ram attribute clusterRevision default = 1; - } - - server cluster AdministratorCommissioning { - callback attribute windowStatus; - callback attribute adminFabricIndex default = 1; - callback attribute adminVendorId; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster OperationalCredentials { - callback attribute NOCs; - callback attribute fabrics; - callback attribute supportedFabrics; - callback attribute commissionedFabrics; - callback attribute trustedRootCertificates; - callback attribute currentFabricIndex; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster GroupKeyManagement { - callback attribute groupKeyMap; - callback attribute groupTable; - callback attribute maxGroupsPerFabric; - callback attribute maxGroupKeysPerFabric; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster FixedLabel { - callback attribute labelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster UserLabel { - callback attribute labelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster RelativeHumidityMeasurement { - ram attribute measuredValue; - ram attribute minMeasuredValue; - ram attribute maxMeasuredValue default = 0x2710; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster FaultInjection { - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } -} -endpoint 1 { - device type onofflight = 256, version 1; - - server cluster Identify { - ram attribute identifyTime; - ram attribute identifyType; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Scenes { - ram attribute sceneCount; - ram attribute currentScene; - ram attribute currentGroup; - ram attribute sceneValid; - ram attribute nameSupport; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster OnOff { - persist attribute onOff; - ram attribute globalSceneControl default = 0x01; - ram attribute onTime; - ram attribute offWaitTime; - persist attribute startUpOnOff default = 0xFF; - ram attribute featureMap default = 0x0001; - ram attribute clusterRevision default = 4; - } - - server cluster OnOffSwitchConfiguration { - ram attribute switchType; - ram attribute switchActions; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster LevelControl { - persist attribute currentLevel default = 0xFE; - ram attribute remainingTime; - ram attribute minLevel default = 0x01; - ram attribute maxLevel default = 0xFE; - ram attribute currentFrequency; - ram attribute minFrequency; - ram attribute maxFrequency; - ram attribute options; - ram attribute onOffTransitionTime; - ram attribute onLevel default = 0xFF; - ram attribute onTransitionTime; - ram attribute offTransitionTime; - ram attribute defaultMoveRate default = 50; - persist attribute startUpCurrentLevel default = 255; - ram attribute featureMap default = 3; - ram attribute clusterRevision default = 5; - } - - server cluster BinaryInputBasic { - ram attribute outOfService; - ram attribute presentValue; - ram attribute statusFlags; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster Descriptor { - callback attribute deviceTypeList; - callback attribute serverList; - callback attribute clientList; - callback attribute partsList; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster Binding { - callback attribute binding; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster Actions { - callback attribute actionList; - callback attribute endpointLists; - callback attribute setupURL; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster PowerSource { - ram attribute status; - ram attribute order default = 2; - ram attribute description default = "B2"; - ram attribute batChargeLevel; - ram attribute batReplacementNeeded; - ram attribute batReplaceability; - ram attribute featureMap default = 2; - ram attribute clusterRevision default = 1; - } - - server cluster Switch { - ram attribute numberOfPositions default = 2; - ram attribute currentPosition; - ram attribute multiPressMax default = 2; - ram attribute featureMap default = 1; - ram attribute clusterRevision default = 1; - } - - server cluster FixedLabel { - callback attribute labelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster UserLabel { - callback attribute labelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster BooleanState { - ram attribute stateValue; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster ModeSelect { - ram attribute description default = "Coffee"; - ram attribute standardNamespace; - callback attribute supportedModes; - persist attribute currentMode; - persist attribute startUpMode; - persist attribute onMode default = 255; - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 1; - ram attribute clusterRevision default = 1; - ram attribute manufacturerExtension default = 255; - } - - server cluster DoorLock { - ram attribute lockState default = 2; - ram attribute lockType; - ram attribute actuatorEnabled; - ram attribute doorState; - ram attribute doorOpenEvents; - ram attribute doorClosedEvents; - ram attribute openPeriod; - ram attribute numberOfTotalUsersSupported default = 10; - ram attribute numberOfPINUsersSupported default = 10; - ram attribute numberOfRFIDUsersSupported default = 10; - ram attribute numberOfWeekDaySchedulesSupportedPerUser default = 10; - ram attribute numberOfYearDaySchedulesSupportedPerUser default = 10; - ram attribute numberOfHolidaySchedulesSupported; - ram attribute maxPINCodeLength default = 6; - ram attribute minPINCodeLength default = 6; - ram attribute maxRFIDCodeLength default = 20; - ram attribute minRFIDCodeLength default = 10; - ram attribute credentialRulesSupport default = 1; - ram attribute numberOfCredentialsSupportedPerUser default = 5; - ram attribute language default = "en"; - ram attribute autoRelockTime default = 60; - ram attribute soundVolume; - ram attribute operatingMode; - ram attribute supportedOperatingModes default = 0xFFF6; - ram attribute defaultConfigurationRegister; - ram attribute enableOneTouchLocking; - ram attribute enableInsideStatusLED; - ram attribute enablePrivacyModeButton; - ram attribute wrongCodeEntryLimit default = 3; - ram attribute userCodeTemporaryDisableTime default = 10; - ram attribute requirePINforRemoteOperation; - ram attribute featureMap default = 0xD13; - ram attribute clusterRevision default = 6; - } - - server cluster WindowCovering { - ram attribute type default = 0x08; - ram attribute physicalClosedLimitLift default = 0xFFFF; - ram attribute physicalClosedLimitTilt default = 0xFFFF; - persist attribute currentPositionLift default = 0x7FFF; - persist attribute currentPositionTilt default = 0x7FFF; - persist attribute numberOfActuationsLift; - persist attribute numberOfActuationsTilt; - persist attribute configStatus default = 0x03; - persist attribute currentPositionLiftPercentage default = 50; - persist attribute currentPositionTiltPercentage default = 50; - ram attribute operationalStatus; - ram attribute targetPositionLiftPercent100ths default = 5000; - ram attribute targetPositionTiltPercent100ths default = 5000; - ram attribute endProductType; - persist attribute currentPositionLiftPercent100ths default = 5000; - persist attribute currentPositionTiltPercent100ths default = 5000; - persist attribute installedOpenLimitLift; - persist attribute installedClosedLimitLift default = 0xFFFF; - persist attribute installedOpenLimitTilt; - persist attribute installedClosedLimitTilt default = 0xFFFF; - persist attribute mode; - ram attribute safetyStatus; - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 0x17; - ram attribute clusterRevision default = 5; - } - - server cluster BarrierControl { - ram attribute barrierMovingState; - ram attribute barrierSafetyStatus; - ram attribute barrierCapabilities; - ram attribute barrierPosition; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster PumpConfigurationAndControl { - ram attribute maxPressure; - ram attribute maxSpeed; - ram attribute maxFlow; - ram attribute minConstPressure; - ram attribute maxConstPressure; - ram attribute minCompPressure; - ram attribute maxCompPressure; - ram attribute minConstSpeed; - ram attribute maxConstSpeed; - ram attribute minConstFlow; - ram attribute maxConstFlow; - ram attribute minConstTemp; - ram attribute maxConstTemp; - ram attribute pumpStatus; - ram attribute effectiveOperationMode; - ram attribute effectiveControlMode; - ram attribute capacity; - ram attribute speed; - ram attribute lifetimeRunningHours; - ram attribute power; - ram attribute lifetimeEnergyConsumed; - ram attribute operationMode; - ram attribute controlMode; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster Thermostat { - ram attribute localTemperature; - ram attribute absMinHeatSetpointLimit default = 0x02BC; - ram attribute absMaxHeatSetpointLimit default = 0x0BB8; - ram attribute absMinCoolSetpointLimit default = 0x0640; - ram attribute absMaxCoolSetpointLimit default = 0x0C80; - ram attribute occupiedCoolingSetpoint default = 0x0A28; - ram attribute occupiedHeatingSetpoint default = 0x07D0; - ram attribute minHeatSetpointLimit default = 0x02BC; - ram attribute maxHeatSetpointLimit default = 0x0BB8; - ram attribute minCoolSetpointLimit default = 0x0640; - ram attribute maxCoolSetpointLimit default = 0x0C80; - ram attribute minSetpointDeadBand default = 0x19; - ram attribute controlSequenceOfOperation default = 0x04; - ram attribute systemMode default = 0x01; - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 0x0023; - ram attribute clusterRevision default = 5; - } - - server cluster FanControl { - ram attribute fanMode; - ram attribute fanModeSequence default = 0x02; - ram attribute percentSetting; - ram attribute percentCurrent; - ram attribute speedMax default = 100; - ram attribute speedSetting; - ram attribute speedCurrent; - ram attribute rockSupport; - ram attribute rockSetting; - ram attribute windSupport; - ram attribute windSetting; - ram attribute featureMap default = 0x0F; - ram attribute clusterRevision default = 2; - } - - server cluster ThermostatUserInterfaceConfiguration { - ram attribute temperatureDisplayMode; - ram attribute keypadLockout; - ram attribute scheduleProgrammingVisibility; - ram attribute featureMap; - ram attribute clusterRevision default = 2; - } - - server cluster ColorControl { - ram attribute currentHue; - ram attribute currentSaturation; - ram attribute remainingTime; - ram attribute currentX default = 0x616B; - ram attribute currentY default = 0x607D; - ram attribute driftCompensation; - ram attribute compensationText; - ram attribute colorTemperatureMireds default = 0x00FA; - ram attribute colorMode default = 0x01; - ram attribute options; - ram attribute numberOfPrimaries; - ram attribute primary1X; - ram attribute primary1Y; - ram attribute primary1Intensity; - ram attribute primary2X; - ram attribute primary2Y; - ram attribute primary2Intensity; - ram attribute primary3X; - ram attribute primary3Y; - ram attribute primary3Intensity; - ram attribute primary4X; - ram attribute primary4Y; - ram attribute primary4Intensity; - ram attribute primary5X; - ram attribute primary5Y; - ram attribute primary5Intensity; - ram attribute primary6X; - ram attribute primary6Y; - ram attribute primary6Intensity; - ram attribute whitePointX; - ram attribute whitePointY; - ram attribute colorPointRX; - ram attribute colorPointRY; - ram attribute colorPointRIntensity; - ram attribute colorPointGX; - ram attribute colorPointGY; - ram attribute colorPointGIntensity; - ram attribute colorPointBX; - ram attribute colorPointBY; - ram attribute colorPointBIntensity; - ram attribute enhancedCurrentHue; - ram attribute enhancedColorMode default = 0x01; - ram attribute colorLoopActive; - ram attribute colorLoopDirection; - ram attribute colorLoopTime default = 0x0019; - ram attribute colorLoopStartEnhancedHue default = 0x2300; - ram attribute colorLoopStoredEnhancedHue; - ram attribute colorCapabilities default = 0x1F; - ram attribute colorTempPhysicalMinMireds; - ram attribute colorTempPhysicalMaxMireds default = 0xFEFF; - ram attribute coupleColorTempToLevelMinMireds; - ram attribute startUpColorTemperatureMireds; - ram attribute featureMap default = 0x1F; - ram attribute clusterRevision default = 5; - } - - server cluster IlluminanceMeasurement { - ram attribute measuredValue; - ram attribute minMeasuredValue default = 0x01; - ram attribute maxMeasuredValue default = 0xFFFE; - ram attribute tolerance; - ram attribute lightSensorType default = 0xFF; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster TemperatureMeasurement { - ram attribute measuredValue default = 0x8000; - ram attribute minMeasuredValue default = 0x8000; - ram attribute maxMeasuredValue default = 0x8000; - ram attribute tolerance; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster PressureMeasurement { - ram attribute measuredValue; - ram attribute minMeasuredValue; - ram attribute maxMeasuredValue; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster FlowMeasurement { - ram attribute measuredValue; - ram attribute minMeasuredValue; - ram attribute maxMeasuredValue; - ram attribute tolerance; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster RelativeHumidityMeasurement { - ram attribute measuredValue; - ram attribute minMeasuredValue; - ram attribute maxMeasuredValue default = 0x2710; - ram attribute tolerance; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster OccupancySensing { - ram attribute occupancy; - ram attribute occupancySensorType; - ram attribute occupancySensorTypeBitmap; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster WakeOnLan { - ram attribute MACAddress; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster Channel { - callback attribute channelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster TargetNavigator { - callback attribute targetList; - ram attribute currentTarget; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster MediaPlayback { - ram attribute currentState; - ram attribute startTime default = 0xFF; - ram attribute duration; - ram attribute playbackSpeed; - ram attribute seekRangeEnd; - ram attribute seekRangeStart; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster MediaInput { - callback attribute inputList; - ram attribute currentInput; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster LowPower { - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster KeypadInput { - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster ContentLauncher { - callback attribute acceptHeader; - ram attribute supportedStreamingProtocols; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster AudioOutput { - callback attribute outputList; - ram attribute currentOutput; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster ApplicationLauncher { - callback attribute catalogList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster ApplicationBasic { - ram attribute vendorName; - ram attribute vendorID; - ram attribute applicationName; - ram attribute productID; - ram attribute status; - ram attribute applicationVersion; - callback attribute allowedVendorList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster AccountLogin { - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster ElectricalMeasurement { - ram attribute measurementType; - ram attribute totalActivePower; - ram attribute rmsVoltage default = 0xffff; - ram attribute rmsVoltageMin default = 0x8000; - ram attribute rmsVoltageMax default = 0x8000; - ram attribute rmsCurrent default = 0xffff; - ram attribute rmsCurrentMin default = 0xffff; - ram attribute rmsCurrentMax default = 0xffff; - ram attribute activePower default = 0xffff; - ram attribute activePowerMin default = 0xffff; - ram attribute activePowerMax default = 0xffff; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } - - server cluster UnitTesting { - ram attribute boolean; - ram attribute bitmap8; - ram attribute bitmap16; - ram attribute bitmap32; - ram attribute bitmap64; - ram attribute int8u; - ram attribute int16u; - ram attribute int24u; - ram attribute int32u; - ram attribute int40u; - ram attribute int48u; - ram attribute int56u; - ram attribute int64u; - ram attribute int8s; - ram attribute int16s; - ram attribute int24s; - ram attribute int32s; - ram attribute int40s; - ram attribute int48s; - ram attribute int56s; - ram attribute int64s; - ram attribute enum8; - ram attribute enum16; - ram attribute floatSingle; - ram attribute floatDouble; - ram attribute octetString; - callback attribute listInt8u; - callback attribute listOctetString; - callback attribute listStructOctetString; - ram attribute longOctetString; - ram attribute charString; - ram attribute longCharString; - ram attribute epochUs; - ram attribute epochS; - ram attribute vendorId; - callback attribute listNullablesAndOptionalsStruct; - ram attribute enumAttr; - callback attribute structAttr; - ram attribute rangeRestrictedInt8u default = 70; - ram attribute rangeRestrictedInt8s default = -20; - ram attribute rangeRestrictedInt16u default = 200; - ram attribute rangeRestrictedInt16s default = -100; - callback attribute listLongOctetString; - callback attribute listFabricScoped; - ram attribute timedWriteBoolean; - callback attribute generalErrorBoolean; - callback attribute clusterErrorBoolean; - ram attribute nullableBoolean; - ram attribute nullableBitmap8; - ram attribute nullableBitmap16; - ram attribute nullableBitmap32; - ram attribute nullableBitmap64; - ram attribute nullableInt8u; - ram attribute nullableInt16u; - ram attribute nullableInt24u; - ram attribute nullableInt32u; - ram attribute nullableInt40u; - ram attribute nullableInt48u; - ram attribute nullableInt56u; - ram attribute nullableInt64u; - ram attribute nullableInt8s; - ram attribute nullableInt16s; - ram attribute nullableInt24s; - ram attribute nullableInt32s; - ram attribute nullableInt40s; - ram attribute nullableInt48s; - ram attribute nullableInt56s; - ram attribute nullableInt64s; - ram attribute nullableEnum8; - ram attribute nullableEnum16; - ram attribute nullableFloatSingle; - ram attribute nullableFloatDouble; - ram attribute nullableOctetString; - ram attribute nullableCharString; - ram attribute nullableEnumAttr; - callback attribute nullableStruct; - ram attribute nullableRangeRestrictedInt8u default = 70; - ram attribute nullableRangeRestrictedInt8s default = -20; - ram attribute nullableRangeRestrictedInt16u default = 200; - ram attribute nullableRangeRestrictedInt16s default = -100; - callback attribute writeOnlyInt8u; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } -} -endpoint 2 { - device type onofflight = 256, version 1; - - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster OnOff { - ram attribute onOff; - ram attribute globalSceneControl default = 1; - ram attribute onTime; - ram attribute offWaitTime; - ram attribute startUpOnOff; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Descriptor { - callback attribute deviceTypeList; - callback attribute serverList; - callback attribute clientList; - callback attribute partsList; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster PowerSource { - ram attribute status; - ram attribute order default = 1; - ram attribute description default = "B3"; - ram attribute batChargeLevel; - ram attribute batReplacementNeeded; - ram attribute batReplaceability; - ram attribute featureMap default = 2; - ram attribute clusterRevision default = 1; - } - - server cluster OccupancySensing { - ram attribute occupancy; - ram attribute occupancySensorType; - ram attribute occupancySensorTypeBitmap; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } -} -endpoint 65534 { - device type anonymousEndpointType = 61442, version 1; - - server cluster Descriptor { - callback attribute deviceTypeList; - callback attribute serverList; - callback attribute clientList; - callback attribute partsList; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster NetworkCommissioning { - callback attribute maxNetworks; - callback attribute networks; - callback attribute scanMaxTimeSeconds; - callback attribute connectMaxTimeSeconds; - callback attribute interfaceEnabled; - callback attribute lastNetworkingStatus; - callback attribute lastNetworkID; - callback attribute lastConnectErrorValue; - callback attribute featureMap; - callback attribute clusterRevision default = 1; - } -} diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter deleted file mode 100644 index 6020196c85103e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter +++ /dev/null @@ -1,2065 +0,0 @@ -// This IDL was generated automatically by ZAP. -// It is for view/code review purposes only. - -struct LabelStruct { - char_string<16> label = 0; - char_string<16> value = 1; -} - -server cluster Identify = 3 { - enum IdentifyEffectIdentifier : ENUM8 { - kBlink = 0; - kBreathe = 1; - kOkay = 2; - kChannelChange = 11; - kFinishEffect = 254; - kStopEffect = 255; - } - - enum IdentifyEffectVariant : ENUM8 { - kDefault = 0; - } - - enum IdentifyIdentifyType : ENUM8 { - kNone = 0; - kVisibleLight = 1; - kVisibleLED = 2; - kAudibleBeep = 3; - kDisplay = 4; - kActuator = 5; - } - - attribute int16u identifyTime = 0; - readonly attribute enum8 identifyType = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct IdentifyRequest { - INT16U identifyTime = 0; - } - - request struct TriggerEffectRequest { - IdentifyEffectIdentifier effectIdentifier = 0; - IdentifyEffectVariant effectVariant = 1; - } - - command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; - command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; -} - -server cluster Groups = 4 { - bitmap GroupClusterFeature : BITMAP32 { - kGroupNames = 0x1; - } - - readonly attribute bitmap8 nameSupport = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AddGroupRequest { - group_id groupId = 0; - CHAR_STRING groupName = 1; - } - - request struct ViewGroupRequest { - group_id groupId = 0; - } - - request struct GetGroupMembershipRequest { - group_id groupList[] = 0; - } - - request struct RemoveGroupRequest { - group_id groupId = 0; - } - - request struct AddGroupIfIdentifyingRequest { - group_id groupId = 0; - CHAR_STRING groupName = 1; - } - - response struct AddGroupResponse = 0 { - ENUM8 status = 0; - group_id groupId = 1; - } - - response struct ViewGroupResponse = 1 { - ENUM8 status = 0; - group_id groupId = 1; - CHAR_STRING groupName = 2; - } - - response struct GetGroupMembershipResponse = 2 { - nullable INT8U capacity = 0; - group_id groupList[] = 1; - } - - response struct RemoveGroupResponse = 3 { - ENUM8 status = 0; - group_id groupId = 1; - } - - fabric command access(invoke: manage) AddGroup(AddGroupRequest): AddGroupResponse = 0; - fabric command ViewGroup(ViewGroupRequest): ViewGroupResponse = 1; - fabric command GetGroupMembership(GetGroupMembershipRequest): GetGroupMembershipResponse = 2; - fabric command access(invoke: manage) RemoveGroup(RemoveGroupRequest): RemoveGroupResponse = 3; - fabric command access(invoke: manage) RemoveAllGroups(): DefaultSuccess = 4; - fabric command access(invoke: manage) AddGroupIfIdentifying(AddGroupIfIdentifyingRequest): DefaultSuccess = 5; -} - -server cluster OnOff = 6 { - enum OnOffDelayedAllOffEffectVariant : ENUM8 { - kFadeToOffIn0p8Seconds = 0; - kNoFade = 1; - k50PercentDimDownIn0p8SecondsThenFadeToOffIn12Seconds = 2; - } - - enum OnOffDyingLightEffectVariant : ENUM8 { - k20PercenterDimUpIn0p5SecondsThenFadeToOffIn1Second = 0; - } - - enum OnOffEffectIdentifier : ENUM8 { - kDelayedAllOff = 0; - kDyingLight = 1; - } - - enum OnOffStartUpOnOff : ENUM8 { - kOff = 0; - kOn = 1; - kTogglePreviousOnOff = 2; - } - - bitmap OnOffControl : BITMAP8 { - kAcceptOnlyWhenOn = 0x1; - } - - bitmap OnOffFeature : BITMAP32 { - kLighting = 0x1; - } - - bitmap ScenesFeature : BITMAP32 { - kSceneNames = 0x1; - } - - readonly attribute boolean onOff = 0; - readonly attribute boolean globalSceneControl = 16384; - attribute int16u onTime = 16385; - attribute int16u offWaitTime = 16386; - attribute access(write: manage) nullable OnOffStartUpOnOff startUpOnOff = 16387; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct OffWithEffectRequest { - OnOffEffectIdentifier effectId = 0; - OnOffDelayedAllOffEffectVariant effectVariant = 1; - } - - request struct OnWithTimedOffRequest { - OnOffControl onOffControl = 0; - int16u onTime = 1; - int16u offWaitTime = 2; - } - - command Off(): DefaultSuccess = 0; - command On(): DefaultSuccess = 1; - command Toggle(): DefaultSuccess = 2; - command OffWithEffect(OffWithEffectRequest): DefaultSuccess = 64; - command OnWithRecallGlobalScene(): DefaultSuccess = 65; - command OnWithTimedOff(OnWithTimedOffRequest): DefaultSuccess = 66; -} - -server cluster LevelControl = 8 { - enum MoveMode : ENUM8 { - kUp = 0; - kDown = 1; - } - - enum StepMode : ENUM8 { - kUp = 0; - kDown = 1; - } - - bitmap LevelControlFeature : BITMAP32 { - kOnOff = 0x1; - kLighting = 0x2; - kFrequency = 0x4; - } - - readonly attribute nullable int8u currentLevel = 0; - readonly attribute int16u remainingTime = 1; - readonly attribute int8u minLevel = 2; - readonly attribute int8u maxLevel = 3; - readonly attribute int16u currentFrequency = 4; - readonly attribute int16u minFrequency = 5; - readonly attribute int16u maxFrequency = 6; - attribute bitmap8 options = 15; - attribute int16u onOffTransitionTime = 16; - attribute nullable int8u onLevel = 17; - attribute nullable int16u onTransitionTime = 18; - attribute nullable int16u offTransitionTime = 19; - attribute nullable int8u defaultMoveRate = 20; - attribute access(write: manage) nullable int8u startUpCurrentLevel = 16384; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct MoveToLevelRequest { - INT8U level = 0; - nullable INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct MoveRequest { - MoveMode moveMode = 0; - nullable INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepRequest { - StepMode stepMode = 0; - INT8U stepSize = 1; - nullable INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct StopRequest { - BITMAP8 optionsMask = 0; - BITMAP8 optionsOverride = 1; - } - - request struct MoveToLevelWithOnOffRequest { - INT8U level = 0; - nullable INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct MoveWithOnOffRequest { - MoveMode moveMode = 0; - nullable INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepWithOnOffRequest { - StepMode stepMode = 0; - INT8U stepSize = 1; - nullable INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct StopWithOnOffRequest { - BITMAP8 optionsMask = 0; - BITMAP8 optionsOverride = 1; - } - - command MoveToLevel(MoveToLevelRequest): DefaultSuccess = 0; - command Move(MoveRequest): DefaultSuccess = 1; - command Step(StepRequest): DefaultSuccess = 2; - command Stop(StopRequest): DefaultSuccess = 3; - command MoveToLevelWithOnOff(MoveToLevelWithOnOffRequest): DefaultSuccess = 4; - command MoveWithOnOff(MoveWithOnOffRequest): DefaultSuccess = 5; - command StepWithOnOff(StepWithOnOffRequest): DefaultSuccess = 6; - command StopWithOnOff(StopWithOnOffRequest): DefaultSuccess = 7; -} - -server cluster Descriptor = 29 { - struct DeviceTypeStruct { - devtype_id type = 0; - int16u revision = 1; - } - - readonly attribute DeviceTypeStruct deviceTypeList[] = 0; - readonly attribute CLUSTER_ID serverList[] = 1; - readonly attribute CLUSTER_ID clientList[] = 2; - readonly attribute ENDPOINT_NO partsList[] = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster AccessControl = 31 { - enum AuthMode : ENUM8 { - kPase = 1; - kCase = 2; - kGroup = 3; - } - - enum ChangeTypeEnum : ENUM8 { - kChanged = 0; - kAdded = 1; - kRemoved = 2; - } - - enum Privilege : ENUM8 { - kView = 1; - kProxyView = 2; - kOperate = 3; - kManage = 4; - kAdminister = 5; - } - - fabric_scoped struct AccessControlEntry { - fabric_sensitive Privilege privilege = 1; - fabric_sensitive AuthMode authMode = 2; - nullable fabric_sensitive int64u subjects[] = 3; - nullable fabric_sensitive Target targets[] = 4; - fabric_idx fabricIndex = 254; - } - - struct Target { - nullable cluster_id cluster = 0; - nullable endpoint_no endpoint = 1; - nullable devtype_id deviceType = 2; - } - - fabric_scoped struct ExtensionEntry { - fabric_sensitive octet_string<128> data = 1; - fabric_idx fabricIndex = 254; - } - - fabric_sensitive info event access(read: administer) AccessControlEntryChanged = 0 { - nullable node_id adminNodeID = 1; - nullable INT16U adminPasscodeID = 2; - ChangeTypeEnum changeType = 3; - nullable AccessControlEntry latestValue = 4; - fabric_idx fabricIndex = 254; - } - - fabric_sensitive info event access(read: administer) AccessControlExtensionChanged = 1 { - nullable node_id adminNodeID = 1; - nullable INT16U adminPasscodeID = 2; - ChangeTypeEnum changeType = 3; - nullable ExtensionEntry latestValue = 4; - fabric_idx fabricIndex = 254; - } - - attribute access(read: administer, write: administer) AccessControlEntry acl[] = 0; - attribute access(read: administer, write: administer) ExtensionEntry extension[] = 1; - readonly attribute int16u subjectsPerAccessControlEntry = 2; - readonly attribute int16u targetsPerAccessControlEntry = 3; - readonly attribute int16u accessControlEntriesPerFabric = 4; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster BasicInformation = 40 { - struct CapabilityMinimaStruct { - int16u caseSessionsPerFabric = 0; - int16u subscriptionsPerFabric = 1; - } - - critical event StartUp = 0 { - INT32U softwareVersion = 0; - } - - critical event ShutDown = 1 { - } - - info event Leave = 2 { - fabric_idx fabricIndex = 0; - } - - info event ReachableChanged = 3 { - boolean reachableNewValue = 0; - } - - readonly attribute int16u dataModelRevision = 0; - readonly attribute char_string<32> vendorName = 1; - readonly attribute vendor_id vendorID = 2; - readonly attribute char_string<32> productName = 3; - readonly attribute int16u productID = 4; - attribute access(write: manage) char_string<32> nodeLabel = 5; - attribute access(write: administer) char_string<2> location = 6; - readonly attribute int16u hardwareVersion = 7; - readonly attribute char_string<64> hardwareVersionString = 8; - readonly attribute int32u softwareVersion = 9; - readonly attribute char_string<64> softwareVersionString = 10; - readonly attribute char_string<16> manufacturingDate = 11; - readonly attribute char_string<32> partNumber = 12; - readonly attribute long_char_string<256> productURL = 13; - readonly attribute char_string<64> productLabel = 14; - readonly attribute char_string<32> serialNumber = 15; - attribute access(write: manage) boolean localConfigDisabled = 16; - readonly attribute boolean reachable = 17; - readonly attribute char_string<32> uniqueID = 18; - readonly attribute CapabilityMinimaStruct capabilityMinima = 19; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -client cluster OtaSoftwareUpdateProvider = 41 { - enum OTAApplyUpdateAction : ENUM8 { - kProceed = 0; - kAwaitNextAction = 1; - kDiscontinue = 2; - } - - enum OTADownloadProtocol : ENUM8 { - kBDXSynchronous = 0; - kBDXAsynchronous = 1; - kHttps = 2; - kVendorSpecific = 3; - } - - enum OTAQueryStatus : ENUM8 { - kUpdateAvailable = 0; - kBusy = 1; - kNotAvailable = 2; - kDownloadProtocolNotSupported = 3; - } - - readonly attribute int16u clusterRevision = 65533; - - request struct QueryImageRequest { - vendor_id vendorId = 0; - INT16U productId = 1; - INT32U softwareVersion = 2; - OTADownloadProtocol protocolsSupported[] = 3; - optional INT16U hardwareVersion = 4; - optional CHAR_STRING<2> location = 5; - optional BOOLEAN requestorCanConsent = 6; - optional OCTET_STRING<512> metadataForProvider = 7; - } - - request struct ApplyUpdateRequestRequest { - OCTET_STRING<32> updateToken = 0; - INT32U newVersion = 1; - } - - request struct NotifyUpdateAppliedRequest { - OCTET_STRING<32> updateToken = 0; - INT32U softwareVersion = 1; - } - - response struct QueryImageResponse = 1 { - OTAQueryStatus status = 0; - optional INT32U delayedActionTime = 1; - optional CHAR_STRING<256> imageURI = 2; - optional INT32U softwareVersion = 3; - optional CHAR_STRING<64> softwareVersionString = 4; - optional OCTET_STRING<32> updateToken = 5; - optional BOOLEAN userConsentNeeded = 6; - optional OCTET_STRING<512> metadataForRequestor = 7; - } - - response struct ApplyUpdateResponse = 3 { - OTAApplyUpdateAction action = 0; - INT32U delayedActionTime = 1; - } - - command QueryImage(QueryImageRequest): QueryImageResponse = 0; - command ApplyUpdateRequest(ApplyUpdateRequestRequest): ApplyUpdateResponse = 2; - command NotifyUpdateApplied(NotifyUpdateAppliedRequest): DefaultSuccess = 4; -} - -server cluster OtaSoftwareUpdateRequestor = 42 { - enum OTAAnnouncementReason : ENUM8 { - kSimpleAnnouncement = 0; - kUpdateAvailable = 1; - kUrgentUpdateAvailable = 2; - } - - enum OTAChangeReasonEnum : ENUM8 { - kUnknown = 0; - kSuccess = 1; - kFailure = 2; - kTimeOut = 3; - kDelayByProvider = 4; - } - - enum OTAUpdateStateEnum : ENUM8 { - kUnknown = 0; - kIdle = 1; - kQuerying = 2; - kDelayedOnQuery = 3; - kDownloading = 4; - kApplying = 5; - kDelayedOnApply = 6; - kRollingBack = 7; - kDelayedOnUserConsent = 8; - } - - fabric_scoped struct ProviderLocation { - node_id providerNodeID = 1; - endpoint_no endpoint = 2; - fabric_idx fabricIndex = 254; - } - - info event StateTransition = 0 { - OTAUpdateStateEnum previousState = 0; - OTAUpdateStateEnum newState = 1; - OTAChangeReasonEnum reason = 2; - nullable INT32U targetSoftwareVersion = 3; - } - - critical event VersionApplied = 1 { - INT32U softwareVersion = 0; - INT16U productID = 1; - } - - info event DownloadError = 2 { - INT32U softwareVersion = 0; - INT64U bytesDownloaded = 1; - nullable INT8U progressPercent = 2; - nullable INT64S platformCode = 3; - } - - attribute ProviderLocation defaultOtaProviders[] = 0; - readonly attribute boolean updatePossible = 1; - readonly attribute OTAUpdateStateEnum updateState = 2; - readonly attribute nullable int8u updateStateProgress = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AnnounceOtaProviderRequest { - node_id providerNodeId = 0; - vendor_id vendorId = 1; - OTAAnnouncementReason announcementReason = 2; - optional OCTET_STRING<512> metadataForNode = 3; - endpoint_no endpoint = 4; - } - - command AnnounceOtaProvider(AnnounceOtaProviderRequest): DefaultSuccess = 0; -} - -server cluster LocalizationConfiguration = 43 { - attribute char_string<35> activeLocale = 0; - readonly attribute CHAR_STRING supportedLocales[] = 1; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster TimeFormatLocalization = 44 { - enum CalendarType : ENUM8 { - kBuddhist = 0; - kChinese = 1; - kCoptic = 2; - kEthiopian = 3; - kGregorian = 4; - kHebrew = 5; - kIndian = 6; - kIslamic = 7; - kJapanese = 8; - kKorean = 9; - kPersian = 10; - kTaiwanese = 11; - } - - enum HourFormat : ENUM8 { - k12hr = 0; - k24hr = 1; - } - - attribute HourFormat hourFormat = 0; - attribute CalendarType activeCalendarType = 1; - readonly attribute CalendarType supportedCalendarTypes[] = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster GeneralCommissioning = 48 { - enum CommissioningError : ENUM8 { - kOk = 0; - kValueOutsideRange = 1; - kInvalidAuthentication = 2; - kNoFailSafe = 3; - kBusyWithOtherAdmin = 4; - } - - enum RegulatoryLocationType : ENUM8 { - kIndoor = 0; - kOutdoor = 1; - kIndoorOutdoor = 2; - } - - struct BasicCommissioningInfo { - int16u failSafeExpiryLengthSeconds = 0; - int16u maxCumulativeFailsafeSeconds = 1; - } - - attribute access(write: administer) int64u breadcrumb = 0; - readonly attribute BasicCommissioningInfo basicCommissioningInfo = 1; - readonly attribute RegulatoryLocationType regulatoryConfig = 2; - readonly attribute RegulatoryLocationType locationCapability = 3; - readonly attribute boolean supportsConcurrentConnection = 4; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct ArmFailSafeRequest { - INT16U expiryLengthSeconds = 0; - INT64U breadcrumb = 1; - } - - request struct SetRegulatoryConfigRequest { - RegulatoryLocationType newRegulatoryConfig = 0; - CHAR_STRING countryCode = 1; - INT64U breadcrumb = 2; - } - - response struct ArmFailSafeResponse = 1 { - CommissioningError errorCode = 0; - CHAR_STRING debugText = 1; - } - - response struct SetRegulatoryConfigResponse = 3 { - CommissioningError errorCode = 0; - CHAR_STRING debugText = 1; - } - - response struct CommissioningCompleteResponse = 5 { - CommissioningError errorCode = 0; - CHAR_STRING debugText = 1; - } - - command access(invoke: administer) ArmFailSafe(ArmFailSafeRequest): ArmFailSafeResponse = 0; - command access(invoke: administer) SetRegulatoryConfig(SetRegulatoryConfigRequest): SetRegulatoryConfigResponse = 2; - fabric command access(invoke: administer) CommissioningComplete(): CommissioningCompleteResponse = 4; -} - -server cluster NetworkCommissioning = 49 { - enum NetworkCommissioningStatus : ENUM8 { - kSuccess = 0; - kOutOfRange = 1; - kBoundsExceeded = 2; - kNetworkIDNotFound = 3; - kDuplicateNetworkID = 4; - kNetworkNotFound = 5; - kRegulatoryError = 6; - kAuthFailure = 7; - kUnsupportedSecurity = 8; - kOtherConnectionFailure = 9; - kIPV6Failed = 10; - kIPBindFailed = 11; - kUnknownError = 12; - } - - enum WiFiBand : ENUM8 { - k2g4 = 0; - k3g65 = 1; - k5g = 2; - k6g = 3; - k60g = 4; - } - - bitmap NetworkCommissioningFeature : BITMAP32 { - kWiFiNetworkInterface = 0x1; - kThreadNetworkInterface = 0x2; - kEthernetNetworkInterface = 0x4; - } - - bitmap WiFiSecurity : BITMAP8 { - kUnencrypted = 0x1; - kWepPersonal = 0x2; - kWpaPersonal = 0x4; - kWpa2Personal = 0x8; - kWpa3Personal = 0x10; - } - - struct NetworkInfo { - octet_string<32> networkID = 0; - boolean connected = 1; - } - - struct WiFiInterfaceScanResult { - WiFiSecurity security = 0; - octet_string<32> ssid = 1; - octet_string<6> bssid = 2; - int16u channel = 3; - WiFiBand wiFiBand = 4; - int8s rssi = 5; - } - - struct ThreadInterfaceScanResult { - int16u panId = 0; - int64u extendedPanId = 1; - char_string<16> networkName = 2; - int16u channel = 3; - int8u version = 4; - octet_string<8> extendedAddress = 5; - int8s rssi = 6; - int8u lqi = 7; - } - - readonly attribute access(read: administer) int8u maxNetworks = 0; - readonly attribute access(read: administer) NetworkInfo networks[] = 1; - readonly attribute int8u scanMaxTimeSeconds = 2; - readonly attribute int8u connectMaxTimeSeconds = 3; - attribute access(write: administer) boolean interfaceEnabled = 4; - readonly attribute access(read: administer) nullable NetworkCommissioningStatus lastNetworkingStatus = 5; - readonly attribute access(read: administer) nullable octet_string<32> lastNetworkID = 6; - readonly attribute access(read: administer) nullable int32s lastConnectErrorValue = 7; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct ScanNetworksRequest { - optional nullable OCTET_STRING<32> ssid = 0; - optional INT64U breadcrumb = 1; - } - - request struct AddOrUpdateWiFiNetworkRequest { - OCTET_STRING<32> ssid = 0; - OCTET_STRING<64> credentials = 1; - optional INT64U breadcrumb = 2; - } - - request struct AddOrUpdateThreadNetworkRequest { - OCTET_STRING<254> operationalDataset = 0; - optional INT64U breadcrumb = 1; - } - - request struct RemoveNetworkRequest { - OCTET_STRING<32> networkID = 0; - optional INT64U breadcrumb = 1; - } - - request struct ConnectNetworkRequest { - OCTET_STRING<32> networkID = 0; - optional INT64U breadcrumb = 1; - } - - request struct ReorderNetworkRequest { - OCTET_STRING<32> networkID = 0; - INT8U networkIndex = 1; - optional INT64U breadcrumb = 2; - } - - response struct ScanNetworksResponse = 1 { - NetworkCommissioningStatus networkingStatus = 0; - optional CHAR_STRING debugText = 1; - optional WiFiInterfaceScanResult wiFiScanResults[] = 2; - optional ThreadInterfaceScanResult threadScanResults[] = 3; - } - - response struct NetworkConfigResponse = 5 { - NetworkCommissioningStatus networkingStatus = 0; - optional CHAR_STRING<512> debugText = 1; - optional INT8U networkIndex = 2; - } - - response struct ConnectNetworkResponse = 7 { - NetworkCommissioningStatus networkingStatus = 0; - optional CHAR_STRING debugText = 1; - nullable INT32S errorValue = 2; - } - - command access(invoke: administer) ScanNetworks(ScanNetworksRequest): ScanNetworksResponse = 0; - command access(invoke: administer) AddOrUpdateWiFiNetwork(AddOrUpdateWiFiNetworkRequest): NetworkConfigResponse = 2; - command access(invoke: administer) AddOrUpdateThreadNetwork(AddOrUpdateThreadNetworkRequest): NetworkConfigResponse = 3; - command access(invoke: administer) RemoveNetwork(RemoveNetworkRequest): NetworkConfigResponse = 4; - command access(invoke: administer) ConnectNetwork(ConnectNetworkRequest): ConnectNetworkResponse = 6; - command access(invoke: administer) ReorderNetwork(ReorderNetworkRequest): NetworkConfigResponse = 8; -} - -server cluster DiagnosticLogs = 50 { - enum LogsIntent : ENUM8 { - kEndUserSupport = 0; - kNetworkDiag = 1; - kCrashLogs = 2; - } - - enum LogsStatus : ENUM8 { - kSuccess = 0; - kExhausted = 1; - kNoLogs = 2; - kBusy = 3; - kDenied = 4; - } - - enum LogsTransferProtocol : ENUM8 { - kResponsePayload = 0; - kBdx = 1; - } - - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct RetrieveLogsRequestRequest { - LogsIntent intent = 0; - LogsTransferProtocol requestedProtocol = 1; - OCTET_STRING<32> transferFileDesignator = 2; - } - - command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; -} - -server cluster GeneralDiagnostics = 51 { - enum BootReasonType : ENUM8 { - kUnspecified = 0; - kPowerOnReboot = 1; - kBrownOutReset = 2; - kSoftwareWatchdogReset = 3; - kHardwareWatchdogReset = 4; - kSoftwareUpdateCompleted = 5; - kSoftwareReset = 6; - } - - enum HardwareFaultType : ENUM8 { - kUnspecified = 0; - kRadio = 1; - kSensor = 2; - kResettableOverTemp = 3; - kNonResettableOverTemp = 4; - kPowerSource = 5; - kVisualDisplayFault = 6; - kAudioOutputFault = 7; - kUserInterfaceFault = 8; - kNonVolatileMemoryError = 9; - kTamperDetected = 10; - } - - enum InterfaceType : ENUM8 { - kUnspecified = 0; - kWiFi = 1; - kEthernet = 2; - kCellular = 3; - kThread = 4; - } - - enum NetworkFaultType : ENUM8 { - kUnspecified = 0; - kHardwareFailure = 1; - kNetworkJammed = 2; - kConnectionFailed = 3; - } - - enum RadioFaultType : ENUM8 { - kUnspecified = 0; - kWiFiFault = 1; - kCellularFault = 2; - kThreadFault = 3; - kNFCFault = 4; - kBLEFault = 5; - kEthernetFault = 6; - } - - struct NetworkInterfaceType { - char_string<32> name = 0; - boolean isOperational = 1; - nullable boolean offPremiseServicesReachableIPv4 = 2; - nullable boolean offPremiseServicesReachableIPv6 = 3; - octet_string<8> hardwareAddress = 4; - octet_string IPv4Addresses[] = 5; - octet_string IPv6Addresses[] = 6; - InterfaceType type = 7; - } - - critical event HardwareFaultChange = 0 { - HardwareFaultType current[] = 0; - HardwareFaultType previous[] = 1; - } - - critical event RadioFaultChange = 1 { - RadioFaultType current[] = 0; - RadioFaultType previous[] = 1; - } - - critical event NetworkFaultChange = 2 { - NetworkFaultType current[] = 0; - NetworkFaultType previous[] = 1; - } - - critical event BootReason = 3 { - BootReasonType bootReason = 0; - } - - readonly attribute NetworkInterfaceType networkInterfaces[] = 0; - readonly attribute int16u rebootCount = 1; - readonly attribute int64u upTime = 2; - readonly attribute int32u totalOperationalHours = 3; - readonly attribute enum8 bootReasons = 4; - readonly attribute ENUM8 activeHardwareFaults[] = 5; - readonly attribute ENUM8 activeRadioFaults[] = 6; - readonly attribute ENUM8 activeNetworkFaults[] = 7; - readonly attribute boolean testEventTriggersEnabled = 8; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct TestEventTriggerRequest { - OCTET_STRING<16> enableKey = 0; - INT64U eventTrigger = 1; - } - - command access(invoke: manage) TestEventTrigger(TestEventTriggerRequest): DefaultSuccess = 0; -} - -server cluster SoftwareDiagnostics = 52 { - bitmap SoftwareDiagnosticsFeature : BITMAP32 { - kWaterMarks = 0x1; - } - - struct ThreadMetrics { - int64u id = 0; - optional char_string<8> name = 1; - optional int32u stackFreeCurrent = 2; - optional int32u stackFreeMinimum = 3; - optional int32u stackSize = 4; - } - - info event SoftwareFault = 0 { - INT64U id = 0; - optional CHAR_STRING name = 1; - optional OCTET_STRING faultRecording = 2; - } - - readonly attribute ThreadMetrics threadMetrics[] = 0; - readonly attribute int64u currentHeapFree = 1; - readonly attribute int64u currentHeapUsed = 2; - readonly attribute int64u currentHeapHighWatermark = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetWatermarks(): DefaultSuccess = 0; -} - -server cluster ThreadNetworkDiagnostics = 53 { - enum NetworkFault : ENUM8 { - kUnspecified = 0; - kLinkDown = 1; - kHardwareFailure = 2; - kNetworkJammed = 3; - } - - enum RoutingRole : ENUM8 { - kUnspecified = 0; - kUnassigned = 1; - kSleepyEndDevice = 2; - kEndDevice = 3; - kReed = 4; - kRouter = 5; - kLeader = 6; - } - - enum ThreadConnectionStatus : ENUM8 { - kConnected = 0; - kNotConnected = 1; - } - - bitmap ThreadNetworkDiagnosticsFeature : BITMAP32 { - kPacketCounts = 0x1; - kErrorCounts = 0x2; - kMLECounts = 0x4; - kMACCounts = 0x8; - } - - struct NeighborTable { - int64u extAddress = 0; - int32u age = 1; - int16u rloc16 = 2; - int32u linkFrameCounter = 3; - int32u mleFrameCounter = 4; - int8u lqi = 5; - nullable int8s averageRssi = 6; - nullable int8s lastRssi = 7; - int8u frameErrorRate = 8; - int8u messageErrorRate = 9; - boolean rxOnWhenIdle = 10; - boolean fullThreadDevice = 11; - boolean fullNetworkData = 12; - boolean isChild = 13; - } - - struct RouteTable { - int64u extAddress = 0; - int16u rloc16 = 1; - int8u routerId = 2; - int8u nextHop = 3; - int8u pathCost = 4; - int8u LQIIn = 5; - int8u LQIOut = 6; - int8u age = 7; - boolean allocated = 8; - boolean linkEstablished = 9; - } - - struct SecurityPolicy { - int16u rotationTime = 0; - bitmap16 flags = 1; - } - - struct OperationalDatasetComponents { - boolean activeTimestampPresent = 0; - boolean pendingTimestampPresent = 1; - boolean masterKeyPresent = 2; - boolean networkNamePresent = 3; - boolean extendedPanIdPresent = 4; - boolean meshLocalPrefixPresent = 5; - boolean delayPresent = 6; - boolean panIdPresent = 7; - boolean channelPresent = 8; - boolean pskcPresent = 9; - boolean securityPolicyPresent = 10; - boolean channelMaskPresent = 11; - } - - info event ConnectionStatus = 0 { - ThreadConnectionStatus connectionStatus = 0; - } - - info event NetworkFaultChange = 1 { - NetworkFault current[] = 0; - NetworkFault previous[] = 1; - } - - readonly attribute nullable int16u channel = 0; - readonly attribute nullable RoutingRole routingRole = 1; - readonly attribute nullable char_string<16> networkName = 2; - readonly attribute nullable int16u panId = 3; - readonly attribute nullable int64u extendedPanId = 4; - readonly attribute nullable octet_string<17> meshLocalPrefix = 5; - readonly attribute int64u overrunCount = 6; - readonly attribute NeighborTable neighborTableList[] = 7; - readonly attribute RouteTable routeTableList[] = 8; - readonly attribute nullable int32u partitionId = 9; - readonly attribute nullable int8u weighting = 10; - readonly attribute nullable int8u dataVersion = 11; - readonly attribute nullable int8u stableDataVersion = 12; - readonly attribute nullable int8u leaderRouterId = 13; - readonly attribute int16u detachedRoleCount = 14; - readonly attribute int16u childRoleCount = 15; - readonly attribute int16u routerRoleCount = 16; - readonly attribute int16u leaderRoleCount = 17; - readonly attribute int16u attachAttemptCount = 18; - readonly attribute int16u partitionIdChangeCount = 19; - readonly attribute int16u betterPartitionAttachAttemptCount = 20; - readonly attribute int16u parentChangeCount = 21; - readonly attribute int32u txTotalCount = 22; - readonly attribute int32u txUnicastCount = 23; - readonly attribute int32u txBroadcastCount = 24; - readonly attribute int32u txAckRequestedCount = 25; - readonly attribute int32u txAckedCount = 26; - readonly attribute int32u txNoAckRequestedCount = 27; - readonly attribute int32u txDataCount = 28; - readonly attribute int32u txDataPollCount = 29; - readonly attribute int32u txBeaconCount = 30; - readonly attribute int32u txBeaconRequestCount = 31; - readonly attribute int32u txOtherCount = 32; - readonly attribute int32u txRetryCount = 33; - readonly attribute int32u txDirectMaxRetryExpiryCount = 34; - readonly attribute int32u txIndirectMaxRetryExpiryCount = 35; - readonly attribute int32u txErrCcaCount = 36; - readonly attribute int32u txErrAbortCount = 37; - readonly attribute int32u txErrBusyChannelCount = 38; - readonly attribute int32u rxTotalCount = 39; - readonly attribute int32u rxUnicastCount = 40; - readonly attribute int32u rxBroadcastCount = 41; - readonly attribute int32u rxDataCount = 42; - readonly attribute int32u rxDataPollCount = 43; - readonly attribute int32u rxBeaconCount = 44; - readonly attribute int32u rxBeaconRequestCount = 45; - readonly attribute int32u rxOtherCount = 46; - readonly attribute int32u rxAddressFilteredCount = 47; - readonly attribute int32u rxDestAddrFilteredCount = 48; - readonly attribute int32u rxDuplicatedCount = 49; - readonly attribute int32u rxErrNoFrameCount = 50; - readonly attribute int32u rxErrUnknownNeighborCount = 51; - readonly attribute int32u rxErrInvalidSrcAddrCount = 52; - readonly attribute int32u rxErrSecCount = 53; - readonly attribute int32u rxErrFcsCount = 54; - readonly attribute int32u rxErrOtherCount = 55; - readonly attribute nullable int64u activeTimestamp = 56; - readonly attribute nullable int64u pendingTimestamp = 57; - readonly attribute nullable int32u delay = 58; - readonly attribute nullable SecurityPolicy securityPolicy = 59; - readonly attribute nullable octet_string<4> channelPage0Mask = 60; - readonly attribute nullable OperationalDatasetComponents operationalDatasetComponents = 61; - readonly attribute NetworkFault activeNetworkFaultsList[] = 62; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetCounts(): DefaultSuccess = 0; -} - -server cluster WiFiNetworkDiagnostics = 54 { - enum AssociationFailureCause : ENUM8 { - kUnknown = 0; - kAssociationFailed = 1; - kAuthenticationFailed = 2; - kSsidNotFound = 3; - } - - enum SecurityType : ENUM8 { - kUnspecified = 0; - kNone = 1; - kWep = 2; - kWpa = 3; - kWpa2 = 4; - kWpa3 = 5; - } - - enum WiFiConnectionStatus : ENUM8 { - kConnected = 0; - kNotConnected = 1; - } - - enum WiFiVersionType : ENUM8 { - k80211a = 0; - k80211b = 1; - k80211g = 2; - k80211n = 3; - k80211ac = 4; - k80211ax = 5; - } - - info event Disconnection = 0 { - INT16U reasonCode = 0; - } - - info event AssociationFailure = 1 { - AssociationFailureCause associationFailure = 0; - INT16U status = 1; - } - - info event ConnectionStatus = 2 { - WiFiConnectionStatus connectionStatus = 0; - } - - readonly attribute nullable octet_string<6> bssid = 0; - readonly attribute nullable SecurityType securityType = 1; - readonly attribute nullable WiFiVersionType wiFiVersion = 2; - readonly attribute nullable int16u channelNumber = 3; - readonly attribute nullable int8s rssi = 4; - readonly attribute nullable int32u beaconLostCount = 5; - readonly attribute nullable int32u beaconRxCount = 6; - readonly attribute nullable int32u packetMulticastRxCount = 7; - readonly attribute nullable int32u packetMulticastTxCount = 8; - readonly attribute nullable int32u packetUnicastRxCount = 9; - readonly attribute nullable int32u packetUnicastTxCount = 10; - readonly attribute nullable int64u currentMaxRate = 11; - readonly attribute nullable int64u overrunCount = 12; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetCounts(): DefaultSuccess = 0; -} - -server cluster EthernetNetworkDiagnostics = 55 { - enum PHYRateType : ENUM8 { - k10m = 0; - k100m = 1; - k1000m = 2; - k25g = 3; - k5g = 4; - k10g = 5; - k40g = 6; - k100g = 7; - k200g = 8; - k400g = 9; - } - - readonly attribute nullable PHYRateType PHYRate = 0; - readonly attribute nullable boolean fullDuplex = 1; - readonly attribute int64u packetRxCount = 2; - readonly attribute int64u packetTxCount = 3; - readonly attribute int64u txErrCount = 4; - readonly attribute int64u collisionCount = 5; - readonly attribute int64u overrunCount = 6; - readonly attribute nullable boolean carrierDetect = 7; - readonly attribute int64u timeSinceReset = 8; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - command ResetCounts(): DefaultSuccess = 0; -} - -server cluster Switch = 59 { - bitmap SwitchFeature : BITMAP32 { - kLatchingSwitch = 0x1; - kMomentarySwitch = 0x2; - kMomentarySwitchRelease = 0x4; - kMomentarySwitchLongPress = 0x8; - kMomentarySwitchMultiPress = 0x10; - } - - info event SwitchLatched = 0 { - INT8U newPosition = 0; - } - - info event InitialPress = 1 { - INT8U newPosition = 0; - } - - info event LongPress = 2 { - INT8U newPosition = 0; - } - - info event ShortRelease = 3 { - INT8U previousPosition = 0; - } - - info event LongRelease = 4 { - INT8U previousPosition = 0; - } - - info event MultiPressOngoing = 5 { - INT8U newPosition = 0; - INT8U currentNumberOfPressesCounted = 1; - } - - info event MultiPressComplete = 6 { - INT8U newPosition = 0; - INT8U totalNumberOfPressesCounted = 1; - } - - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster AdministratorCommissioning = 60 { - enum CommissioningWindowStatus : ENUM8 { - kWindowNotOpen = 0; - kEnhancedWindowOpen = 1; - kBasicWindowOpen = 2; - } - - enum StatusCode : ENUM8 { - kBusy = 2; - kPAKEParameterError = 3; - kWindowNotOpen = 4; - } - - readonly attribute CommissioningWindowStatus windowStatus = 0; - readonly attribute nullable fabric_idx adminFabricIndex = 1; - readonly attribute nullable int16u adminVendorId = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct OpenCommissioningWindowRequest { - INT16U commissioningTimeout = 0; - OCTET_STRING PAKEVerifier = 1; - INT16U discriminator = 2; - INT32U iterations = 3; - OCTET_STRING salt = 4; - } - - request struct OpenBasicCommissioningWindowRequest { - INT16U commissioningTimeout = 0; - } - - timed command access(invoke: administer) OpenCommissioningWindow(OpenCommissioningWindowRequest): DefaultSuccess = 0; - timed command access(invoke: administer) OpenBasicCommissioningWindow(OpenBasicCommissioningWindowRequest): DefaultSuccess = 1; - timed command access(invoke: administer) RevokeCommissioning(): DefaultSuccess = 2; -} - -server cluster OperationalCredentials = 62 { - enum OperationalCertStatus : ENUM8 { - kSuccess = 0; - kInvalidPublicKey = 1; - kInvalidNodeOpId = 2; - kInvalidNOC = 3; - kMissingCsr = 4; - kTableFull = 5; - kInvalidAdminSubject = 6; - kFabricConflict = 9; - kLabelConflict = 10; - kInvalidFabricIndex = 11; - } - - fabric_scoped struct NOCStruct { - fabric_sensitive octet_string noc = 1; - nullable fabric_sensitive octet_string icac = 2; - fabric_idx fabricIndex = 254; - } - - fabric_scoped struct FabricDescriptor { - octet_string<65> rootPublicKey = 1; - vendor_id vendorId = 2; - fabric_id fabricId = 3; - node_id nodeId = 4; - char_string<32> label = 5; - fabric_idx fabricIndex = 254; - } - - readonly attribute access(read: administer) NOCStruct NOCs[] = 0; - readonly attribute FabricDescriptor fabrics[] = 1; - readonly attribute int8u supportedFabrics = 2; - readonly attribute int8u commissionedFabrics = 3; - readonly attribute OCTET_STRING trustedRootCertificates[] = 4; - readonly attribute int8u currentFabricIndex = 5; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct AttestationRequestRequest { - OCTET_STRING attestationNonce = 0; - } - - request struct CertificateChainRequestRequest { - INT8U certificateType = 0; - } - - request struct CSRRequestRequest { - OCTET_STRING CSRNonce = 0; - optional boolean isForUpdateNOC = 1; - } - - request struct AddNOCRequest { - OCTET_STRING NOCValue = 0; - optional OCTET_STRING ICACValue = 1; - OCTET_STRING IPKValue = 2; - Int64u caseAdminSubject = 3; - VENDOR_ID adminVendorId = 4; - } - - request struct UpdateNOCRequest { - OCTET_STRING NOCValue = 0; - optional OCTET_STRING ICACValue = 1; - } - - request struct UpdateFabricLabelRequest { - CHAR_STRING<32> label = 0; - } - - request struct RemoveFabricRequest { - fabric_idx fabricIndex = 0; - } - - request struct AddTrustedRootCertificateRequest { - OCTET_STRING rootCertificate = 0; - } - - response struct AttestationResponse = 1 { - OCTET_STRING attestationElements = 0; - OCTET_STRING signature = 1; - } - - response struct CertificateChainResponse = 3 { - OCTET_STRING certificate = 0; - } - - response struct CSRResponse = 5 { - OCTET_STRING NOCSRElements = 0; - OCTET_STRING attestationSignature = 1; - } - - response struct NOCResponse = 8 { - OperationalCertStatus statusCode = 0; - optional fabric_idx fabricIndex = 1; - optional CHAR_STRING debugText = 2; - } - - command access(invoke: administer) AttestationRequest(AttestationRequestRequest): AttestationResponse = 0; - command access(invoke: administer) CertificateChainRequest(CertificateChainRequestRequest): CertificateChainResponse = 2; - command access(invoke: administer) CSRRequest(CSRRequestRequest): CSRResponse = 4; - command access(invoke: administer) AddNOC(AddNOCRequest): NOCResponse = 6; - fabric command access(invoke: administer) UpdateNOC(UpdateNOCRequest): NOCResponse = 7; - fabric command access(invoke: administer) UpdateFabricLabel(UpdateFabricLabelRequest): NOCResponse = 9; - command access(invoke: administer) RemoveFabric(RemoveFabricRequest): NOCResponse = 10; - command access(invoke: administer) AddTrustedRootCertificate(AddTrustedRootCertificateRequest): DefaultSuccess = 11; -} - -server cluster GroupKeyManagement = 63 { - enum GroupKeySecurityPolicy : ENUM8 { - kTrustFirst = 0; - kCacheAndSync = 1; - } - - fabric_scoped struct GroupKeyMapStruct { - group_id groupId = 1; - int16u groupKeySetID = 2; - fabric_idx fabricIndex = 254; - } - - fabric_scoped struct GroupInfoMapStruct { - group_id groupId = 1; - endpoint_no endpoints[] = 2; - optional char_string<16> groupName = 3; - fabric_idx fabricIndex = 254; - } - - struct GroupKeySetStruct { - int16u groupKeySetID = 0; - GroupKeySecurityPolicy groupKeySecurityPolicy = 1; - nullable octet_string<16> epochKey0 = 2; - nullable epoch_us epochStartTime0 = 3; - nullable octet_string<16> epochKey1 = 4; - nullable epoch_us epochStartTime1 = 5; - nullable octet_string<16> epochKey2 = 6; - nullable epoch_us epochStartTime2 = 7; - } - - attribute access(write: manage) GroupKeyMapStruct groupKeyMap[] = 0; - readonly attribute GroupInfoMapStruct groupTable[] = 1; - readonly attribute int16u maxGroupsPerFabric = 2; - readonly attribute int16u maxGroupKeysPerFabric = 3; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct KeySetWriteRequest { - GroupKeySetStruct groupKeySet = 0; - } - - request struct KeySetReadRequest { - INT16U groupKeySetID = 0; - } - - request struct KeySetRemoveRequest { - INT16U groupKeySetID = 0; - } - - request struct KeySetReadAllIndicesRequest { - INT16U groupKeySetIDs[] = 0; - } - - response struct KeySetReadResponse = 2 { - GroupKeySetStruct groupKeySet = 0; - } - - response struct KeySetReadAllIndicesResponse = 5 { - INT16U groupKeySetIDs[] = 0; - } - - fabric command access(invoke: administer) KeySetWrite(KeySetWriteRequest): DefaultSuccess = 0; - fabric command access(invoke: administer) KeySetRead(KeySetReadRequest): KeySetReadResponse = 1; - fabric command access(invoke: administer) KeySetRemove(KeySetRemoveRequest): DefaultSuccess = 3; - fabric command access(invoke: administer) KeySetReadAllIndices(KeySetReadAllIndicesRequest): KeySetReadAllIndicesResponse = 4; -} - -server cluster FixedLabel = 64 { - readonly attribute LabelStruct labelList[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster UserLabel = 65 { - attribute access(write: manage) LabelStruct labelList[] = 0; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -server cluster ColorControl = 768 { - enum ColorLoopAction : ENUM8 { - kDeactivate = 0; - kActivateFromColorLoopStartEnhancedHue = 1; - kActivateFromEnhancedCurrentHue = 2; - } - - enum ColorLoopDirection : ENUM8 { - kDecrementHue = 0; - kIncrementHue = 1; - } - - enum ColorMode : ENUM8 { - kCurrentHueAndCurrentSaturation = 0; - kCurrentXAndCurrentY = 1; - kColorTemperature = 2; - } - - enum HueDirection : ENUM8 { - kShortestDistance = 0; - kLongestDistance = 1; - kUp = 2; - kDown = 3; - } - - enum HueMoveMode : ENUM8 { - kStop = 0; - kUp = 1; - kDown = 3; - } - - enum HueStepMode : ENUM8 { - kUp = 1; - kDown = 3; - } - - enum SaturationMoveMode : ENUM8 { - kStop = 0; - kUp = 1; - kDown = 3; - } - - enum SaturationStepMode : ENUM8 { - kUp = 1; - kDown = 3; - } - - bitmap ColorCapabilities : BITMAP16 { - kHueSaturationSupported = 0x1; - kEnhancedHueSupported = 0x2; - kColorLoopSupported = 0x4; - kXYAttributesSupported = 0x8; - kColorTemperatureSupported = 0x10; - } - - bitmap ColorControlFeature : BITMAP32 { - kHueAndSaturation = 0x1; - kEnhancedHue = 0x2; - kColorLoop = 0x4; - kXy = 0x8; - kColorTemperature = 0x10; - } - - bitmap ColorLoopUpdateFlags : BITMAP8 { - kUpdateAction = 0x1; - kUpdateDirection = 0x2; - kUpdateTime = 0x4; - kUpdateStartHue = 0x8; - } - - readonly attribute int8u currentHue = 0; - readonly attribute int8u currentSaturation = 1; - readonly attribute int16u remainingTime = 2; - readonly attribute int16u currentX = 3; - readonly attribute int16u currentY = 4; - readonly attribute int16u colorTemperatureMireds = 7; - readonly attribute enum8 colorMode = 8; - attribute bitmap8 options = 15; - readonly attribute nullable int8u numberOfPrimaries = 16; - readonly attribute int16u enhancedCurrentHue = 16384; - readonly attribute enum8 enhancedColorMode = 16385; - readonly attribute int8u colorLoopActive = 16386; - readonly attribute int8u colorLoopDirection = 16387; - readonly attribute int16u colorLoopTime = 16388; - readonly attribute int16u colorLoopStartEnhancedHue = 16389; - readonly attribute int16u colorLoopStoredEnhancedHue = 16390; - readonly attribute bitmap16 colorCapabilities = 16394; - readonly attribute int16u colorTempPhysicalMinMireds = 16395; - readonly attribute int16u colorTempPhysicalMaxMireds = 16396; - readonly attribute int16u coupleColorTempToLevelMinMireds = 16397; - attribute access(write: manage) nullable int16u startUpColorTemperatureMireds = 16400; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct MoveToHueRequest { - INT8U hue = 0; - HueDirection direction = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveHueRequest { - HueMoveMode moveMode = 0; - INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepHueRequest { - HueStepMode stepMode = 0; - INT8U stepSize = 1; - INT8U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToSaturationRequest { - INT8U saturation = 0; - INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct MoveSaturationRequest { - SaturationMoveMode moveMode = 0; - INT8U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepSaturationRequest { - SaturationStepMode stepMode = 0; - INT8U stepSize = 1; - INT8U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToHueAndSaturationRequest { - INT8U hue = 0; - INT8U saturation = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToColorRequest { - INT16U colorX = 0; - INT16U colorY = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveColorRequest { - INT16S rateX = 0; - INT16S rateY = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct StepColorRequest { - INT16S stepX = 0; - INT16S stepY = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct MoveToColorTemperatureRequest { - INT16U colorTemperature = 0; - INT16U transitionTime = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct EnhancedMoveToHueRequest { - INT16U enhancedHue = 0; - HueDirection direction = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct EnhancedMoveHueRequest { - HueMoveMode moveMode = 0; - INT16U rate = 1; - BITMAP8 optionsMask = 2; - BITMAP8 optionsOverride = 3; - } - - request struct EnhancedStepHueRequest { - HueStepMode stepMode = 0; - INT16U stepSize = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct EnhancedMoveToHueAndSaturationRequest { - INT16U enhancedHue = 0; - INT8U saturation = 1; - INT16U transitionTime = 2; - BITMAP8 optionsMask = 3; - BITMAP8 optionsOverride = 4; - } - - request struct ColorLoopSetRequest { - ColorLoopUpdateFlags updateFlags = 0; - ColorLoopAction action = 1; - ColorLoopDirection direction = 2; - INT16U time = 3; - INT16U startHue = 4; - BITMAP8 optionsMask = 5; - BITMAP8 optionsOverride = 6; - } - - request struct StopMoveStepRequest { - BITMAP8 optionsMask = 0; - BITMAP8 optionsOverride = 1; - } - - request struct MoveColorTemperatureRequest { - HueMoveMode moveMode = 0; - INT16U rate = 1; - INT16U colorTemperatureMinimumMireds = 2; - INT16U colorTemperatureMaximumMireds = 3; - BITMAP8 optionsMask = 4; - BITMAP8 optionsOverride = 5; - } - - request struct StepColorTemperatureRequest { - HueStepMode stepMode = 0; - INT16U stepSize = 1; - INT16U transitionTime = 2; - INT16U colorTemperatureMinimumMireds = 3; - INT16U colorTemperatureMaximumMireds = 4; - BITMAP8 optionsMask = 5; - BITMAP8 optionsOverride = 6; - } - - command MoveToHue(MoveToHueRequest): DefaultSuccess = 0; - command MoveHue(MoveHueRequest): DefaultSuccess = 1; - command StepHue(StepHueRequest): DefaultSuccess = 2; - command MoveToSaturation(MoveToSaturationRequest): DefaultSuccess = 3; - command MoveSaturation(MoveSaturationRequest): DefaultSuccess = 4; - command StepSaturation(StepSaturationRequest): DefaultSuccess = 5; - command MoveToHueAndSaturation(MoveToHueAndSaturationRequest): DefaultSuccess = 6; - command MoveToColor(MoveToColorRequest): DefaultSuccess = 7; - command MoveColor(MoveColorRequest): DefaultSuccess = 8; - command StepColor(StepColorRequest): DefaultSuccess = 9; - command MoveToColorTemperature(MoveToColorTemperatureRequest): DefaultSuccess = 10; - command EnhancedMoveToHue(EnhancedMoveToHueRequest): DefaultSuccess = 64; - command EnhancedMoveHue(EnhancedMoveHueRequest): DefaultSuccess = 65; - command EnhancedStepHue(EnhancedStepHueRequest): DefaultSuccess = 66; - command EnhancedMoveToHueAndSaturation(EnhancedMoveToHueAndSaturationRequest): DefaultSuccess = 67; - command ColorLoopSet(ColorLoopSetRequest): DefaultSuccess = 68; - command StopMoveStep(StopMoveStepRequest): DefaultSuccess = 71; - command MoveColorTemperature(MoveColorTemperatureRequest): DefaultSuccess = 75; - command StepColorTemperature(StepColorTemperatureRequest): DefaultSuccess = 76; -} - -server cluster OccupancySensing = 1030 { - readonly attribute bitmap8 occupancy = 0; - readonly attribute enum8 occupancySensorType = 1; - readonly attribute bitmap8 occupancySensorTypeBitmap = 2; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; -} - -endpoint 0 { - device type rootdevice = 22, version 1; - binding cluster OtaSoftwareUpdateProvider; - - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Descriptor { - callback attribute deviceTypeList; - callback attribute serverList; - callback attribute clientList; - callback attribute partsList; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster AccessControl { - callback attribute acl; - callback attribute extension; - callback attribute subjectsPerAccessControlEntry default = 4; - callback attribute targetsPerAccessControlEntry default = 3; - callback attribute accessControlEntriesPerFabric default = 4; - callback attribute attributeList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster BasicInformation { - callback attribute dataModelRevision default = 10; - callback attribute vendorName; - callback attribute vendorID; - callback attribute productName; - callback attribute productID; - persist attribute nodeLabel; - callback attribute location default = "XX"; - callback attribute hardwareVersion; - callback attribute hardwareVersionString; - callback attribute softwareVersion; - callback attribute softwareVersionString; - callback attribute manufacturingDate default = "20210614123456ZZ"; - callback attribute partNumber; - callback attribute productURL; - callback attribute productLabel; - callback attribute serialNumber; - persist attribute localConfigDisabled; - ram attribute reachable default = 1; - callback attribute uniqueID; - callback attribute capabilityMinima; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster OtaSoftwareUpdateRequestor { - callback attribute defaultOtaProviders; - ram attribute updatePossible default = 1; - ram attribute updateState; - ram attribute updateStateProgress; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster LocalizationConfiguration { - persist attribute activeLocale default = "en-US"; - callback attribute supportedLocales; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster TimeFormatLocalization { - persist attribute hourFormat; - persist attribute activeCalendarType; - callback attribute supportedCalendarTypes; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster GeneralCommissioning { - ram attribute breadcrumb; - callback attribute basicCommissioningInfo; - callback attribute regulatoryConfig; - callback attribute locationCapability; - callback attribute supportsConcurrentConnection default = 1; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster NetworkCommissioning { - ram attribute maxNetworks; - callback attribute networks; - ram attribute scanMaxTimeSeconds; - ram attribute connectMaxTimeSeconds; - ram attribute interfaceEnabled; - ram attribute lastNetworkingStatus; - ram attribute lastNetworkID; - ram attribute lastConnectErrorValue; - ram attribute featureMap default = 2; - ram attribute clusterRevision default = 1; - } - - server cluster DiagnosticLogs { - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster GeneralDiagnostics { - callback attribute networkInterfaces; - callback attribute rebootCount; - callback attribute upTime; - callback attribute totalOperationalHours; - callback attribute bootReasons; - callback attribute activeHardwareFaults; - callback attribute activeRadioFaults; - callback attribute activeNetworkFaults; - callback attribute testEventTriggersEnabled; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster SoftwareDiagnostics { - callback attribute threadMetrics; - callback attribute currentHeapFree; - callback attribute currentHeapUsed; - callback attribute currentHeapHighWatermark; - ram attribute featureMap default = 1; - ram attribute clusterRevision default = 1; - } - - server cluster ThreadNetworkDiagnostics { - callback attribute channel; - callback attribute routingRole; - callback attribute networkName; - callback attribute panId; - callback attribute extendedPanId; - callback attribute meshLocalPrefix; - callback attribute overrunCount; - callback attribute neighborTableList; - callback attribute routeTableList; - callback attribute partitionId; - callback attribute weighting; - callback attribute dataVersion; - callback attribute stableDataVersion; - callback attribute leaderRouterId; - callback attribute detachedRoleCount; - callback attribute childRoleCount; - callback attribute routerRoleCount; - callback attribute leaderRoleCount; - callback attribute attachAttemptCount; - callback attribute partitionIdChangeCount; - callback attribute betterPartitionAttachAttemptCount; - callback attribute parentChangeCount; - callback attribute txTotalCount; - callback attribute txUnicastCount; - callback attribute txBroadcastCount; - callback attribute txAckRequestedCount; - callback attribute txAckedCount; - callback attribute txNoAckRequestedCount; - callback attribute txDataCount; - callback attribute txDataPollCount; - callback attribute txBeaconCount; - callback attribute txBeaconRequestCount; - callback attribute txOtherCount; - callback attribute txRetryCount; - callback attribute txDirectMaxRetryExpiryCount; - callback attribute txIndirectMaxRetryExpiryCount; - callback attribute txErrCcaCount; - callback attribute txErrAbortCount; - callback attribute txErrBusyChannelCount; - callback attribute rxTotalCount; - callback attribute rxUnicastCount; - callback attribute rxBroadcastCount; - callback attribute rxDataCount; - callback attribute rxDataPollCount; - callback attribute rxBeaconCount; - callback attribute rxBeaconRequestCount; - callback attribute rxOtherCount; - callback attribute rxAddressFilteredCount; - callback attribute rxDestAddrFilteredCount; - callback attribute rxDuplicatedCount; - callback attribute rxErrNoFrameCount; - callback attribute rxErrUnknownNeighborCount; - callback attribute rxErrInvalidSrcAddrCount; - callback attribute rxErrSecCount; - callback attribute rxErrFcsCount; - callback attribute rxErrOtherCount; - callback attribute activeTimestamp; - callback attribute pendingTimestamp; - callback attribute delay; - callback attribute securityPolicy; - callback attribute channelPage0Mask; - callback attribute operationalDatasetComponents; - callback attribute activeNetworkFaultsList; - ram attribute featureMap default = 0x000F; - ram attribute clusterRevision default = 1; - } - - server cluster WiFiNetworkDiagnostics { - callback attribute bssid; - callback attribute securityType; - callback attribute wiFiVersion; - callback attribute channelNumber; - callback attribute rssi; - callback attribute beaconLostCount; - callback attribute beaconRxCount; - callback attribute packetMulticastRxCount; - callback attribute packetMulticastTxCount; - callback attribute packetUnicastRxCount; - callback attribute packetUnicastTxCount; - callback attribute currentMaxRate; - callback attribute overrunCount; - ram attribute featureMap default = 3; - ram attribute clusterRevision default = 1; - } - - server cluster EthernetNetworkDiagnostics { - callback attribute PHYRate; - callback attribute fullDuplex; - callback attribute packetRxCount; - callback attribute packetTxCount; - callback attribute txErrCount; - callback attribute collisionCount; - callback attribute overrunCount; - callback attribute carrierDetect; - callback attribute timeSinceReset; - ram attribute featureMap default = 3; - ram attribute clusterRevision default = 1; - } - - server cluster Switch { - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster AdministratorCommissioning { - callback attribute windowStatus; - callback attribute adminFabricIndex default = 1; - callback attribute adminVendorId; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster OperationalCredentials { - callback attribute NOCs; - callback attribute fabrics; - callback attribute supportedFabrics; - callback attribute commissionedFabrics; - callback attribute trustedRootCertificates; - callback attribute currentFabricIndex; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster GroupKeyManagement { - callback attribute groupKeyMap; - callback attribute groupTable; - callback attribute maxGroupsPerFabric; - callback attribute maxGroupKeysPerFabric; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster FixedLabel { - callback attribute labelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } - - server cluster UserLabel { - callback attribute labelList; - ram attribute featureMap; - ram attribute clusterRevision default = 1; - } -} -endpoint 1 { - device type dimmablelight = 257, version 1; - - server cluster Identify { - ram attribute identifyTime; - ram attribute identifyType; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap; - ram attribute clusterRevision default = 4; - } - - server cluster OnOff { - persist attribute onOff; - ram attribute globalSceneControl default = 0x01; - ram attribute onTime; - ram attribute offWaitTime; - persist attribute startUpOnOff default = 0xFF; - ram attribute featureMap default = 1; - ram attribute clusterRevision default = 4; - } - - server cluster LevelControl { - persist attribute currentLevel default = 0x01; - ram attribute remainingTime; - ram attribute minLevel default = 0x01; - ram attribute maxLevel default = 0xFE; - ram attribute currentFrequency; - ram attribute minFrequency; - ram attribute maxFrequency; - ram attribute options; - ram attribute onOffTransitionTime; - ram attribute onLevel default = 0xFF; - ram attribute onTransitionTime; - ram attribute offTransitionTime; - ram attribute defaultMoveRate default = 50; - persist attribute startUpCurrentLevel default = 255; - ram attribute featureMap default = 3; - ram attribute clusterRevision default = 5; - } - - server cluster Descriptor { - callback attribute deviceTypeList; - callback attribute serverList; - callback attribute clientList; - callback attribute partsList; - ram attribute featureMap; - callback attribute clusterRevision default = 1; - } - - server cluster ColorControl { - ram attribute currentHue; - ram attribute currentSaturation; - ram attribute remainingTime; - ram attribute currentX default = 0x616B; - ram attribute currentY default = 0x607D; - ram attribute colorTemperatureMireds default = 0x00FA; - ram attribute colorMode default = 0x01; - ram attribute options; - ram attribute numberOfPrimaries; - ram attribute enhancedCurrentHue; - ram attribute enhancedColorMode default = 0x01; - ram attribute colorLoopActive; - ram attribute colorLoopDirection; - ram attribute colorLoopTime default = 0x0019; - ram attribute colorLoopStartEnhancedHue default = 0x2300; - ram attribute colorLoopStoredEnhancedHue; - ram attribute colorCapabilities default = 0x1F; - ram attribute colorTempPhysicalMinMireds; - ram attribute colorTempPhysicalMaxMireds default = 0xFEFF; - ram attribute coupleColorTempToLevelMinMireds; - ram attribute startUpColorTemperatureMireds; - ram attribute featureMap default = 0x1F; - ram attribute clusterRevision default = 5; - } - - server cluster OccupancySensing { - ram attribute occupancy; - ram attribute occupancySensorType; - ram attribute occupancySensorTypeBitmap; - ram attribute featureMap; - ram attribute clusterRevision default = 3; - } -} diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter deleted file mode 100644 index 2b14f9a5987b7c..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter +++ /dev/null @@ -1,7 +0,0 @@ -client cluster MyCluster = 1 { - request struct FooRequest { - optional OCTET_STRING argument = 0; - } - - command Foo(FooRequest): DefaultSuccess = 0; -} \ No newline at end of file diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter deleted file mode 100644 index 39e5227ba3dc8b..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter +++ /dev/null @@ -1,52 +0,0 @@ -client cluster First = 1 { - attribute int16u someInteger = 1; -} - -client cluster Second = 2 { - fabric_scoped struct FabricDescriptorStruct { - octet_string<65> rootPublicKey = 1; - vendor_id vendorID = 2; - fabric_id fabricID = 3; - node_id nodeID = 4; - char_string<32> label = 5; - fabric_idx fabricIndex = 254; - } - - readonly attribute FabricDescriptorStruct fabrics[] = 0; - readonly attribute octet_string<32> someBytes = 123; -} - -client cluster Third = 3 { - enum MyEnum : enum8 { - kUnknown = 0; - kKnown = 100; - } - - bitmap LevelControlOptions : BITMAP8 { - kExecuteIfOff = 0x1; - kCoupleColorTempToLevel = 0x2; - } - - attribute MyEnum someEnum = 10; - attribute LevelControlOptions options = 20; -} - -server cluster Third = 3 { - enum MyEnum : enum8 { - kUnknown = 0; - kKnown = 100; - } - - attribute MyEnum someEnum = 10; - readonly attribute int16u clusterRevision = 65533; -} - -endpoint 0 { - device type rootdevice = 22, version 1; - binding cluster Second; - - server cluster Third { - ram attribute someEnum; - ram attribute clusterRevision default = 2; - } -} diff --git a/scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter deleted file mode 100644 index 79bc97caa9a048..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter +++ /dev/null @@ -1,4 +0,0 @@ -client cluster MyCluster = 123 { - attribute int16u clusterAttr = 1; -} - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.cpp deleted file mode 100644 index a6d25bd54707df..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include - -namespace chip { -namespace TLVMeta { -namespace { - -using namespace chip::FlatTree; -using namespace chip::TLV; - -const Entry _DemoCluster[] = { - { { AttributeTag(5), "singleFailSafe", ItemType::kDefault }, 3 }, // DemoCluster::ArmFailSafeRequest - { { AttributeTag(100), "armFailsafes", ItemType::kList }, 4 }, // DemoCluster::ArmFailSafeRequest[] -}; - -const Entry _DemoCluster_ArmFailSafeRequest[] = { - { { ContextTag(0), "expiryLengthSeconds", ItemType::kDefault }, kInvalidNodeIndex }, // DemoCluster::INT16U - { { ContextTag(1), "breadcrumb", ItemType::kDefault }, kInvalidNodeIndex }, // DemoCluster::INT64U - { { ContextTag(2), "timeoutMs", ItemType::kDefault }, kInvalidNodeIndex }, // DemoCluster::INT32U -}; - -const Entry _DemoCluster_ArmFailSafeRequest_list_[] = { - { { AnonymousTag(), "Anonymous<>", ItemType::kDefault }, 3 }, // DemoCluster_ArmFailSafeRequest[] -}; - -const Entry _all_clusters[] = { - { { ClusterTag(0x0A), "DemoCluster", ItemType::kDefault }, 2 }, - -}; - -// For any non-structure list like u64[] or similar. -const Entry _primitive_type_list[] = { - { { AnonymousTag(), "Anonymous<>", ItemType::kDefault }, kInvalidNodeIndex }, -}; - -} // namespace - -#define _ENTRY(n) { sizeof(n) / sizeof(n[0]), n} - -const std::array, 3 + 2> clusters_meta = { { - _ENTRY(_all_clusters), // 0 - _ENTRY(_primitive_type_list), // 1 - _ENTRY(_DemoCluster), // 2 - _ENTRY(_DemoCluster_ArmFailSafeRequest), // 3 - _ENTRY(_DemoCluster_ArmFailSafeRequest_list_), // 4 -} }; - -} // namespace TLVMeta -} // namespace chip diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.h deleted file mode 100644 index c8a3aa64885266..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/cpp-tlvmeta/clusters_meta.h +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include - -#include - -namespace chip { -namespace TLVMeta { - -extern const std::array, 3 + 2> clusters_meta; - -} // namespace TLVMeta -} // namespace chip diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPCallbackTypes.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPCallbackTypes.h deleted file mode 100644 index fcb6fe68e06488..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPCallbackTypes.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -typedef void (*CHIPDefaultSuccessCallbackType)(void *, const chip::app::DataModel::NullObjectType &); -typedef void (*CHIPDefaultWriteSuccessCallbackType)(void *); -typedef void (*CHIPDefaultFailureCallbackType)(void *, CHIP_ERROR); - - -typedef void (*CHIPDemoClusterClusterSingleFailSafeAttributeCallbackType)(void *, chip::app::Clusters::DemoCluster::Attributes::SingleFailSafe::TypeInfo::DecodableArgType); -typedef void (*CHIPDemoClusterClusterArmFailsafesAttributeCallbackType)(void *, const chip::app::Clusters::DemoCluster::Attributes::ArmFailsafes::TypeInfo::DecodableType &); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPReadReadCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPReadReadCallbacks.h deleted file mode 100644 index f338e7db9f28e2..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/CHIPReadReadCallbacks.h +++ /dev/null @@ -1,393 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include - -class CHIPBooleanAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPBooleanAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPBooleanAttributeCallback(); - - static void maybeDestroy(CHIPBooleanAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, bool value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPCharStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPCharStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPCharStringAttributeCallback(); - - static void maybeDestroy(CHIPCharStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::CharSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPDoubleAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDoubleAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDoubleAttributeCallback(); - - static void maybeDestroy(CHIPDoubleAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, double value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPFloatAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPFloatAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPFloatAttributeCallback(); - - static void maybeDestroy(CHIPFloatAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, float value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8sAttributeCallback(); - - static void maybeDestroy(CHIPInt8sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8uAttributeCallback(); - - static void maybeDestroy(CHIPInt8uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16sAttributeCallback(); - - static void maybeDestroy(CHIPInt16sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16uAttributeCallback(); - - static void maybeDestroy(CHIPInt16uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32sAttributeCallback(); - - static void maybeDestroy(CHIPInt32sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32uAttributeCallback(); - - static void maybeDestroy(CHIPInt32uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64sAttributeCallback(); - - static void maybeDestroy(CHIPInt64sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64uAttributeCallback(); - - static void maybeDestroy(CHIPInt64uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPOctetStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPOctetStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPOctetStringAttributeCallback(); - - static void maybeDestroy(CHIPOctetStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::ByteSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - - -class CHIPDemoClusterSingleFailSafeAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDemoClusterSingleFailSafeAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDemoClusterSingleFailSafeAttributeCallback(); - - static void maybeDestroy(CHIPDemoClusterSingleFailSafeAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, chip::app::Clusters::DemoCluster::Structs::ArmFailSafeRequest::DecodableType value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - -class CHIPDemoClusterArmFailsafesAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDemoClusterArmFailsafesAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDemoClusterArmFailsafesAttributeCallback(); - - static void maybeDestroy(CHIPDemoClusterArmFailsafesAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::app::DataModel::DecodableList & list); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index fc3ff0a8d4c134..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, DemoClusterCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, DemoClusterCluster, subscribeArmFailsafesAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::DemoCluster::Attributes::ArmFailsafes::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPDemoClusterArmFailsafesAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp deleted file mode 100644 index 400f3dee271a2a..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp +++ /dev/null @@ -1,38 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME -JNI_METHOD(void, DemoClusterCluster, readArmFailsafesAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::DemoCluster::Attributes::ArmFailsafes::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.cpp deleted file mode 100644 index 66462f8a497554..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include - -namespace chip { -namespace TLVMeta { -namespace { - -using namespace chip::FlatTree; -using namespace chip::TLV; - -const Entry _OnOff[] = { - { { AttributeTag(0), "onOff", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::boolean - { { AttributeTag(65532), "featureMap", ItemType::kBitmap }, 8 }, // OnOff::OnOffFeature - { { AttributeTag(65533), "clusterRevision", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::int16u - { { CommandTag(0), "Off", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::Off::() - { { CommandTag(1), "On", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::On::() - { { CommandTag(2), "Toggle", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::Toggle::() -}; - -const Entry _OnOff_OnOffDelayedAllOffEffectVariant[] = { - { { ConstantValueTag(0x0), "kFadeToOffIn0p8Seconds", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffDelayedAllOffEffectVariant::kFadeToOffIn0p8Seconds - { { ConstantValueTag(0x1), "kNoFade", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffDelayedAllOffEffectVariant::kNoFade - { { ConstantValueTag(0x2), "k50PercentDimDownIn0p8SecondsThenFadeToOffIn12Seconds", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffDelayedAllOffEffectVariant::k50PercentDimDownIn0p8SecondsThenFadeToOffIn12Seconds -}; - -const Entry _OnOff_OnOffDyingLightEffectVariant[] = { - { { ConstantValueTag(0x0), "k20PercenterDimUpIn0p5SecondsThenFadeToOffIn1Second", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffDyingLightEffectVariant::k20PercenterDimUpIn0p5SecondsThenFadeToOffIn1Second -}; - -const Entry _OnOff_OnOffEffectIdentifier[] = { - { { ConstantValueTag(0x0), "kDelayedAllOff", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffEffectIdentifier::kDelayedAllOff - { { ConstantValueTag(0x1), "kDyingLight", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffEffectIdentifier::kDyingLight -}; - -const Entry _OnOff_OnOffStartUpOnOff[] = { - { { ConstantValueTag(0x0), "kOff", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffStartUpOnOff::kOff - { { ConstantValueTag(0x1), "kOn", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffStartUpOnOff::kOn - { { ConstantValueTag(0x2), "kTogglePreviousOnOff", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffStartUpOnOff::kTogglePreviousOnOff -}; - -const Entry _OnOff_OnOffControl[] = { - { { ConstantValueTag(0x1), "kAcceptOnlyWhenOn", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffControl::kAcceptOnlyWhenOn -}; - -const Entry _OnOff_OnOffFeature[] = { - { { ConstantValueTag(0x1), "kLighting", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::OnOffFeature::kLighting -}; - -const Entry _OnOff_ScenesFeature[] = { - { { ConstantValueTag(0x1), "kSceneNames", ItemType::kDefault }, kInvalidNodeIndex }, // OnOff::ScenesFeature::kSceneNames -}; - -const Entry _all_clusters[] = { - -}; - -// For any non-structure list like u64[] or similar. -const Entry _primitive_type_list[] = { - { { AnonymousTag(), "Anonymous<>", ItemType::kDefault }, kInvalidNodeIndex }, -}; - -} // namespace - -#define _ENTRY(n) { sizeof(n) / sizeof(n[0]), n} - -const std::array, 8 + 2> clusters_meta = { { - _ENTRY(_all_clusters), // 0 - _ENTRY(_primitive_type_list), // 1 - _ENTRY(_OnOff), // 2 - _ENTRY(_OnOff_OnOffDelayedAllOffEffectVariant), // 3 - _ENTRY(_OnOff_OnOffDyingLightEffectVariant), // 4 - _ENTRY(_OnOff_OnOffEffectIdentifier), // 5 - _ENTRY(_OnOff_OnOffStartUpOnOff), // 6 - _ENTRY(_OnOff_OnOffControl), // 7 - _ENTRY(_OnOff_OnOffFeature), // 8 - _ENTRY(_OnOff_ScenesFeature), // 9 -} }; - -} // namespace TLVMeta -} // namespace chip diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.h deleted file mode 100644 index f2bd0832877be6..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_with_commands/cpp-tlvmeta/clusters_meta.h +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include - -#include - -namespace chip { -namespace TLVMeta { - -extern const std::array, 8 + 2> clusters_meta; - -} // namespace TLVMeta -} // namespace chip diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPCallbackTypes.h b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPCallbackTypes.h deleted file mode 100644 index 6abf7f8bc6b9cc..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPCallbackTypes.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -typedef void (*CHIPDefaultSuccessCallbackType)(void *, const chip::app::DataModel::NullObjectType &); -typedef void (*CHIPDefaultWriteSuccessCallbackType)(void *); -typedef void (*CHIPDefaultFailureCallbackType)(void *, CHIP_ERROR); - - -typedef void (*CHIPDemoClusterClusterSingleLabelAttributeCallbackType)(void *, chip::app::Clusters::DemoCluster::Attributes::SingleLabel::TypeInfo::DecodableArgType); -typedef void (*CHIPDemoClusterClusterSomeLabelsAttributeCallbackType)(void *, const chip::app::Clusters::DemoCluster::Attributes::SomeLabels::TypeInfo::DecodableType &); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPReadReadCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPReadReadCallbacks.h deleted file mode 100644 index 35c84f3ef4c0dd..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/CHIPReadReadCallbacks.h +++ /dev/null @@ -1,393 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include - -class CHIPBooleanAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPBooleanAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPBooleanAttributeCallback(); - - static void maybeDestroy(CHIPBooleanAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, bool value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPCharStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPCharStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPCharStringAttributeCallback(); - - static void maybeDestroy(CHIPCharStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::CharSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPDoubleAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDoubleAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDoubleAttributeCallback(); - - static void maybeDestroy(CHIPDoubleAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, double value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPFloatAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPFloatAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPFloatAttributeCallback(); - - static void maybeDestroy(CHIPFloatAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, float value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8sAttributeCallback(); - - static void maybeDestroy(CHIPInt8sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8uAttributeCallback(); - - static void maybeDestroy(CHIPInt8uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16sAttributeCallback(); - - static void maybeDestroy(CHIPInt16sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16uAttributeCallback(); - - static void maybeDestroy(CHIPInt16uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32sAttributeCallback(); - - static void maybeDestroy(CHIPInt32sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32uAttributeCallback(); - - static void maybeDestroy(CHIPInt32uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64sAttributeCallback(); - - static void maybeDestroy(CHIPInt64sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64uAttributeCallback(); - - static void maybeDestroy(CHIPInt64uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPOctetStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPOctetStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPOctetStringAttributeCallback(); - - static void maybeDestroy(CHIPOctetStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::ByteSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - - -class CHIPDemoClusterSingleLabelAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDemoClusterSingleLabelAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDemoClusterSingleLabelAttributeCallback(); - - static void maybeDestroy(CHIPDemoClusterSingleLabelAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, chip::app::Clusters::DemoCluster::Structs::LabelStruct::DecodableType value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - -class CHIPDemoClusterSomeLabelsAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDemoClusterSomeLabelsAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDemoClusterSomeLabelsAttributeCallback(); - - static void maybeDestroy(CHIPDemoClusterSomeLabelsAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::app::DataModel::DecodableList & list); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index 0ed4b562e6b16d..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, DemoClusterCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, DemoClusterCluster, subscribeSomeLabelsAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::DemoCluster::Attributes::SomeLabels::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPDemoClusterSomeLabelsAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp deleted file mode 100644 index 243f4a46273139..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp +++ /dev/null @@ -1,38 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME -JNI_METHOD(void, DemoClusterCluster, readSomeLabelsAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::DemoCluster::Attributes::SomeLabels::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h deleted file mode 100644 index 713ef6ef5ab70e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h +++ /dev/null @@ -1,130 +0,0 @@ -#pragma once -void MatterAccessControlPluginServerInitCallback(); -void MatterAccountLoginPluginServerInitCallback(); -void MatterActionsPluginServerInitCallback(); -void MatterAdministratorCommissioningPluginServerInitCallback(); -void MatterApplicationBasicPluginServerInitCallback(); -void MatterApplicationLauncherPluginServerInitCallback(); -void MatterAudioOutputPluginServerInitCallback(); -void MatterBarrierControlPluginServerInitCallback(); -void MatterBasicInformationPluginServerInitCallback(); -void MatterBinaryInputBasicPluginServerInitCallback(); -void MatterBindingPluginServerInitCallback(); -void MatterBooleanStatePluginServerInitCallback(); -void MatterChannelPluginServerInitCallback(); -void MatterColorControlPluginServerInitCallback(); -void MatterContentLauncherPluginServerInitCallback(); -void MatterDescriptorPluginServerInitCallback(); -void MatterDiagnosticLogsPluginServerInitCallback(); -void MatterDoorLockPluginServerInitCallback(); -void MatterElectricalMeasurementPluginServerInitCallback(); -void MatterEthernetNetworkDiagnosticsPluginServerInitCallback(); -void MatterFanControlPluginServerInitCallback(); -void MatterFaultInjectionPluginServerInitCallback(); -void MatterFixedLabelPluginServerInitCallback(); -void MatterFlowMeasurementPluginServerInitCallback(); -void MatterGeneralCommissioningPluginServerInitCallback(); -void MatterGeneralDiagnosticsPluginServerInitCallback(); -void MatterGroupKeyManagementPluginServerInitCallback(); -void MatterGroupsPluginServerInitCallback(); -void MatterIdentifyPluginServerInitCallback(); -void MatterIlluminanceMeasurementPluginServerInitCallback(); -void MatterKeypadInputPluginServerInitCallback(); -void MatterLevelControlPluginServerInitCallback(); -void MatterLocalizationConfigurationPluginServerInitCallback(); -void MatterLowPowerPluginServerInitCallback(); -void MatterMediaInputPluginServerInitCallback(); -void MatterMediaPlaybackPluginServerInitCallback(); -void MatterModeSelectPluginServerInitCallback(); -void MatterNetworkCommissioningPluginServerInitCallback(); -void MatterOccupancySensingPluginServerInitCallback(); -void MatterOnOffPluginServerInitCallback(); -void MatterOnOffSwitchConfigurationPluginServerInitCallback(); -void MatterOperationalCredentialsPluginServerInitCallback(); -void MatterOtaSoftwareUpdateRequestorPluginServerInitCallback(); -void MatterPowerSourcePluginServerInitCallback(); -void MatterPowerSourceConfigurationPluginServerInitCallback(); -void MatterPressureMeasurementPluginServerInitCallback(); -void MatterPumpConfigurationAndControlPluginServerInitCallback(); -void MatterRelativeHumidityMeasurementPluginServerInitCallback(); -void MatterScenesPluginServerInitCallback(); -void MatterSoftwareDiagnosticsPluginServerInitCallback(); -void MatterSwitchPluginServerInitCallback(); -void MatterTargetNavigatorPluginServerInitCallback(); -void MatterTemperatureMeasurementPluginServerInitCallback(); -void MatterThermostatPluginServerInitCallback(); -void MatterThermostatUserInterfaceConfigurationPluginServerInitCallback(); -void MatterThreadNetworkDiagnosticsPluginServerInitCallback(); -void MatterTimeFormatLocalizationPluginServerInitCallback(); -void MatterUnitLocalizationPluginServerInitCallback(); -void MatterUnitTestingPluginServerInitCallback(); -void MatterUserLabelPluginServerInitCallback(); -void MatterWakeOnLanPluginServerInitCallback(); -void MatterWiFiNetworkDiagnosticsPluginServerInitCallback(); -void MatterWindowCoveringPluginServerInitCallback(); - -#define MATTER_PLUGINS_INIT \ - MatterAccessControlPluginServerInitCallback(); \ - MatterAccountLoginPluginServerInitCallback(); \ - MatterActionsPluginServerInitCallback(); \ - MatterAdministratorCommissioningPluginServerInitCallback(); \ - MatterApplicationBasicPluginServerInitCallback(); \ - MatterApplicationLauncherPluginServerInitCallback(); \ - MatterAudioOutputPluginServerInitCallback(); \ - MatterBarrierControlPluginServerInitCallback(); \ - MatterBasicInformationPluginServerInitCallback(); \ - MatterBinaryInputBasicPluginServerInitCallback(); \ - MatterBindingPluginServerInitCallback(); \ - MatterBooleanStatePluginServerInitCallback(); \ - MatterChannelPluginServerInitCallback(); \ - MatterColorControlPluginServerInitCallback(); \ - MatterContentLauncherPluginServerInitCallback(); \ - MatterDescriptorPluginServerInitCallback(); \ - MatterDiagnosticLogsPluginServerInitCallback(); \ - MatterDoorLockPluginServerInitCallback(); \ - MatterElectricalMeasurementPluginServerInitCallback(); \ - MatterEthernetNetworkDiagnosticsPluginServerInitCallback(); \ - MatterFanControlPluginServerInitCallback(); \ - MatterFaultInjectionPluginServerInitCallback(); \ - MatterFixedLabelPluginServerInitCallback(); \ - MatterFlowMeasurementPluginServerInitCallback(); \ - MatterGeneralCommissioningPluginServerInitCallback(); \ - MatterGeneralDiagnosticsPluginServerInitCallback(); \ - MatterGroupKeyManagementPluginServerInitCallback(); \ - MatterGroupsPluginServerInitCallback(); \ - MatterIdentifyPluginServerInitCallback(); \ - MatterIlluminanceMeasurementPluginServerInitCallback(); \ - MatterKeypadInputPluginServerInitCallback(); \ - MatterLevelControlPluginServerInitCallback(); \ - MatterLocalizationConfigurationPluginServerInitCallback(); \ - MatterLowPowerPluginServerInitCallback(); \ - MatterMediaInputPluginServerInitCallback(); \ - MatterMediaPlaybackPluginServerInitCallback(); \ - MatterModeSelectPluginServerInitCallback(); \ - MatterNetworkCommissioningPluginServerInitCallback(); \ - MatterOccupancySensingPluginServerInitCallback(); \ - MatterOnOffPluginServerInitCallback(); \ - MatterOnOffSwitchConfigurationPluginServerInitCallback(); \ - MatterOperationalCredentialsPluginServerInitCallback(); \ - MatterOtaSoftwareUpdateRequestorPluginServerInitCallback(); \ - MatterPowerSourcePluginServerInitCallback(); \ - MatterPowerSourceConfigurationPluginServerInitCallback(); \ - MatterPressureMeasurementPluginServerInitCallback(); \ - MatterPumpConfigurationAndControlPluginServerInitCallback(); \ - MatterRelativeHumidityMeasurementPluginServerInitCallback(); \ - MatterScenesPluginServerInitCallback(); \ - MatterSoftwareDiagnosticsPluginServerInitCallback(); \ - MatterSwitchPluginServerInitCallback(); \ - MatterTargetNavigatorPluginServerInitCallback(); \ - MatterTemperatureMeasurementPluginServerInitCallback(); \ - MatterThermostatPluginServerInitCallback(); \ - MatterThermostatUserInterfaceConfigurationPluginServerInitCallback(); \ - MatterThreadNetworkDiagnosticsPluginServerInitCallback(); \ - MatterTimeFormatLocalizationPluginServerInitCallback(); \ - MatterUnitLocalizationPluginServerInitCallback(); \ - MatterUnitTestingPluginServerInitCallback(); \ - MatterUserLabelPluginServerInitCallback(); \ - MatterWakeOnLanPluginServerInitCallback(); \ - MatterWiFiNetworkDiagnosticsPluginServerInitCallback(); \ - MatterWindowCoveringPluginServerInitCallback(); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp deleted file mode 100644 index 3ca10516cd3a58..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp +++ /dev/null @@ -1,529 +0,0 @@ -#include -#include -#include -#include - -using namespace chip; - -// Cluster Init Functions -void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) -{ - switch (clusterId) - { - case app::Clusters::AccessControl::Id: - emberAfAccessControlClusterInitCallback(endpoint); - break; - case app::Clusters::AccountLogin::Id: - emberAfAccountLoginClusterInitCallback(endpoint); - break; - case app::Clusters::Actions::Id: - emberAfActionsClusterInitCallback(endpoint); - break; - case app::Clusters::AdministratorCommissioning::Id: - emberAfAdministratorCommissioningClusterInitCallback(endpoint); - break; - case app::Clusters::ApplicationBasic::Id: - emberAfApplicationBasicClusterInitCallback(endpoint); - break; - case app::Clusters::ApplicationLauncher::Id: - emberAfApplicationLauncherClusterInitCallback(endpoint); - break; - case app::Clusters::AudioOutput::Id: - emberAfAudioOutputClusterInitCallback(endpoint); - break; - case app::Clusters::BarrierControl::Id: - emberAfBarrierControlClusterInitCallback(endpoint); - break; - case app::Clusters::BasicInformation::Id: - emberAfBasicInformationClusterInitCallback(endpoint); - break; - case app::Clusters::BinaryInputBasic::Id: - emberAfBinaryInputBasicClusterInitCallback(endpoint); - break; - case app::Clusters::Binding::Id: - emberAfBindingClusterInitCallback(endpoint); - break; - case app::Clusters::BooleanState::Id: - emberAfBooleanStateClusterInitCallback(endpoint); - break; - case app::Clusters::Channel::Id: - emberAfChannelClusterInitCallback(endpoint); - break; - case app::Clusters::ColorControl::Id: - emberAfColorControlClusterInitCallback(endpoint); - break; - case app::Clusters::ContentLauncher::Id: - emberAfContentLauncherClusterInitCallback(endpoint); - break; - case app::Clusters::Descriptor::Id: - emberAfDescriptorClusterInitCallback(endpoint); - break; - case app::Clusters::DiagnosticLogs::Id: - emberAfDiagnosticLogsClusterInitCallback(endpoint); - break; - case app::Clusters::DoorLock::Id: - emberAfDoorLockClusterInitCallback(endpoint); - break; - case app::Clusters::ElectricalMeasurement::Id: - emberAfElectricalMeasurementClusterInitCallback(endpoint); - break; - case app::Clusters::EthernetNetworkDiagnostics::Id: - emberAfEthernetNetworkDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::FanControl::Id: - emberAfFanControlClusterInitCallback(endpoint); - break; - case app::Clusters::FaultInjection::Id: - emberAfFaultInjectionClusterInitCallback(endpoint); - break; - case app::Clusters::FixedLabel::Id: - emberAfFixedLabelClusterInitCallback(endpoint); - break; - case app::Clusters::FlowMeasurement::Id: - emberAfFlowMeasurementClusterInitCallback(endpoint); - break; - case app::Clusters::GeneralCommissioning::Id: - emberAfGeneralCommissioningClusterInitCallback(endpoint); - break; - case app::Clusters::GeneralDiagnostics::Id: - emberAfGeneralDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::GroupKeyManagement::Id: - emberAfGroupKeyManagementClusterInitCallback(endpoint); - break; - case app::Clusters::Groups::Id: - emberAfGroupsClusterInitCallback(endpoint); - break; - case app::Clusters::Identify::Id: - emberAfIdentifyClusterInitCallback(endpoint); - break; - case app::Clusters::IlluminanceMeasurement::Id: - emberAfIlluminanceMeasurementClusterInitCallback(endpoint); - break; - case app::Clusters::KeypadInput::Id: - emberAfKeypadInputClusterInitCallback(endpoint); - break; - case app::Clusters::LevelControl::Id: - emberAfLevelControlClusterInitCallback(endpoint); - break; - case app::Clusters::LocalizationConfiguration::Id: - emberAfLocalizationConfigurationClusterInitCallback(endpoint); - break; - case app::Clusters::LowPower::Id: - emberAfLowPowerClusterInitCallback(endpoint); - break; - case app::Clusters::MediaInput::Id: - emberAfMediaInputClusterInitCallback(endpoint); - break; - case app::Clusters::MediaPlayback::Id: - emberAfMediaPlaybackClusterInitCallback(endpoint); - break; - case app::Clusters::ModeSelect::Id: - emberAfModeSelectClusterInitCallback(endpoint); - break; - case app::Clusters::NetworkCommissioning::Id: - emberAfNetworkCommissioningClusterInitCallback(endpoint); - break; - case app::Clusters::OccupancySensing::Id: - emberAfOccupancySensingClusterInitCallback(endpoint); - break; - case app::Clusters::OnOff::Id: - emberAfOnOffClusterInitCallback(endpoint); - break; - case app::Clusters::OnOffSwitchConfiguration::Id: - emberAfOnOffSwitchConfigurationClusterInitCallback(endpoint); - break; - case app::Clusters::OperationalCredentials::Id: - emberAfOperationalCredentialsClusterInitCallback(endpoint); - break; - case app::Clusters::OtaSoftwareUpdateProvider::Id: - emberAfOtaSoftwareUpdateProviderClusterInitCallback(endpoint); - break; - case app::Clusters::OtaSoftwareUpdateRequestor::Id: - emberAfOtaSoftwareUpdateRequestorClusterInitCallback(endpoint); - break; - case app::Clusters::PowerSource::Id: - emberAfPowerSourceClusterInitCallback(endpoint); - break; - case app::Clusters::PowerSourceConfiguration::Id: - emberAfPowerSourceConfigurationClusterInitCallback(endpoint); - break; - case app::Clusters::PressureMeasurement::Id: - emberAfPressureMeasurementClusterInitCallback(endpoint); - break; - case app::Clusters::PumpConfigurationAndControl::Id: - emberAfPumpConfigurationAndControlClusterInitCallback(endpoint); - break; - case app::Clusters::RelativeHumidityMeasurement::Id: - emberAfRelativeHumidityMeasurementClusterInitCallback(endpoint); - break; - case app::Clusters::Scenes::Id: - emberAfScenesClusterInitCallback(endpoint); - break; - case app::Clusters::SoftwareDiagnostics::Id: - emberAfSoftwareDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::Switch::Id: - emberAfSwitchClusterInitCallback(endpoint); - break; - case app::Clusters::TargetNavigator::Id: - emberAfTargetNavigatorClusterInitCallback(endpoint); - break; - case app::Clusters::TemperatureMeasurement::Id: - emberAfTemperatureMeasurementClusterInitCallback(endpoint); - break; - case app::Clusters::Thermostat::Id: - emberAfThermostatClusterInitCallback(endpoint); - break; - case app::Clusters::ThermostatUserInterfaceConfiguration::Id: - emberAfThermostatUserInterfaceConfigurationClusterInitCallback(endpoint); - break; - case app::Clusters::ThreadNetworkDiagnostics::Id: - emberAfThreadNetworkDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::TimeFormatLocalization::Id: - emberAfTimeFormatLocalizationClusterInitCallback(endpoint); - break; - case app::Clusters::UnitLocalization::Id: - emberAfUnitLocalizationClusterInitCallback(endpoint); - break; - case app::Clusters::UnitTesting::Id: - emberAfUnitTestingClusterInitCallback(endpoint); - break; - case app::Clusters::UserLabel::Id: - emberAfUserLabelClusterInitCallback(endpoint); - break; - case app::Clusters::WakeOnLan::Id: - emberAfWakeOnLanClusterInitCallback(endpoint); - break; - case app::Clusters::WiFiNetworkDiagnostics::Id: - emberAfWiFiNetworkDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::WindowCovering::Id: - emberAfWindowCoveringClusterInitCallback(endpoint); - break; - default: - // Unrecognized cluster ID - break; - } -} -void __attribute__((weak)) emberAfAccessControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfAccountLoginClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfActionsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfAdministratorCommissioningClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfApplicationBasicClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfApplicationLauncherClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfAudioOutputClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfBarrierControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfBasicInformationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfBinaryInputBasicClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfBindingClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfBooleanStateClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfChannelClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfColorControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfContentLauncherClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfDescriptorClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfDiagnosticLogsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfDoorLockClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfElectricalMeasurementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfEthernetNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfFanControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfFaultInjectionClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfFixedLabelClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfFlowMeasurementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGeneralCommissioningClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGeneralDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGroupKeyManagementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGroupsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfIdentifyClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfIlluminanceMeasurementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfKeypadInputClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfLevelControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfLocalizationConfigurationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfLowPowerClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfMediaInputClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfMediaPlaybackClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfModeSelectClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfNetworkCommissioningClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOccupancySensingClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOnOffClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOnOffSwitchConfigurationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOperationalCredentialsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOtaSoftwareUpdateProviderClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOtaSoftwareUpdateRequestorClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfPowerSourceClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfPowerSourceConfigurationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfPressureMeasurementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfPumpConfigurationAndControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfRelativeHumidityMeasurementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfScenesClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfSoftwareDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfSwitchClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfTargetNavigatorClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfTemperatureMeasurementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfThermostatClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfThermostatUserInterfaceConfigurationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfTimeFormatLocalizationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfUnitLocalizationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfUnitTestingClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfUserLabelClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfWakeOnLanClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h deleted file mode 100644 index de27155a6c4896..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once -void MatterAccessControlPluginServerInitCallback(); -void MatterAdministratorCommissioningPluginServerInitCallback(); -void MatterBasicInformationPluginServerInitCallback(); -void MatterColorControlPluginServerInitCallback(); -void MatterDescriptorPluginServerInitCallback(); -void MatterDiagnosticLogsPluginServerInitCallback(); -void MatterEthernetNetworkDiagnosticsPluginServerInitCallback(); -void MatterFixedLabelPluginServerInitCallback(); -void MatterGeneralCommissioningPluginServerInitCallback(); -void MatterGeneralDiagnosticsPluginServerInitCallback(); -void MatterGroupKeyManagementPluginServerInitCallback(); -void MatterGroupsPluginServerInitCallback(); -void MatterIdentifyPluginServerInitCallback(); -void MatterLevelControlPluginServerInitCallback(); -void MatterLocalizationConfigurationPluginServerInitCallback(); -void MatterNetworkCommissioningPluginServerInitCallback(); -void MatterOccupancySensingPluginServerInitCallback(); -void MatterOnOffPluginServerInitCallback(); -void MatterOperationalCredentialsPluginServerInitCallback(); -void MatterOtaSoftwareUpdateRequestorPluginServerInitCallback(); -void MatterSoftwareDiagnosticsPluginServerInitCallback(); -void MatterSwitchPluginServerInitCallback(); -void MatterThreadNetworkDiagnosticsPluginServerInitCallback(); -void MatterTimeFormatLocalizationPluginServerInitCallback(); -void MatterUserLabelPluginServerInitCallback(); -void MatterWiFiNetworkDiagnosticsPluginServerInitCallback(); - -#define MATTER_PLUGINS_INIT \ - MatterAccessControlPluginServerInitCallback(); \ - MatterAdministratorCommissioningPluginServerInitCallback(); \ - MatterBasicInformationPluginServerInitCallback(); \ - MatterColorControlPluginServerInitCallback(); \ - MatterDescriptorPluginServerInitCallback(); \ - MatterDiagnosticLogsPluginServerInitCallback(); \ - MatterEthernetNetworkDiagnosticsPluginServerInitCallback(); \ - MatterFixedLabelPluginServerInitCallback(); \ - MatterGeneralCommissioningPluginServerInitCallback(); \ - MatterGeneralDiagnosticsPluginServerInitCallback(); \ - MatterGroupKeyManagementPluginServerInitCallback(); \ - MatterGroupsPluginServerInitCallback(); \ - MatterIdentifyPluginServerInitCallback(); \ - MatterLevelControlPluginServerInitCallback(); \ - MatterLocalizationConfigurationPluginServerInitCallback(); \ - MatterNetworkCommissioningPluginServerInitCallback(); \ - MatterOccupancySensingPluginServerInitCallback(); \ - MatterOnOffPluginServerInitCallback(); \ - MatterOperationalCredentialsPluginServerInitCallback(); \ - MatterOtaSoftwareUpdateRequestorPluginServerInitCallback(); \ - MatterSoftwareDiagnosticsPluginServerInitCallback(); \ - MatterSwitchPluginServerInitCallback(); \ - MatterThreadNetworkDiagnosticsPluginServerInitCallback(); \ - MatterTimeFormatLocalizationPluginServerInitCallback(); \ - MatterUserLabelPluginServerInitCallback(); \ - MatterWiFiNetworkDiagnosticsPluginServerInitCallback(); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp deleted file mode 100644 index edaf1f292fc935..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp +++ /dev/null @@ -1,233 +0,0 @@ -#include -#include -#include -#include - -using namespace chip; - -// Cluster Init Functions -void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) -{ - switch (clusterId) - { - case app::Clusters::AccessControl::Id: - emberAfAccessControlClusterInitCallback(endpoint); - break; - case app::Clusters::AdministratorCommissioning::Id: - emberAfAdministratorCommissioningClusterInitCallback(endpoint); - break; - case app::Clusters::BasicInformation::Id: - emberAfBasicInformationClusterInitCallback(endpoint); - break; - case app::Clusters::ColorControl::Id: - emberAfColorControlClusterInitCallback(endpoint); - break; - case app::Clusters::Descriptor::Id: - emberAfDescriptorClusterInitCallback(endpoint); - break; - case app::Clusters::DiagnosticLogs::Id: - emberAfDiagnosticLogsClusterInitCallback(endpoint); - break; - case app::Clusters::EthernetNetworkDiagnostics::Id: - emberAfEthernetNetworkDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::FixedLabel::Id: - emberAfFixedLabelClusterInitCallback(endpoint); - break; - case app::Clusters::GeneralCommissioning::Id: - emberAfGeneralCommissioningClusterInitCallback(endpoint); - break; - case app::Clusters::GeneralDiagnostics::Id: - emberAfGeneralDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::GroupKeyManagement::Id: - emberAfGroupKeyManagementClusterInitCallback(endpoint); - break; - case app::Clusters::Groups::Id: - emberAfGroupsClusterInitCallback(endpoint); - break; - case app::Clusters::Identify::Id: - emberAfIdentifyClusterInitCallback(endpoint); - break; - case app::Clusters::LevelControl::Id: - emberAfLevelControlClusterInitCallback(endpoint); - break; - case app::Clusters::LocalizationConfiguration::Id: - emberAfLocalizationConfigurationClusterInitCallback(endpoint); - break; - case app::Clusters::NetworkCommissioning::Id: - emberAfNetworkCommissioningClusterInitCallback(endpoint); - break; - case app::Clusters::OccupancySensing::Id: - emberAfOccupancySensingClusterInitCallback(endpoint); - break; - case app::Clusters::OnOff::Id: - emberAfOnOffClusterInitCallback(endpoint); - break; - case app::Clusters::OperationalCredentials::Id: - emberAfOperationalCredentialsClusterInitCallback(endpoint); - break; - case app::Clusters::OtaSoftwareUpdateProvider::Id: - emberAfOtaSoftwareUpdateProviderClusterInitCallback(endpoint); - break; - case app::Clusters::OtaSoftwareUpdateRequestor::Id: - emberAfOtaSoftwareUpdateRequestorClusterInitCallback(endpoint); - break; - case app::Clusters::SoftwareDiagnostics::Id: - emberAfSoftwareDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::Switch::Id: - emberAfSwitchClusterInitCallback(endpoint); - break; - case app::Clusters::ThreadNetworkDiagnostics::Id: - emberAfThreadNetworkDiagnosticsClusterInitCallback(endpoint); - break; - case app::Clusters::TimeFormatLocalization::Id: - emberAfTimeFormatLocalizationClusterInitCallback(endpoint); - break; - case app::Clusters::UserLabel::Id: - emberAfUserLabelClusterInitCallback(endpoint); - break; - case app::Clusters::WiFiNetworkDiagnostics::Id: - emberAfWiFiNetworkDiagnosticsClusterInitCallback(endpoint); - break; - default: - // Unrecognized cluster ID - break; - } -} -void __attribute__((weak)) emberAfAccessControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfAdministratorCommissioningClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfBasicInformationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfColorControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfDescriptorClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfDiagnosticLogsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfEthernetNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfFixedLabelClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGeneralCommissioningClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGeneralDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGroupKeyManagementClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfGroupsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfIdentifyClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfLevelControlClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfLocalizationConfigurationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfNetworkCommissioningClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOccupancySensingClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOnOffClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOperationalCredentialsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOtaSoftwareUpdateProviderClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfOtaSoftwareUpdateRequestorClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfSoftwareDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfSwitchClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfTimeFormatLocalizationClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfUserLabelClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPCallbackTypes.h b/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPCallbackTypes.h deleted file mode 100644 index 3310f9d64f5321..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPCallbackTypes.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -typedef void (*CHIPDefaultSuccessCallbackType)(void *, const chip::app::DataModel::NullObjectType &); -typedef void (*CHIPDefaultWriteSuccessCallbackType)(void *); -typedef void (*CHIPDefaultFailureCallbackType)(void *, CHIP_ERROR); - - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPReadReadCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPReadReadCallbacks.h deleted file mode 100644 index 60383ba31b550d..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/CHIPReadReadCallbacks.h +++ /dev/null @@ -1,341 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include - -class CHIPBooleanAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPBooleanAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPBooleanAttributeCallback(); - - static void maybeDestroy(CHIPBooleanAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, bool value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPCharStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPCharStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPCharStringAttributeCallback(); - - static void maybeDestroy(CHIPCharStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::CharSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPDoubleAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDoubleAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDoubleAttributeCallback(); - - static void maybeDestroy(CHIPDoubleAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, double value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPFloatAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPFloatAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPFloatAttributeCallback(); - - static void maybeDestroy(CHIPFloatAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, float value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8sAttributeCallback(); - - static void maybeDestroy(CHIPInt8sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8uAttributeCallback(); - - static void maybeDestroy(CHIPInt8uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16sAttributeCallback(); - - static void maybeDestroy(CHIPInt16sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16uAttributeCallback(); - - static void maybeDestroy(CHIPInt16uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32sAttributeCallback(); - - static void maybeDestroy(CHIPInt32sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32uAttributeCallback(); - - static void maybeDestroy(CHIPInt32uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64sAttributeCallback(); - - static void maybeDestroy(CHIPInt64sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64uAttributeCallback(); - - static void maybeDestroy(CHIPInt64uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPOctetStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPOctetStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPOctetStringAttributeCallback(); - - static void maybeDestroy(CHIPOctetStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::ByteSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index b599b46b723e5b..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, MyClusterCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, MyClusterCluster, - foo)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback,jobject argument,jobject timedInvokeTimeoutMs) -{ - chip::DeviceLayer::StackLock lock; - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster; - - ListFreer listFreer; - chip::app::Clusters::MyCluster::Commands::Foo::Type request; - - std::vector> cleanupByteArrays; - std::vector> cleanupStrings;{ - jobject optionalValue_0 = nullptr; - chip::JniReferences::GetInstance().GetOptionalValue(argument, optionalValue_0); - if (optionalValue_0) { - auto & definedValue_0 = request.argument.Emplace(); - cleanupByteArrays.push_back(chip::Platform::MakeUnique(env, static_cast(optionalValue_0))); - definedValue_0 = cleanupByteArrays.back()->byteSpan(); - } - } - - - std::unique_ptr onSuccess( - Platform::New(callback), Platform::Delete); - std::unique_ptr onFailure(Platform::New(callback), Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native callback", CHIP_ERROR_NO_MEMORY)); - VerifyOrReturn(onFailure.get() != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native callback", CHIP_ERROR_NO_MEMORY)); - - cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error getting native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - if (timedInvokeTimeoutMs == nullptr) { - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall); - } else { - err = cppCluster->InvokeCommand(request, onSuccess->mContext, successFn->mCall, failureFn->mCall, chip::JniReferences::GetInstance().IntegerToPrimitive(timedInvokeTimeoutMs)); - } - VerifyOrReturn(err == CHIP_NO_ERROR, AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error invoking command", CHIP_ERROR_INCORRECT_STATE)); - - onSuccess.release(); - onFailure.release(); -} - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp deleted file mode 100644 index 30a766dd4563aa..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp +++ /dev/null @@ -1,14 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/first_cluster.proto b/scripts/py_matter_idl/matter_idl/tests/outputs/proto/first_cluster.proto deleted file mode 100644 index 479a1688fb50aa..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/first_cluster.proto +++ /dev/null @@ -1,29 +0,0 @@ - -/// AUTO-GENERATED with matter_idl. - -syntax = "proto3"; - -package com.matter.example.proto; - -option java_multiple_files = true; - -message FirstCluster { - // option (message_type) = MATTER_TRAIT; - - enum ClusterId { - CLUSTER_ID_UNSUPPORTED = 0; - CLUSTER_ID = 1; - } - - // Attributes - /** int16u Type: 6 IsList: 0 FieldId: 1 */ - int16u some_integer = 3145729; - /* - [(attribute) = { - is_writable : true, - is_subscribable: true, - }]; - */ - - -} // FirstCluster diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/ota_software_update_provider_cluster.proto b/scripts/py_matter_idl/matter_idl/tests/outputs/proto/ota_software_update_provider_cluster.proto deleted file mode 100644 index 15bfdb9abe5c4c..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/ota_software_update_provider_cluster.proto +++ /dev/null @@ -1,107 +0,0 @@ - -/// AUTO-GENERATED with matter_idl. - -syntax = "proto3"; - -package com.matter.example.proto; - -option java_multiple_files = true; - -message OtaSoftwareUpdateProviderCluster { - // option (message_type) = MATTER_TRAIT; - - enum ClusterId { - CLUSTER_ID_UNSUPPORTED = 0; - CLUSTER_ID = 41; - } - - // Enums - enum OTAApplyUpdateAction { - OTAAUA_PROCEED = 0; - OTAAUA_AWAIT_NEXT_ACTION = 1; - OTAAUA_DISCONTINUE = 2; - } - - enum OTADownloadProtocol { - OTADP_BDXSYNCHRONOUS = 0; - OTADP_BDXASYNCHRONOUS = 1; - OTADP_HTTPS = 2; - OTADP_VENDOR_SPECIFIC = 3; - } - - enum OTAQueryStatus { - OTAQS_UPDATE_AVAILABLE = 0; - OTAQS_BUSY = 1; - OTAQS_NOT_AVAILABLE = 2; - OTAQS_DOWNLOAD_PROTOCOL_NOT_SUPPORTED = 3; - } - - - // Structs - - // Attributes - /** int16u Type: 6 IsList: 0 FieldId: 65533 */ - int16u cluster_revision = 3211261; - /* - [(attribute) = { - is_subscribable: true, - }]; - */ - - - - // Commands - message QueryImageCommand { - // option (message_type) = MATTER_COMMAND; - - /** vendor_id Type: 1 IsList: 0 FieldId: 0 */ - uint32 vendor_id = 524288; - /** INT16U Type: 6 IsList: 0 FieldId: 1 */ - INT16U product_id = 3145729; - /** INT32U Type: 6 IsList: 0 FieldId: 2 */ - INT32U software_version = 3145730; - /** OTADownloadProtocol Type: 6 IsList: 1 FieldId: 3 */ - repeated OTADownloadProtocol protocols_supported = 3145731; - /** INT16U Type: 6 IsList: 0 FieldId: 4 */ - optional INT16U hardware_version = 3145732; - /** CHAR_STRING Type: 4 IsList: 0 FieldId: 5 */ - optional string location = 2097157; - /** BOOLEAN Type: 3 IsList: 0 FieldId: 6 */ - optional bool requestor_can_consent = 1572870; - /** OCTET_STRING Type: 5 IsList: 0 FieldId: 7 */ - optional bytes metadata_for_provider = 2621447; - } - - message QueryImageCommandResponse { - // option (message_type) = MATTER_COMMAND_RESPONSE; - - } - - message ApplyUpdateRequestCommand { - // option (message_type) = MATTER_COMMAND; - - /** OCTET_STRING Type: 5 IsList: 0 FieldId: 0 */ - bytes update_token = 2621440; - /** INT32U Type: 6 IsList: 0 FieldId: 1 */ - INT32U new_version = 3145729; - } - - message ApplyUpdateRequestCommandResponse { - // option (message_type) = MATTER_COMMAND_RESPONSE; - - /** OTAApplyUpdateAction Type: 6 IsList: 0 FieldId: 0 */ - OTAApplyUpdateAction action = 3145728; - /** INT32U Type: 6 IsList: 0 FieldId: 1 */ - INT32U delayed_action_time = 3145729; - } - - message NotifyUpdateAppliedCommand { - // option (message_type) = MATTER_COMMAND; - - /** OCTET_STRING Type: 5 IsList: 0 FieldId: 0 */ - bytes update_token = 2621440; - /** INT32U Type: 6 IsList: 0 FieldId: 1 */ - INT32U software_version = 3145729; - } - -} // OtaSoftwareUpdateProviderCluster diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/second_cluster.proto b/scripts/py_matter_idl/matter_idl/tests/outputs/proto/second_cluster.proto deleted file mode 100644 index e0d99270b10304..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/second_cluster.proto +++ /dev/null @@ -1,54 +0,0 @@ - -/// AUTO-GENERATED with matter_idl. - -syntax = "proto3"; - -package com.matter.example.proto; - -option java_multiple_files = true; - -message SecondCluster { - // option (message_type) = MATTER_TRAIT; - - enum ClusterId { - CLUSTER_ID_UNSUPPORTED = 0; - CLUSTER_ID = 2; - } - - // Structs - message FabricDescriptorStruct { - /** octet_string Type: 5 IsList: 0 FieldId: 1 */ - bytes root_public_key = 2621441; - /** vendor_id Type: 1 IsList: 0 FieldId: 2 */ - uint32 vendor_id = 524290; - /** fabric_id Type: 1 IsList: 0 FieldId: 3 */ - uint64 fabric_id = 524291; - /** node_id Type: 1 IsList: 0 FieldId: 4 */ - uint64 node_id = 524292; - /** char_string Type: 4 IsList: 0 FieldId: 5 */ - string label = 2097157; - /** fabric_idx Type: 1 IsList: 0 FieldId: 254 */ - uint32 fabric_index = 524542; - } - - - // Attributes - /** FabricDescriptorStruct Type: 6 IsList: 1 FieldId: 0 */ - FabricDescriptorStruct fabrics = 3145728; - /* - [(attribute) = { - is_subscribable: true, - }]; - */ - - - /** octet_string Type: 5 IsList: 0 FieldId: 123 */ - bytes some_bytes = 2621563; - /* - [(attribute) = { - is_subscribable: true, - }]; - */ - - -} // SecondCluster diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/third_cluster.proto b/scripts/py_matter_idl/matter_idl/tests/outputs/proto/third_cluster.proto deleted file mode 100644 index 16c8685257692e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/proto/third_cluster.proto +++ /dev/null @@ -1,54 +0,0 @@ - -/// AUTO-GENERATED with matter_idl. - -syntax = "proto3"; - -package com.matter.example.proto; - -option java_multiple_files = true; - -message ThirdCluster { - // option (message_type) = MATTER_TRAIT; - - enum ClusterId { - CLUSTER_ID_UNSUPPORTED = 0; - CLUSTER_ID = 3; - } - - // Enums - enum MyEnum { - ME_UNKNOWN = 0; - ME_KNOWN = 100; - } - - - // Bitmaps - enum LevelControlOptions { - LCO_UNSUPPORTED = 0; - LCO_EXECUTE_IF_OFF = 1; - LCO_COUPLE_COLOR_TEMP_TO_LEVEL = 2; - } - - - // Attributes - /** MyEnum Type: 6 IsList: 0 FieldId: 10 */ - MyEnum some_enum = 3145738; - /* - [(attribute) = { - is_writable : true, - is_subscribable: true, - }]; - */ - - - /** LevelControlOptions Type: 1 IsList: 0 FieldId: 20 */ - uint32 options = 524308; - /* - [(attribute) = { - is_writable : true, - is_subscribable: true, - }]; - */ - - -} // ThirdCluster diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h deleted file mode 100644 index 620b4159b1350c..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once -void MatterThirdPluginServerInitCallback(); - -#define MATTER_PLUGINS_INIT \ - MatterThirdPluginServerInitCallback(); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp deleted file mode 100644 index d603013606d835..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include -#include -#include -#include - -using namespace chip; - -// Cluster Init Functions -void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) -{ - switch (clusterId) - { - case app::Clusters::First::Id: - emberAfFirstClusterInitCallback(endpoint); - break; - case app::Clusters::Second::Id: - emberAfSecondClusterInitCallback(endpoint); - break; - case app::Clusters::Third::Id: - emberAfThirdClusterInitCallback(endpoint); - break; - default: - // Unrecognized cluster ID - break; - } -} -void __attribute__((weak)) emberAfFirstClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfSecondClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} -void __attribute__((weak)) emberAfThirdClusterInitCallback(EndpointId endpoint) -{ - // To prevent warning - (void) endpoint; -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterIDMapping.java b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterIDMapping.java deleted file mode 100644 index 22493a3a4ace9b..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterIDMapping.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller; - -public class ClusterIDMapping { - public interface BaseCluster { - long getID(); - String getAttributeName(long id) throws NoSuchFieldError; - String getEventName(long id) throws NoSuchFieldError; - String getCommandName(long id) throws NoSuchFieldError; - long getAttributeID(String name) throws IllegalArgumentException; - long getEventID(String name) throws IllegalArgumentException; - long getCommandID(String name) throws IllegalArgumentException; - } - - public static BaseCluster getCluster(long clusterId) { - if (clusterId == First.ID) { - return new First(); - } - if (clusterId == Second.ID) { - return new Second(); - } - if (clusterId == Third.ID) { - return new Third(); - }return null; - } - public static class First implements BaseCluster { - public static final long ID = 1L; - public long getID() { - return ID; - } - - public enum Attribute { - SomeInteger(1L),; - private final long id; - Attribute(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Attribute value(long id) throws NoSuchFieldError { - for (Attribute attribute : Attribute.values()) { - if (attribute.getID() == id) { - return attribute; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Event {; - private final long id; - Event(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Event value(long id) throws NoSuchFieldError { - for (Event event : Event.values()) { - if (event.getID() == id) { - return event; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Command {; - private final long id; - Command(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Command value(long id) throws NoSuchFieldError { - for (Command command : Command.values()) { - if (command.getID() == id) { - return command; - } - } - throw new NoSuchFieldError(); - } - }@Override - public String getAttributeName(long id) throws NoSuchFieldError { - return Attribute.value(id).toString(); - } - - @Override - public String getEventName(long id) throws NoSuchFieldError { - return Event.value(id).toString(); - } - - @Override - public String getCommandName(long id) throws NoSuchFieldError { - return Command.value(id).toString(); - } - - @Override - public long getAttributeID(String name) throws IllegalArgumentException { - return Attribute.valueOf(name).getID(); - } - - @Override - public long getEventID(String name) throws IllegalArgumentException { - return Event.valueOf(name).getID(); - } - - @Override - public long getCommandID(String name) throws IllegalArgumentException { - return Command.valueOf(name).getID(); - } - } - public static class Second implements BaseCluster { - public static final long ID = 2L; - public long getID() { - return ID; - } - - public enum Attribute { - Fabrics(0L), - SomeBytes(123L),; - private final long id; - Attribute(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Attribute value(long id) throws NoSuchFieldError { - for (Attribute attribute : Attribute.values()) { - if (attribute.getID() == id) { - return attribute; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Event {; - private final long id; - Event(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Event value(long id) throws NoSuchFieldError { - for (Event event : Event.values()) { - if (event.getID() == id) { - return event; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Command {; - private final long id; - Command(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Command value(long id) throws NoSuchFieldError { - for (Command command : Command.values()) { - if (command.getID() == id) { - return command; - } - } - throw new NoSuchFieldError(); - } - }@Override - public String getAttributeName(long id) throws NoSuchFieldError { - return Attribute.value(id).toString(); - } - - @Override - public String getEventName(long id) throws NoSuchFieldError { - return Event.value(id).toString(); - } - - @Override - public String getCommandName(long id) throws NoSuchFieldError { - return Command.value(id).toString(); - } - - @Override - public long getAttributeID(String name) throws IllegalArgumentException { - return Attribute.valueOf(name).getID(); - } - - @Override - public long getEventID(String name) throws IllegalArgumentException { - return Event.valueOf(name).getID(); - } - - @Override - public long getCommandID(String name) throws IllegalArgumentException { - return Command.valueOf(name).getID(); - } - } - public static class Third implements BaseCluster { - public static final long ID = 3L; - public long getID() { - return ID; - } - - public enum Attribute { - SomeEnum(10L), - Options(20L),; - private final long id; - Attribute(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Attribute value(long id) throws NoSuchFieldError { - for (Attribute attribute : Attribute.values()) { - if (attribute.getID() == id) { - return attribute; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Event {; - private final long id; - Event(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Event value(long id) throws NoSuchFieldError { - for (Event event : Event.values()) { - if (event.getID() == id) { - return event; - } - } - throw new NoSuchFieldError(); - } - } - - public enum Command {; - private final long id; - Command(long id) { - this.id = id; - } - - public long getID() { - return id; - } - - public static Command value(long id) throws NoSuchFieldError { - for (Command command : Command.values()) { - if (command.getID() == id) { - return command; - } - } - throw new NoSuchFieldError(); - } - }@Override - public String getAttributeName(long id) throws NoSuchFieldError { - return Attribute.value(id).toString(); - } - - @Override - public String getEventName(long id) throws NoSuchFieldError { - return Event.value(id).toString(); - } - - @Override - public String getCommandName(long id) throws NoSuchFieldError { - return Command.value(id).toString(); - } - - @Override - public long getAttributeID(String name) throws IllegalArgumentException { - return Attribute.valueOf(name).getID(); - } - - @Override - public long getEventID(String name) throws IllegalArgumentException { - return Event.valueOf(name).getID(); - } - - @Override - public long getCommandID(String name) throws IllegalArgumentException { - return Command.valueOf(name).getID(); - } - }} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterReadMapping.java b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterReadMapping.java deleted file mode 100644 index a5c86be6fc291d..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterReadMapping.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller; - -import chip.clusterinfo.CommandParameterInfo; -import chip.clusterinfo.InteractionInfo; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -public class ClusterReadMapping { - - - private static Map readFirstInteractionInfo() { - Map result = new LinkedHashMap<>();Map readFirstSomeIntegerCommandParams = new LinkedHashMap(); - InteractionInfo readFirstSomeIntegerAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.FirstCluster) cluster).readSomeIntegerAttribute( - (ChipClusters.IntegerAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedIntegerAttributeCallback(), - readFirstSomeIntegerCommandParams - ); - result.put("readSomeIntegerAttribute", readFirstSomeIntegerAttributeInteractionInfo); - - return result; - } - private static Map readSecondInteractionInfo() { - Map result = new LinkedHashMap<>();Map readSecondFabricsCommandParams = new LinkedHashMap(); - InteractionInfo readSecondFabricsAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.SecondCluster) cluster).readFabricsAttribute( - (ChipClusters.SecondCluster.FabricsAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedSecondClusterFabricsAttributeCallback(), - readSecondFabricsCommandParams - ); - result.put("readFabricsAttribute", readSecondFabricsAttributeInteractionInfo); - Map readSecondSomeBytesCommandParams = new LinkedHashMap(); - InteractionInfo readSecondSomeBytesAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.SecondCluster) cluster).readSomeBytesAttribute( - (ChipClusters.OctetStringAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedOctetStringAttributeCallback(), - readSecondSomeBytesCommandParams - ); - result.put("readSomeBytesAttribute", readSecondSomeBytesAttributeInteractionInfo); - - return result; - } - private static Map readThirdInteractionInfo() { - Map result = new LinkedHashMap<>();Map readThirdSomeEnumCommandParams = new LinkedHashMap(); - InteractionInfo readThirdSomeEnumAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.ThirdCluster) cluster).readSomeEnumAttribute( - (ChipClusters.IntegerAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedIntegerAttributeCallback(), - readThirdSomeEnumCommandParams - ); - result.put("readSomeEnumAttribute", readThirdSomeEnumAttributeInteractionInfo); - Map readThirdOptionsCommandParams = new LinkedHashMap(); - InteractionInfo readThirdOptionsAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.ThirdCluster) cluster).readOptionsAttribute( - (ChipClusters.IntegerAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedIntegerAttributeCallback(), - readThirdOptionsCommandParams - ); - result.put("readOptionsAttribute", readThirdOptionsAttributeInteractionInfo); - - return result; - } - @SuppressWarnings("serial") - public Map> getReadAttributeMap() { - - return new HashMap>(){{ - put("first", readFirstInteractionInfo()); - put("second", readSecondInteractionInfo()); - put("third", readThirdInteractionInfo());}}; - } -} - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterWriteMapping.java b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterWriteMapping.java deleted file mode 100644 index ff07bb30e4ccff..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/ClusterWriteMapping.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller; - -import chip.clusterinfo.CommandParameterInfo; -import chip.clusterinfo.InteractionInfo; -import chip.devicecontroller.ChipClusters.DefaultClusterCallback; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -public class ClusterWriteMapping { - public Map> getWriteAttributeMap() { - Map> writeAttributeMap = new HashMap<>(); - Map writeFirstInteractionInfo = new LinkedHashMap<>(); - Map writeFirstSomeIntegerCommandParams = new LinkedHashMap(); - CommandParameterInfo firstsomeIntegerCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeFirstSomeIntegerCommandParams.put( - "value", - firstsomeIntegerCommandParameterInfo - ); - InteractionInfo writeFirstSomeIntegerAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.FirstCluster) cluster).writeSomeIntegerAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeFirstSomeIntegerCommandParams - ); - writeFirstInteractionInfo.put("writeSomeIntegerAttribute", writeFirstSomeIntegerAttributeInteractionInfo); - writeAttributeMap.put("first", writeFirstInteractionInfo); - Map writeSecondInteractionInfo = new LinkedHashMap<>(); - writeAttributeMap.put("second", writeSecondInteractionInfo); - Map writeThirdInteractionInfo = new LinkedHashMap<>(); - Map writeThirdSomeEnumCommandParams = new LinkedHashMap(); - CommandParameterInfo thirdsomeEnumCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeThirdSomeEnumCommandParams.put( - "value", - thirdsomeEnumCommandParameterInfo - ); - InteractionInfo writeThirdSomeEnumAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.ThirdCluster) cluster).writeSomeEnumAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeThirdSomeEnumCommandParams - ); - writeThirdInteractionInfo.put("writeSomeEnumAttribute", writeThirdSomeEnumAttributeInteractionInfo); - Map writeThirdOptionsCommandParams = new LinkedHashMap(); - CommandParameterInfo thirdoptionsCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeThirdOptionsCommandParams.put( - "value", - thirdoptionsCommandParameterInfo - ); - InteractionInfo writeThirdOptionsAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.ThirdCluster) cluster).writeOptionsAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeThirdOptionsCommandParams - ); - writeThirdInteractionInfo.put("writeOptionsAttribute", writeThirdOptionsAttributeInteractionInfo); - writeAttributeMap.put("third", writeThirdInteractionInfo);return writeAttributeMap; - } -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt deleted file mode 100644 index e86ce5788fd642..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/java/SecondClusterFabricDescriptorStruct.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package chip.devicecontroller.cluster.structs - -import chip.devicecontroller.cluster.* -import chip.tlv.AnonymousTag -import chip.tlv.ContextSpecificTag -import chip.tlv.Tag -import chip.tlv.TlvParsingException -import chip.tlv.TlvReader -import chip.tlv.TlvWriter - -import java.util.Optional - -class SecondClusterFabricDescriptorStruct ( - val rootPublicKey: ByteArray, - val vendorID: Int, - val fabricID: Long, - val nodeID: Long, - val label: String, - val fabricIndex: Int) { - override fun toString(): String = buildString { - append("SecondClusterFabricDescriptorStruct {\n") - append("\trootPublicKey : $rootPublicKey\n") - append("\tvendorID : $vendorID\n") - append("\tfabricID : $fabricID\n") - append("\tnodeID : $nodeID\n") - append("\tlabel : $label\n") - append("\tfabricIndex : $fabricIndex\n") - append("}\n") - } - - fun toTlv(tag: Tag, tlvWriter: TlvWriter) { - tlvWriter.apply { - startStructure(tag) - put(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY), rootPublicKey) - put(ContextSpecificTag(TAG_VENDOR_I_D), vendorID) - put(ContextSpecificTag(TAG_FABRIC_I_D), fabricID) - put(ContextSpecificTag(TAG_NODE_I_D), nodeID) - put(ContextSpecificTag(TAG_LABEL), label) - put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) - endStructure() - } - } - - companion object { - private const val TAG_ROOT_PUBLIC_KEY = 1 - private const val TAG_VENDOR_I_D = 2 - private const val TAG_FABRIC_I_D = 3 - private const val TAG_NODE_I_D = 4 - private const val TAG_LABEL = 5 - private const val TAG_FABRIC_INDEX = 254 - - fun fromTlv(tag: Tag, tlvReader: TlvReader) : SecondClusterFabricDescriptorStruct { - tlvReader.enterStructure(tag) - val rootPublicKey = tlvReader.getByteArray(ContextSpecificTag(TAG_ROOT_PUBLIC_KEY)) - val vendorID = tlvReader.getInt(ContextSpecificTag(TAG_VENDOR_I_D)) - val fabricID = tlvReader.getLong(ContextSpecificTag(TAG_FABRIC_I_D)) - val nodeID = tlvReader.getLong(ContextSpecificTag(TAG_NODE_I_D)) - val label = tlvReader.getString(ContextSpecificTag(TAG_LABEL)) - val fabricIndex = tlvReader.getInt(ContextSpecificTag(TAG_FABRIC_INDEX)) - - tlvReader.exitContainer() - - return SecondClusterFabricDescriptorStruct(rootPublicKey, vendorID, fabricID, nodeID, label, fabricIndex) - } - } -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPCallbackTypes.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPCallbackTypes.h deleted file mode 100644 index d32e68fbfda3ab..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPCallbackTypes.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -typedef void (*CHIPDefaultSuccessCallbackType)(void *, const chip::app::DataModel::NullObjectType &); -typedef void (*CHIPDefaultWriteSuccessCallbackType)(void *); -typedef void (*CHIPDefaultFailureCallbackType)(void *, CHIP_ERROR); - - -typedef void (*CHIPFirstClusterSomeIntegerAttributeCallbackType)(void *, chip::app::Clusters::First::Attributes::SomeInteger::TypeInfo::DecodableArgType); -typedef void (*CHIPSecondClusterFabricsAttributeCallbackType)(void *, const chip::app::Clusters::Second::Attributes::Fabrics::TypeInfo::DecodableType &); -typedef void (*CHIPSecondClusterSomeBytesAttributeCallbackType)(void *, chip::app::Clusters::Second::Attributes::SomeBytes::TypeInfo::DecodableArgType); -typedef void (*CHIPThirdClusterSomeEnumAttributeCallbackType)(void *, chip::app::Clusters::Third::Attributes::SomeEnum::TypeInfo::DecodableArgType); -typedef void (*CHIPThirdClusterOptionsAttributeCallbackType)(void *, chip::app::Clusters::Third::Attributes::Options::TypeInfo::DecodableArgType); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPReadReadCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPReadReadCallbacks.h deleted file mode 100644 index 60603103b8f692..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/CHIPReadReadCallbacks.h +++ /dev/null @@ -1,423 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include - -class CHIPBooleanAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPBooleanAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPBooleanAttributeCallback(); - - static void maybeDestroy(CHIPBooleanAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, bool value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPCharStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPCharStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPCharStringAttributeCallback(); - - static void maybeDestroy(CHIPCharStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::CharSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPDoubleAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDoubleAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDoubleAttributeCallback(); - - static void maybeDestroy(CHIPDoubleAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, double value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPFloatAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPFloatAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPFloatAttributeCallback(); - - static void maybeDestroy(CHIPFloatAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, float value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8sAttributeCallback(); - - static void maybeDestroy(CHIPInt8sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8uAttributeCallback(); - - static void maybeDestroy(CHIPInt8uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16sAttributeCallback(); - - static void maybeDestroy(CHIPInt16sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16uAttributeCallback(); - - static void maybeDestroy(CHIPInt16uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32sAttributeCallback(); - - static void maybeDestroy(CHIPInt32sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32uAttributeCallback(); - - static void maybeDestroy(CHIPInt32uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64sAttributeCallback(); - - static void maybeDestroy(CHIPInt64sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64uAttributeCallback(); - - static void maybeDestroy(CHIPInt64uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPOctetStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPOctetStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPOctetStringAttributeCallback(); - - static void maybeDestroy(CHIPOctetStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::ByteSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - - - - -class CHIPSecondFabricsAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPSecondFabricsAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPSecondFabricsAttributeCallback(); - - static void maybeDestroy(CHIPSecondFabricsAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::app::DataModel::DecodableList & list); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - - -class CHIPThirdSomeEnumAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPThirdSomeEnumAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPThirdSomeEnumAttributeCallback(); - - static void maybeDestroy(CHIPThirdSomeEnumAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, chip::app::Clusters::Third::MyEnum value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - -class CHIPThirdOptionsAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPThirdOptionsAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPThirdOptionsAttributeCallback(); - - static void maybeDestroy(CHIPThirdOptionsAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, chip::BitMask value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index 8a613d404b23ae..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, FirstCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, FirstCluster, subscribeSomeIntegerAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::First::Attributes::SomeInteger::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPInt16uAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp deleted file mode 100644 index 0d09a2adced29f..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp +++ /dev/null @@ -1,38 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME -JNI_METHOD(void, FirstCluster, readSomeIntegerAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::First::Attributes::SomeInteger::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index f123a5407e0170..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, SecondCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, SecondCluster, subscribeFabricsAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::Second::Attributes::Fabrics::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPSecondFabricsAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -}JNI_METHOD(void, SecondCluster, subscribeSomeBytesAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::Second::Attributes::SomeBytes::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPOctetStringAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp deleted file mode 100644 index 714790e2c9d28e..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp +++ /dev/null @@ -1,62 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME -JNI_METHOD(void, SecondCluster, readFabricsAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jboolean isFabricFiltered) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::Second::Attributes::Fabrics::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, isFabricFiltered); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - -JNI_METHOD(void, SecondCluster, readSomeBytesAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::Second::Attributes::SomeBytes::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index c2fb763a0eefb4..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, ThirdCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, ThirdCluster, subscribeSomeEnumAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::Third::Attributes::SomeEnum::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPInt8uAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -}JNI_METHOD(void, ThirdCluster, subscribeOptionsAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::Third::Attributes::Options::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPInt8uAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp deleted file mode 100644 index 5799f7a6f4a3e0..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp +++ /dev/null @@ -1,62 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME -JNI_METHOD(void, ThirdCluster, readSomeEnumAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::Third::Attributes::SomeEnum::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - -JNI_METHOD(void, ThirdCluster, readOptionsAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::Third::Attributes::Options::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/shared/jni/CHIPGlobalCallbacks.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/shared/jni/CHIPGlobalCallbacks.cpp deleted file mode 100644 index e89045213a74c8..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/shared/jni/CHIPGlobalCallbacks.cpp +++ /dev/null @@ -1,603 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -CHIPBooleanAttributeCallback::CHIPBooleanAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPBooleanAttributeCallback::~CHIPBooleanAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPBooleanAttributeCallback::CallbackFn(void * context, bool value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Z)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPCharStringAttributeCallback::CHIPCharStringAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPCharStringAttributeCallback::~CHIPCharStringAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPCharStringAttributeCallback::CallbackFn(void * context, const chip::CharSpan value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(Ljava/lang/String;)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - - chip::UtfString valueStr(env, value); - env->CallVoidMethod(javaCallbackRef, javaMethod, valueStr.jniValue()); -} - -CHIPDoubleAttributeCallback::CHIPDoubleAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPDoubleAttributeCallback::~CHIPDoubleAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPDoubleAttributeCallback::CallbackFn(void * context, double value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(D)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPFloatAttributeCallback::CHIPFloatAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPFloatAttributeCallback::~CHIPFloatAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPFloatAttributeCallback::CallbackFn(void * context, float value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(F)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt8sAttributeCallback::CHIPInt8sAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt8sAttributeCallback::~CHIPInt8sAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt8sAttributeCallback::CallbackFn(void * context, int8_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt8uAttributeCallback::CHIPInt8uAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt8uAttributeCallback::~CHIPInt8uAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt8uAttributeCallback::CallbackFn(void * context, uint8_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt16sAttributeCallback::CHIPInt16sAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt16sAttributeCallback::~CHIPInt16sAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt16sAttributeCallback::CallbackFn(void * context, int16_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt16uAttributeCallback::CHIPInt16uAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt16uAttributeCallback::~CHIPInt16uAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt16uAttributeCallback::CallbackFn(void * context, uint16_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(I)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt32sAttributeCallback::CHIPInt32sAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt32sAttributeCallback::~CHIPInt32sAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt32sAttributeCallback::CallbackFn(void * context, int32_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(J)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt32uAttributeCallback::CHIPInt32uAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt32uAttributeCallback::~CHIPInt32uAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt32uAttributeCallback::CallbackFn(void * context, uint32_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(J)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt64sAttributeCallback::CHIPInt64sAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt64sAttributeCallback::~CHIPInt64sAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt64sAttributeCallback::CallbackFn(void * context, int64_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(J)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPInt64uAttributeCallback::CHIPInt64uAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPInt64uAttributeCallback::~CHIPInt64uAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPInt64uAttributeCallback::CallbackFn(void * context, uint64_t value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "(J)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - env->CallVoidMethod(javaCallbackRef, javaMethod, static_cast(value)); -} - -CHIPOctetStringAttributeCallback::CHIPOctetStringAttributeCallback(jobject javaCallback, bool keepAlive) : - chip::Callback::Callback(CallbackFn, this), keepAlive(keepAlive) -{ - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - return; - } - javaCallbackRef = env->NewGlobalRef(javaCallback); - if (javaCallbackRef == nullptr) { - ChipLogError(Zcl, "Could not create global reference for Java callback"); - } -} - -CHIPOctetStringAttributeCallback::~CHIPOctetStringAttributeCallback() { - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - if (env == nullptr) - { - ChipLogError(Zcl, "Could not delete global reference for Java callback"); - return; - } - env->DeleteGlobalRef(javaCallbackRef); -} - -void CHIPOctetStringAttributeCallback::CallbackFn(void * context, const chip::ByteSpan value) -{ - chip::DeviceLayer::StackUnlock unlock; - CHIP_ERROR err = CHIP_NO_ERROR; - - JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); - VerifyOrReturn(env != nullptr, ChipLogError(Zcl, "Could not get JNI env")); - - std::unique_ptr cppCallback(reinterpret_cast(context), maybeDestroy); - - // It's valid for javaCallbackRef to be nullptr if the Java code passed in a - // null callback. - jobject javaCallbackRef = cppCallback.get()->javaCallbackRef; - VerifyOrReturn(javaCallbackRef != nullptr, ChipLogDetail(Zcl, "Early return from attribute callback since Java callback is null")); - - jmethodID javaMethod; - err = chip::JniReferences::GetInstance().FindMethod(env, javaCallbackRef, "onSuccess", "([B)V", &javaMethod); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Could not find onSuccess method")); - - VerifyOrReturn(chip::CanCastTo(value.size()), ChipLogError(Zcl, "Value too long")); - jbyteArray valueArr = env->NewByteArray(static_cast(value.size())); - env->ExceptionClear(); - env->SetByteArrayRegion(valueArr, 0, static_cast(value.size()), reinterpret_cast(value.data())); - - env->CallVoidMethod(javaCallbackRef, javaMethod, valueArr); -} - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPCallbackTypes.h b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPCallbackTypes.h deleted file mode 100644 index 975e27045e0aba..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPCallbackTypes.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -typedef void (*CHIPDefaultSuccessCallbackType)(void *, const chip::app::DataModel::NullObjectType &); -typedef void (*CHIPDefaultWriteSuccessCallbackType)(void *); -typedef void (*CHIPDefaultFailureCallbackType)(void *, CHIP_ERROR); - - -typedef void (*CHIPMyClusterClusterClusterAttrAttributeCallbackType)(void *, chip::app::Clusters::MyCluster::Attributes::ClusterAttr::TypeInfo::DecodableArgType); - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPReadReadCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPReadReadCallbacks.h deleted file mode 100644 index 60383ba31b550d..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/CHIPReadReadCallbacks.h +++ /dev/null @@ -1,341 +0,0 @@ -/* - * - * Copyright (c) 2023 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include - -class CHIPBooleanAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPBooleanAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPBooleanAttributeCallback(); - - static void maybeDestroy(CHIPBooleanAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, bool value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPCharStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPCharStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPCharStringAttributeCallback(); - - static void maybeDestroy(CHIPCharStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::CharSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPDoubleAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPDoubleAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPDoubleAttributeCallback(); - - static void maybeDestroy(CHIPDoubleAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, double value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPFloatAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPFloatAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPFloatAttributeCallback(); - - static void maybeDestroy(CHIPFloatAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, float value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8sAttributeCallback(); - - static void maybeDestroy(CHIPInt8sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt8uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt8uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt8uAttributeCallback(); - - static void maybeDestroy(CHIPInt8uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint8_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16sAttributeCallback(); - - static void maybeDestroy(CHIPInt16sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt16uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt16uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt16uAttributeCallback(); - - static void maybeDestroy(CHIPInt16uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint16_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32sAttributeCallback(); - - static void maybeDestroy(CHIPInt32sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt32uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt32uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt32uAttributeCallback(); - - static void maybeDestroy(CHIPInt32uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint32_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64sAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64sAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64sAttributeCallback(); - - static void maybeDestroy(CHIPInt64sAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, int64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPInt64uAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPInt64uAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPInt64uAttributeCallback(); - - static void maybeDestroy(CHIPInt64uAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, uint64_t value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; -class CHIPOctetStringAttributeCallback : public chip::Callback::Callback -{ -public: - CHIPOctetStringAttributeCallback(jobject javaCallback, bool keepAlive = false); - - ~CHIPOctetStringAttributeCallback(); - - static void maybeDestroy(CHIPOctetStringAttributeCallback * callback) { - if (!callback->keepAlive) { - callback->Cancel(); - chip::Platform::Delete(callback); - } - } - - static void CallbackFn(void * context, const chip::ByteSpan value); - static void OnSubscriptionEstablished(void * context, chip::SubscriptionId subscriptionId) { - CHIP_ERROR err = chip::JniReferences::GetInstance().CallSubscriptionEstablished(reinterpret_cast(context)->javaCallbackRef, subscriptionId); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Zcl, "Error calling onSubscriptionEstablished: %s", ErrorStr(err))); - }; - -private: - jobject javaCallbackRef; - bool keepAlive; -}; - - - - - diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp deleted file mode 100644 index 128a6f8329ecad..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME - -using namespace chip; -using chip::Controller::ClusterBase; - -JNI_METHOD(jlong, MyClusterCluster, initWithDevice)(JNIEnv * env, jobject self, jlong devicePtr, jint endpointId) -{ - chip::DeviceLayer::StackLock lock; - DeviceProxy * device = reinterpret_cast(devicePtr); - ClusterBase * cppCluster = new ClusterBase(*device->GetExchangeManager(), device->GetSecureSession().Value(), endpointId); - return reinterpret_cast(cppCluster); -} - -JNI_METHOD(void, MyClusterCluster, subscribeClusterAttrAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback, jint minInterval, jint maxInterval) -{ - chip::DeviceLayer::StackLock lock;std::unique_ptr onSuccess(Platform::New(callback, true), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - using TypeInfo = chip::app::Clusters::MyCluster::Attributes::ClusterAttr::TypeInfo; - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - - err = cppCluster->SubscribeAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall, static_cast(minInterval), static_cast(maxInterval), CHIPInt16uAttributeCallback::OnSubscriptionEstablished); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error subscribing to attribute", err)); - - onSuccess.release(); - onFailure.release(); -} diff --git a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp deleted file mode 100644 index 504996a2928a51..00000000000000 --- a/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp +++ /dev/null @@ -1,38 +0,0 @@ - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#define JNI_METHOD(RETURN, CLASS_NAME, METHOD_NAME) \ - extern "C" JNIEXPORT RETURN JNICALL Java_chip_devicecontroller_ChipClusters_00024##CLASS_NAME##_##METHOD_NAME -JNI_METHOD(void, MyClusterCluster, readClusterAttrAttribute)(JNIEnv * env, jobject self, jlong clusterPtr, jobject callback) -{ - chip::DeviceLayer::StackLock lock; - using TypeInfo = chip::app::Clusters::MyCluster::Attributes::ClusterAttr::TypeInfo; - std::unique_ptr onSuccess(chip::Platform::New(callback, false), chip::Platform::Delete); - VerifyOrReturn(onSuccess.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native success callback", CHIP_ERROR_NO_MEMORY)); - - std::unique_ptr onFailure(chip::Platform::New(callback), chip::Platform::Delete); - VerifyOrReturn(onFailure.get() != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error creating native failure callback", CHIP_ERROR_NO_MEMORY)); - - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Controller::ClusterBase * cppCluster = reinterpret_cast(clusterPtr); - VerifyOrReturn(cppCluster != nullptr, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Could not get native cluster", CHIP_ERROR_INCORRECT_STATE)); - - auto successFn = chip::Callback::Callback::FromCancelable(onSuccess->Cancel()); - auto failureFn = chip::Callback::Callback::FromCancelable(onFailure->Cancel()); - err = cppCluster->ReadAttribute(onSuccess->mContext, successFn->mCall, failureFn->mCall); - VerifyOrReturn(err == CHIP_NO_ERROR, chip::AndroidClusterExceptions::GetInstance().ReturnIllegalStateException(env, callback, "Error reading attribute", err)); - - onSuccess.release(); - onFailure.release(); -} - - diff --git a/scripts/py_matter_idl/matter_idl/xml_parser.py b/scripts/py_matter_idl/matter_idl/xml_parser.py deleted file mode 100755 index 5a07490e9c3b68..00000000000000 --- a/scripts/py_matter_idl/matter_idl/xml_parser.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import os - -try: - from matter_idl.zapxml import ParseSource, ParseXmls -except ImportError: - import sys - - sys.path.append(os.path.abspath( - os.path.join(os.path.dirname(__file__), '..'))) - from matter_idl.zapxml import ParseSource, ParseXmls - - -if __name__ == '__main__': - # This Parser is generally not intended to be run as a stand-alone binary. - # The ability to run is for debug and to print out the parsed AST. - import pprint - - import click - - # Supported log levels, mapping string values required for argument - # parsing into logging constants - __LOG_LEVELS__ = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warn': logging.WARN, - 'fatal': logging.FATAL, - } - - @ click.command() - @ click.option( - '--log-level', - default='INFO', - show_default=True, - type=click.Choice(list(__LOG_LEVELS__.keys()), case_sensitive=False), - help='Determines the verbosity of script output.') - @ click.option( - '--no-print', - show_default=True, - default=False, - is_flag=True, - help='Do not pring output data (parsed data)') - @ click.argument('filenames', nargs=-1) - def main(log_level, no_print, filenames): - logging.basicConfig( - level=__LOG_LEVELS__[log_level], - format='%(asctime)s %(levelname)-7s %(message)s', - ) - - logging.info("Starting to parse ...") - - sources = [ParseSource(source=name) for name in filenames] - data = ParseXmls(sources) - logging.info("Parse completed") - - if not no_print: - print("Data:") - pprint.pp(data) - - main(auto_envvar_prefix='CHIP') diff --git a/scripts/py_matter_idl/matter_idl/zapxml/__init__.py b/scripts/py_matter_idl/matter_idl/zapxml/__init__.py deleted file mode 100644 index 606abc6c9b7cb1..00000000000000 --- a/scripts/py_matter_idl/matter_idl/zapxml/__init__.py +++ /dev/null @@ -1,122 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import typing -import xml.sax.handler -from dataclasses import dataclass -from typing import List, Optional, Union - -from matter_idl.matter_idl_types import Idl -from matter_idl.zapxml.handlers import Context, ZapXmlHandler - - -class ParseHandler(xml.sax.handler.ContentHandler): - """A parser for ZAP-style XML data definitions. - - Defers its processing to ZapXmlHandler and keeps track of: - - an internal context for all handlers - - the parsed Idl structure that is incrementally built - - sets up parsing location within the context - - keeps track of ParsePath - - Overall converts a python SAX handler into matter_idl.zapxml.handlers - """ - - def __init__(self, include_meta_data=True): - super().__init__() - self._idl = Idl() - self._processing_stack = [] - # Context persists across all - self._context = Context() - self._include_meta_data = include_meta_data - self._locator = None - - def PrepareParsing(self, filename): - # This is a bit ugly: filename keeps changing during parse - # IDL meta is not prepared for this (as source is XML and .matter is - # single file) - if self._include_meta_data: - self._idl.parse_file_name = filename - - self._context.file_name = filename - - def Finish(self) -> Idl: - self._context.PostProcess(self._idl) - return self._idl - - def startDocument(self): - if self._include_meta_data and self._locator: - self._context.locator = self._locator - self._processing_stack = [ZapXmlHandler(self._context, self._idl)] - - def endDocument(self): - if len(self._processing_stack) != 1: - raise Exception("Unexpected nesting!") - - def startElement(self, name: str, attrs): - logging.debug("ELEMENT START: %r / %r" % (name, attrs)) - self._context.path.push(name) - self._processing_stack.append( - self._processing_stack[-1].GetNextProcessor(name, attrs)) - - def endElement(self, name: str): - logging.debug("ELEMENT END: %r" % name) - - last = self._processing_stack.pop() - last.EndProcessing() - - # important to pop AFTER processing end to allow processing - # end to access the current context - self._context.path.pop() - - def characters(self, content): - self._processing_stack[-1].HandleContent(content) - - -@dataclass -class ParseSource: - """Represents an input sopurce for ParseXmls. - - Allows for named data sources to be parsed. - """ - source: Union[str, typing.IO] # filename or stream - # actual filename to use, None if the source is a filename already - name: Optional[str] = None - - @ property - def source_file_name(self): - if self.name: - return self.name - return self.source # assume string - - -def ParseXmls(sources: List[ParseSource], include_meta_data=True) -> Idl: - """Parse one or more XML inputs and return the resulting Idl data. - - Params: - sources - what to parse - include_meta_data - if parsing location data should be included in the Idl - """ - handler = ParseHandler(include_meta_data=include_meta_data) - - for source in sources: - logging.info('Parsing %s...' % source.source_file_name) - handler.PrepareParsing(source.source_file_name) - - parser = xml.sax.make_parser() - parser.setContentHandler(handler) - parser.parse(source.source) - - return handler.Finish() diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py deleted file mode 100644 index 3745954a195cfd..00000000000000 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .base import BaseHandler -from .context import Context -from .handlers import ConfiguratorHandler - -from matter_idl.matter_idl_types import Idl - - -class ZapXmlHandler(BaseHandler): - """Handles the top level (/) of a zap xml file. - - Generally these files only contain a 'configurator' element in them - """ - - def __init__(self, context: Context, idl: Idl): - super().__init__(context) - self._idl = idl - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'configurator': - return ConfiguratorHandler(self.context, self._idl) - else: - return BaseHandler(self.context) diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py deleted file mode 100644 index ac17363d3fa6ae..00000000000000 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum - -from .context import Context - - -class HandledDepth: - """Defines how deep a XML element has been handled.""" - NOT_HANDLED = enum.auto() # Unknown/parsed element - ENTIRE_TREE = enum.auto() # Entire tree can be ignored - SINGLE_TAG = enum.auto() # Single tag processed, but not sub-items - - -class BaseHandler: - """A generic element handler. - - XML processing is done in the form of depth-first processing: - - Tree is descended into using `GetNextProcessor` - - Processors are expected to extend `BaseHandler` and allow for: - - GetNextProcessor to recurse - - HandleContent in case the text content is relevant - - EndProcessing once the entire tree has been walked (when xml element ends) - - BaseHandler keeps track if it has been handled or ot by its `_handled` setting and - init parameter. Non-handled elements will be tagged within the context, resulting - in logs. This is to detect if unknown/new tags appear in XML files. - """ - - def __init__(self, context: Context, handled=HandledDepth.NOT_HANDLED): - self.context = context - self._handled = handled - - def GetNextProcessor(self, name, attrs): - """Get the next processor to use for the given name""" - - if self._handled == HandledDepth.SINGLE_TAG: - handled = HandledDepth.NOT_HANDLED - else: - handled = self._handled - - return BaseHandler(context=self.context, handled=handled) - - def HandleContent(self, content): - """Processes some content""" - pass - - def EndProcessing(self): - """Finalizes the processing of the current element""" - if self._handled == HandledDepth.NOT_HANDLED: - self.context.MarkTagNotHandled() diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py deleted file mode 100644 index 230016e1eb5b98..00000000000000 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py +++ /dev/null @@ -1,147 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import xml.sax.xmlreader -from typing import List, Optional - -from matter_idl.matter_idl_types import Attribute, Idl, ParseMetaData - - -class IdlPostProcessor: - """Defines a callback that will apply after an entire parsing - is complete. - """ - - def FinalizeProcessing(self, idl: Idl): - """Update idl with any post-processing directives.""" - pass - - -class ProcessingPath: - """Maintains the current path of tags within xml processing. - - As processing descents into an xml like `....` - paths will have contents like ['configurator', 'cluster', ...]. - - The main purpose for this is to log and keep track of what was visited - and in general to report things like 'this path found but was not handled'. - """ - - def __init__(self, paths: Optional[List[str]] = None): - if paths is None: - paths = [] - self.paths = paths - - def push(self, name: str): - self.paths.append(name) - - def pop(self): - self.paths.pop() - - def __str__(self): - return '::'.join(self.paths) - - def __repr__(self): - return 'ProcessingPath(%r)' % self.paths - - -class Context: - """ - Contains a processing state during XML reading. - - The purpose of this is to allow elements to interact with each other, share - data and defer processing. - - Usage: - - globally shared data: - > locator: parsing location, for error reporting - > path: current ProcessingPath for any logging of where we are located - - shared data: - > global attributes are parsed by one handler, but used by others - - post-processing support: - > can register AddIdlPostProcessor to perform some processing once - a full parsing pass has been done - - More data may be added in time if it involves separate XML parse handlers - needing to interact with each other. - """ - - def __init__(self, locator: Optional[xml.sax.xmlreader.Locator] = None): - self.path = ProcessingPath() - self.locator = locator - self.file_name = None - self._not_handled = set() - self._idl_post_processors = [] - - # Map of code -> attribute - self._global_attributes = {} - - def GetCurrentLocationMeta(self) -> Optional[ParseMetaData]: - if not self.locator: - return None - - return ParseMetaData(line=self.locator.getLineNumber(), column=self.locator.getColumnNumber()) - - def ParseLogLocation(self) -> Optional[str]: - if not self.file_name: - return None - meta = self.GetCurrentLocationMeta() - if not meta: - return None - - return f"{self.file_name}:{meta.line}:{meta.column}" - - def GetGlobalAttribute(self, code): - if code in self._global_attributes: - return self._global_attributes[code] - - raise Exception( - 'Global attribute 0x%X (%d) not found. You probably need to load global-attributes.xml' % (code, code)) - - def GetGlobalAttributes(self): - return [attribute for code, attribute in self._global_attributes.items()] - - def AddGlobalAttribute(self, attribute: Attribute): - # NOTE: this may get added several times as both 'client' and 'server' - # however matter should not differentiate between the two - code = attribute.definition.code - logging.info('Adding global attribute 0x%X (%d): %s' % - (code, code, attribute.definition.name)) - - self._global_attributes[code] = attribute - - def MarkTagNotHandled(self): - path = str(self.path) - if path not in self._not_handled: - msg = "TAG %s was not handled/recognized" % path - - where = self.ParseLogLocation() - if where: - msg = msg + " at " + where - - logging.warning(msg) - self._not_handled.add(path) - - def AddIdlPostProcessor(self, processor: IdlPostProcessor, has_priority: bool = False): - if has_priority: - self._idl_post_processors.insert(0, processor) - else: - self._idl_post_processors.append(processor) - - def PostProcess(self, idl: Idl): - for p in self._idl_post_processors: - p.FinalizeProcessing(idl) - - self._idl_post_processors = [] diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py deleted file mode 100644 index 966d875c3355ed..00000000000000 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py +++ /dev/null @@ -1,661 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -from typing import Any, Optional - -from matter_idl.matter_idl_types import (Attribute, Bitmap, Cluster, ClusterSide, Command, CommandQuality, ConstantEntry, DataType, - Enum, Event, EventPriority, EventQuality, Field, FieldQuality, Idl, Struct, StructQuality, - StructTag) - -from .base import BaseHandler, HandledDepth -from .context import Context, IdlPostProcessor -from .parsing import AttrsToAccessPrivilege, AttrsToAttribute, ParseInt - -LOGGER = logging.getLogger('matter-xml-parser') - - -class ClusterNameHandler(BaseHandler): - """Handles /configurator/cluster/name elements.""" - - def __init__(self, context: Context, cluster: Cluster): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._cluster = cluster - - def HandleContent(self, content): - self._cluster.name = content.replace(' ', '') - - -class AttributeDescriptionHandler(BaseHandler): - """Handles /configurator/cluster/attribute/description elements.""" - - def __init__(self, context: Context, attribute: Attribute): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._attribute = attribute - - def HandleContent(self, content: str): - self._attribute.definition.name = content.replace(' ', '') - - -class ClusterCodeHandler(BaseHandler): - """Handles /configurator/cluster/code elements.""" - - def __init__(self, context: Context, cluster: Cluster): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._cluster = cluster - - def HandleContent(self, content: str): - self._cluster.code = ParseInt(content) - - -class EventHandler(BaseHandler): - """Handles /configurator/cluster/event elements.""" - - def __init__(self, context: Context, cluster: Cluster, attrs): - super().__init__(context) - self._cluster = cluster - - if attrs['priority'] == 'debug': - priority = EventPriority.DEBUG - elif attrs['priority'] == 'info': - priority = EventPriority.INFO - elif attrs['priority'] == 'critical': - priority = EventPriority.CRITICAL - else: - raise Exception("Unknown event priority: %s" % attrs['priority']) - - self._event = Event( - priority=priority, - code=ParseInt(attrs['code']), - name=attrs['name'], - fields=[], - ) - - if attrs.get('isFabricSensitive', "false").lower() == 'true': - self._event.qualities |= EventQuality.FABRIC_SENSITIVE - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'field': - data_type = DataType(name=attrs['type']) - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=ParseInt(attrs['id']), - name=attrs['name'], - is_list=(attrs.get('array', 'false').lower() == 'true'), - ) - - if attrs.get('optional', "false").lower() == 'true': - field.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - field.qualities |= FieldQuality.NULLABLE - - self._event.fields.append(field) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'access': - self._event.readacl = AttrsToAccessPrivilege(attrs) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def EndProcessing(self): - self._cluster.events.append(self._event) - - -class AttributeHandler(BaseHandler): - """Handles /configurator/cluster/attribute elements.""" - - def __init__(self, context: Context, cluster: Cluster, attrs): - super().__init__(context) - self._cluster = cluster - self._attribute = AttrsToAttribute(attrs) - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'access': - # Modifier not currently used: fabric scoped exists on the structure itself. - if 'modifier' in attrs: - if attrs['modifier'] != 'fabric-scoped': - raise Exception("UNKNOWN MODIFIER: %s" % attrs['modifier']) - - if ('role' in attrs) or ('privilege' in attrs): - role = AttrsToAccessPrivilege(attrs) - - if attrs['op'] == 'read': - self._attribute.readacl = role - elif attrs['op'] == 'write': - self._attribute.writeacl = role - else: - LOGGER.error("Unknown access: %r" % attrs['op']) - - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - return AttributeDescriptionHandler(self.context, self._attribute) - else: - return BaseHandler(self.context) - - def HandleContent(self, content: str): - # Content generally is the name EXCEPT if access controls - # exist, in which case `description` contains the name - content = content.strip() - if content and not self._attribute.definition.name: - self._attribute.definition.name = content - - def EndProcessing(self): - if self._attribute.definition.name is None: - raise Exception("Name for attribute was not parsed.") - - self._cluster.attributes.append(self._attribute) - - -class StructHandler(BaseHandler, IdlPostProcessor): - """ Handling /configurator/struct elements.""" - - def __init__(self, context: Context, attrs): - super().__init__(context) - - # if set, struct belongs to a specific cluster - self._cluster_codes = set() - self._struct = Struct(name=attrs['name'], fields=[]) - self._field_index = 0 - # The following are not set: - # - tag not set because not a request/response - # - code not set because not a response - - if attrs.get('isFabricScoped', "false").lower() == 'true': - self._struct.qualities |= StructQuality.FABRIC_SCOPED - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'item': - data_type = DataType( - name=attrs['type'] - ) - - if 'fieldId' in attrs: - field_index = ParseInt(attrs['fieldId']) - else: - # NOTE: code does NOT exist, so the number is incremental here - # this seems a defficiency in XML format. - field_index = self._field_index - self._field_index = field_index + 1 - - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=field_index, - name=attrs['name'], - is_list=(attrs.get('array', 'false').lower() == 'true'), - ) - - if attrs.get('optional', "false").lower() == 'true': - field.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - field.qualities |= FieldQuality.NULLABLE - - if attrs.get('isFabricSensitive', "false").lower() == 'true': - field.qualities |= FieldQuality.FABRIC_SENSITIVE - - self._struct.fields.append(field) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'cluster': - self._cluster_codes.add(ParseInt(attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - # We have two choices of adding a struct: - # - inside a cluster if a code exists - # - inside top level if no codes were associated - if self._cluster_codes: - for code in self._cluster_codes: - found = False - for c in idl.clusters: - if c.code == code: - c.structs.append(self._struct) - found = True - - if not found: - LOGGER.error('Enum %s could not find cluster (code %d/0x%X)' % - (self._struct.name, code, code)) - else: - idl.structs.append(self._struct) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class EnumHandler(BaseHandler, IdlPostProcessor): - """ Handling /configurator/enum elements.""" - - def __init__(self, context: Context, attrs): - super().__init__(context) - - # no cluster codes means global. Note that at the time - # of writing this, no global enums were defined in XMLs - self._cluster_codes = set() - self._enum = Enum(name=attrs['name'], - base_type=attrs['type'], entries=[]) - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'item': - self._enum.entries.append(ConstantEntry( - name=attrs['name'], - code=ParseInt(attrs['value']) - )) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'cluster': - self._cluster_codes.add(ParseInt(attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - # We have two choices of adding an enum: - # - inside a cluster if a code exists - # - inside top level if a code does not exist - - if not self._cluster_codes: - idl.enums.append(self._enum) - else: - found = set() - for c in idl.clusters: - if c.code in self._cluster_codes: - c.enums.append(self._enum) - found.add(c.code) - - if found != self._cluster_codes: - LOGGER.error('Enum %s could not find its clusters (codes: %r)' % - (self._enum.name, self._cluster_codes - found)) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class BitmapHandler(BaseHandler): - """ Handling /configurator/bitmap elements.""" - - def __init__(self, context: Context, attrs): - super().__init__(context) - self._cluster_codes = set() - self._bitmap = Bitmap( - name=attrs['name'], base_type=attrs['type'], entries=[]) - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'cluster': - # Multiple clusters may be associated, like IasZoneStatus - self._cluster_codes.add(ParseInt(attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'field': - self._bitmap.entries.append(ConstantEntry( - name=attrs['name'], - code=ParseInt(attrs['mask']) - )) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - # We have two choices of adding an enum: - # - inside a cluster if a code exists - # - inside top level if a code does not exist - if not self._cluster_codes: - # Log only instead of critical, as not our XML is well formed. - # For example at the time of writing this, SwitchFeature in switch-cluster.xml - # did not have a code associated with it. - LOGGER.error("Bitmap %r has no cluster codes" % self._bitmap) - return - - for code in self._cluster_codes: - found = False - for c in idl.clusters: - if c.code == code: - c.bitmaps.append(self._bitmap) - found = True - if not found: - LOGGER.error('Bitmap %s could not find its cluster (code %d/0x%X)' % - (self._bitmap.name, code, code)) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class DescriptionHandler(BaseHandler): - """Handles .../description text elements - - Attaches a "description" attribute to a given structure - """ - - def __init__(self, context: Context, target: Any): - super().__init__(context) - self.target = target - - def HandleContent(self, content): - self.target.description = content - - -class CommandHandler(BaseHandler): - """Handles /configurator/cluster/command elements.""" - - def __init__(self, context: Context, cluster: Cluster, attrs): - super().__init__(context) - self._cluster = cluster - self._command = None - self._struct = Struct(name=attrs['name'], fields=[]) - self._field_index = 0 # commands DO NOT support field index it seems - - if attrs['source'].lower() == 'client': - self._struct.tag = StructTag.REQUEST - - name = attrs['name'] - - if name.endswith('Request'): - request_name = name - else: - request_name = name+'Request' - - self._struct.name = request_name - - if 'response' in attrs: - response_name = attrs['response'] - else: - response_name = 'DefaultResponse' - - self._command = Command( - name=name, - code=ParseInt(attrs['code']), - input_param=request_name, - output_param=response_name, - ) - - if attrs.get('isFabricScoped', 'false') == 'true': - self._command.qualities |= CommandQuality.FABRIC_SCOPED - - if attrs.get('mustUseTimedInvoke', 'false') == 'true': - self._command.qualities |= CommandQuality.TIMED_INVOKE - - else: - self._struct.tag = StructTag.RESPONSE - self._struct.code = ParseInt(attrs['code']) - - def GetArgumentField(self, attrs): - data_type = DataType(name=attrs['type']) - - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - field = Field( - data_type=data_type, - code=self._field_index, - name=attrs['name'], - is_list=(attrs.get('array', 'false') == 'true') - ) - - self._field_index += 1 - - if attrs.get('optional', "false").lower() == 'true': - field.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - field.qualities |= FieldQuality.NULLABLE - - return field - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'access': - if attrs['op'] != 'invoke': - raise Exception('Unknown access for %r' % self._struct) - - if self._command: - self._command.invokeacl = AttrsToAccessPrivilege(attrs) - else: - LOGGER.warning( - "Ignored access role for reply %r" % self._struct) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'arg': - self._struct.fields.append(self.GetArgumentField(attrs)) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name.lower() == 'description': - if self._command: - return DescriptionHandler(self.context, self._command) - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def EndProcessing(self): - - if self._struct.fields: - self._cluster.structs.append(self._struct) - else: - # no input - self._command.input_param = None - - if self._command: - self._cluster.commands.append(self._command) - - -class ClusterGlobalAttributeHandler(BaseHandler): - """Handles /configurator/cluster/globalAttribute elements.""" - - def __init__(self, context: Context, cluster: Cluster, code: int): - super().__init__(context) - self._cluster = cluster - self._code = code - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'featurebit': - # It is uncler what featurebits mean. likely a bitmap should be created - # here, however only one such example exists currently: door-lock-cluster.xml - LOGGER.info('Ignoring featurebit tag for global attribute 0x%X (%d)' % ( - self._code, self._code)) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - for attribute in self._cluster.attributes: - if attribute.definition.code == self._code: - # NOTE: For now the value is ignored, but if needed it could - # be updated here. - return - - self._cluster.attributes.append( - self.context.GetGlobalAttribute(self._code)) - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - -class ClusterHandler(BaseHandler): - """Handles /configurator/cluster elements.""" - - def __init__(self, context: Context, idl: Optional[Idl]): - super().__init__(context) - self._cluster = Cluster( - side=ClusterSide.CLIENT, - name="NAME-MISSING", - code=-1, - parse_meta=context.GetCurrentLocationMeta() - ) - self._idl = idl - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'code': - return ClusterCodeHandler(self.context, self._cluster) - elif name.lower() == 'name': - return ClusterNameHandler(self.context, self._cluster) - elif name.lower() == 'attribute': - return AttributeHandler(self.context, self._cluster, attrs) - elif name.lower() == 'event': - return EventHandler(self.context, self._cluster, attrs) - elif name.lower() == 'globalattribute': - # We ignore 'side' and 'value' since they do not seem useful - return ClusterGlobalAttributeHandler(self.context, self._cluster, ParseInt(attrs['code'])) - elif name.lower() == 'command': - return CommandHandler(self.context, self._cluster, attrs) - elif name.lower() == 'description': - return DescriptionHandler(self.context, self._cluster) - elif name.lower() in ['define', 'domain', 'tag', 'client', 'server']: - # NOTE: we COULD use client and server to create separate definitions - # of each, but the usefulness of this is unclear as the definitions are - # likely identical and matter has no concept of differences between the two - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - else: - return BaseHandler(self.context) - - def EndProcessing(self): - if not self._idl: - raise Exception("Missing idl") - if self._cluster.name == "NAME-MISSING": - raise Exception("Missing cluster name") - elif self._cluster.code == -1: - raise Exception("Missing cluster code") - - self._idl.clusters.append(self._cluster) - -# Cluster extensions have extra bits for existing clusters. Can only be loaded -# IF the underlying cluster exits - - -class ClusterExtensionHandler(ClusterHandler, IdlPostProcessor): - """Handling /configurator/clusterExtension elements.""" - - def __init__(self, context: Context, code: int): - # NOTE: IDL is set to NONE so that ClusterHandler cannot - # inadvertently change it (it will be invalid anyway) - super().__init__(context, None) - self._cluster_code = code - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self) - - def FinalizeProcessing(self, idl: Idl): - found = False - for c in idl.clusters: - if c.code == self._cluster_code: - found = True - - # Append everything that can be appended - c.enums.extend(self._cluster.enums) - c.bitmaps.extend(self._cluster.bitmaps) - c.events.extend(self._cluster.events) - c.attributes.extend(self._cluster.attributes) - c.structs.extend(self._cluster.structs) - c.commands.extend(self._cluster.commands) - - if not found: - LOGGER.error('Could not extend cluster 0x%X (%d): cluster not found' % - (self._cluster_code, self._cluster_code)) - - -class GlobalAttributeHandler(BaseHandler): - """Handling configurator/global/globalAttribute elements.""" - - def __init__(self, context: Context, attribute: Attribute): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._attribute = attribute - - def HandleContent(self, content: str): - # Content generally is the name EXCEPT if access controls - # exist, in which case `description` contains the name - # - # Global attributes do not currently have access controls, so this - # case is not handled here - content = content.strip() - if content and not self._attribute.definition.name: - self._attribute.definition.name = content - - def EndProcessing(self): - if self._attribute.definition.name is None: - raise Exception("Name for attribute was not parsed.") - - self.context.AddGlobalAttribute(self._attribute) - - -class GlobalHandler(BaseHandler): - """Handling configurator/global elements.""" - - def __init__(self, context: Context): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - - def GetNextProcessor(self, name, attrs): - if name.lower() == 'attribute': - if attrs['side'].lower() == 'client': - # We expect to also have 'server' equivalent, so ignore client - # side attributes - LOGGER.debug( - 'Ignoring global client-side attribute %s' % (attrs['code'])) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - - return GlobalAttributeHandler(self.context, AttrsToAttribute(attrs)) - else: - return BaseHandler(self.context) - - def FinalizeProcessing(self, idl: Idl): - global_attributes = self.context.GetGlobalAttributes() - for cluster in idl.clusters: - cluster.attributes += global_attributes - - def EndProcessing(self): - self.context.AddIdlPostProcessor(self, True) - - -class ConfiguratorHandler(BaseHandler): - """ Handling /configurator elements.""" - - def __init__(self, context: Context, idl: Idl): - super().__init__(context, handled=HandledDepth.SINGLE_TAG) - self._idl = idl - - def GetNextProcessor(self, name: str, attrs): - if name.lower() == 'cluster': - return ClusterHandler(self.context, self._idl) - elif name.lower() == 'enum': - return EnumHandler(self.context, attrs) - elif name.lower() == 'struct': - return StructHandler(self.context, attrs) - elif name.lower() == 'bitmap': - return BitmapHandler(self.context, attrs) - elif name.lower() == 'domain': - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'clusterextension': - return ClusterExtensionHandler(self.context, ParseInt(attrs['code'])) - elif name.lower() == 'accesscontrol': - # These contain operation/role/modifier and generally only contain a - # description. These do not seem as useful to parse. - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'atomic': - # A list of types in 'chip-types' - # Generally does not seem useful - matches a type id to a description, size and some discrete/analog flags - # - # Could be eventually used as a preload of types into base types, however matter idl - # generator logic has hardcoded sizing as well. - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'devicetype': - # A list of device types in 'matter-devices.xml' - # Useful for conformance tests, but does not seem usable for serialization logic - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name.lower() == 'global': - return GlobalHandler(self.context) - else: - return BaseHandler(self.context) diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py deleted file mode 100644 index e6620e0f01fdc6..00000000000000 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py +++ /dev/null @@ -1,114 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Optional - -from matter_idl.generators.types import GetDataTypeSizeInBits, IsSignedDataType -from matter_idl.matter_idl_types import AccessPrivilege, Attribute, AttributeQuality, DataType, Field, FieldQuality - - -def ParseInt(value: str, data_type: Optional[DataType] = None) -> int: - """ - Convert a string that is a known integer into an actual number. - - Supports decimal or hex values prefixed with '0x' - """ - if value.startswith('0x'): - value = int(value[2:], 16) - if data_type and IsSignedDataType(data_type): - bits = GetDataTypeSizeInBits(data_type) - if value & (1 << (bits - 1)): - value -= 1 << bits - return value - else: - return int(value) - - -def AttrsToAccessPrivilege(attrs) -> AccessPrivilege: - """Given attributes of an '' tag, generate the underlying - access privilege by looking at the role/privilege attribute. - """ - - # XML seems to use both role and privilege to mean the same thing - # they are used interchangeably - if 'role' in attrs: - role = attrs['role'] - else: - role = attrs['privilege'] - - if role.lower() == 'view': - return AccessPrivilege.VIEW - elif role.lower() == 'operate': - return AccessPrivilege.OPERATE - elif role.lower() == 'manage': - return AccessPrivilege.MANAGE - elif role.lower() == 'administer': - return AccessPrivilege.ADMINISTER - else: - raise Exception('Unknown ACL role: %r' % role) - - -def AttrsToAttribute(attrs) -> Attribute: - """Given the attributes of an '' tag, generate the - underlying IDL Attribute dataclass. - """ - - if attrs['type'].lower() == 'array': - data_type = DataType(name=attrs['entryType']) - else: - data_type = DataType(name=attrs['type']) - - if 'minLength' in attrs: - data_type.min_length = ParseInt(attrs['minLength']) - - if 'length' in attrs: - data_type.max_length = ParseInt(attrs['length']) - - if 'min' in attrs: - data_type.min_value = ParseInt(attrs['min'], data_type) - - if 'max' in attrs: - data_type.max_value = ParseInt(attrs['max'], data_type) - - field = Field( - data_type=data_type, - code=ParseInt(attrs['code']), - name='', - is_list=(attrs['type'].lower() == 'array') - ) - - attribute = Attribute(definition=field) - - if attrs.get('optional', "false").lower() == 'true': - attribute.definition.qualities |= FieldQuality.OPTIONAL - - if attrs.get('isNullable', "false").lower() == 'true': - attribute.definition.qualities |= FieldQuality.NULLABLE - - if attrs.get('readable', "true").lower() == 'true': - attribute.qualities |= AttributeQuality.READABLE - - if attrs.get('writable', "false").lower() == 'true': - attribute.qualities |= AttributeQuality.WRITABLE - - # TODO(#22937): NOSUBSCRIBE attribute tag is not available - could find no - # clear source to get this info. - - # NOTE: default values are also present in this XML, however generally IDL - # **DATA** definitions would not care about the defaults. The - # defaults should be used to initializ storage for devices, hence - # they are part of endpoint definition/composition. We are not doing - # that here, so defaults are ignored. - - return attribute diff --git a/scripts/py_matter_idl/pyproject.toml b/scripts/py_matter_idl/pyproject.toml deleted file mode 100644 index ab9c08adaab8b5..00000000000000 --- a/scripts/py_matter_idl/pyproject.toml +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[build-system] -requires = ['setuptools', 'wheel'] -build-backend = 'setuptools.build_meta' diff --git a/scripts/py_matter_idl/setup.cfg b/scripts/py_matter_idl/setup.cfg deleted file mode 100644 index 57f93c3dd9aa82..00000000000000 --- a/scripts/py_matter_idl/setup.cfg +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[metadata] -name = matter_idl -version = 0.0.1 -author = Project CHIP Authors -description = Parse matter idl files - -[options] -packages = find: -zip_safe = False -install_requires= - lark - jinja2 - stringcase - -[options.package_data] -matter_idl = - lint/lint_rules_grammar.lark - matter_grammar.lark - generators/cpp/application/CallbackStubSource.jinja - generators/cpp/application/PluginApplicationCallbacksHeader.jinja - generators/cpp/tlvmeta/TLVMetaData_cpp.jinja - generators/cpp/tlvmeta/TLVMetaData_h.jinja - generators/java/CHIPCallbackTypes.jinja - generators/java/ChipClustersCpp.jinja - generators/java/ChipClustersRead.jinja - generators/java/CHIPReadCallbacks_h.jinja - generators/java/ClusterIDMapping.jinja - generators/java/ClusterReadMapping.jinja - generators/java/ClusterWriteMapping.jinja diff --git a/scripts/py_matter_idl/setup.py b/scripts/py_matter_idl/setup.py deleted file mode 100644 index 5c10e05ae39916..00000000000000 --- a/scripts/py_matter_idl/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -"""The matter_idl package.""" - -import setuptools # type: ignore - -setuptools.setup() # Package definition in setup.cfg