From cac78e490e82389a29ff76328650da16e857589f Mon Sep 17 00:00:00 2001 From: cpagravel Date: Fri, 12 May 2023 06:11:42 -0700 Subject: [PATCH 01/36] Add esp32-devkitc-light-rpc target in smoke-test.yaml (#26486) --- integrations/cloudbuild/smoke-test.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index 411ae1825f67a5..5c1d09c5f555ad 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -29,6 +29,7 @@ steps: args: - >- ./scripts/build/build_examples.py --enable-flashbundle --target + esp32-devkitc-light-rpc --target esp32-m5stack-all-clusters-ipv6only --target esp32-m5stack-all-clusters-rpc --target esp32-m5stack-light --target From 35b148b813261475f226b6701340fe273c922660 Mon Sep 17 00:00:00 2001 From: Thomas Langewouters <82949801+q-thla@users.noreply.github.com> Date: Fri, 12 May 2023 15:15:14 +0200 Subject: [PATCH 02/36] qpg: remove MBEDTLS_REPO_DIR make argument (#26507) This argument is obsolete and this change was accidentally omitted from previous PR's. --- third_party/qpg_sdk/BUILD.gn | 8 -------- 1 file changed, 8 deletions(-) diff --git a/third_party/qpg_sdk/BUILD.gn b/third_party/qpg_sdk/BUILD.gn index c6565e4041e9ed..4d10e71fc00704 100755 --- a/third_party/qpg_sdk/BUILD.gn +++ b/third_party/qpg_sdk/BUILD.gn @@ -90,8 +90,6 @@ qpg_make_build("qpg_mbedtls_alt") { "-f", rebase_path(qpg_sdk_root, root_build_dir) + "/Libraries/Qorvo/mbedtls_alt/Makefile.mbedtls_alt_${qpg_target_ic}", - "MBEDTLS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + - "/third_party/mbedtls/repo", "WORKDIR=" + rebase_path(target_gen_dir, root_build_dir) + "/${qpg_sdk_lib_dir}/mbedtls_alt_${qpg_target_ic}", ] @@ -129,8 +127,6 @@ qpg_make_build("qpg_glue") { rebase_path(qpg_sdk_root, root_build_dir) + "/Libraries/Qorvo/MatterQorvoGlue/Makefile.MatterQorvoGlue_${qpg_target_ic}_libbuild", "FREERTOS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + "/third_party/freertos/repo", - "MBEDTLS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + - "/third_party/mbedtls/repo", "WORKDIR=" + rebase_path(target_gen_dir, root_build_dir) + "/${qpg_sdk_lib_dir}/MatterQorvoGlue", ] @@ -151,8 +147,6 @@ qpg_make_build("qpg_bootloader") { rebase_path(qpg_sdk_root, root_build_dir) + "/Libraries/Qorvo/Bootloader/Makefile.Bootloader_${qpg_target_ic}_compr_secure", "FREERTOS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + "/third_party/freertos/repo", - "MBEDTLS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + - "/third_party/mbedtls/repo", "WORKDIR=" + rebase_path(target_gen_dir, root_build_dir) + "/${qpg_sdk_lib_dir}/Bootloader_${qpg_target_ic}_compr_secure", "UMB_WORKDIR=" + rebase_path(target_gen_dir, root_build_dir) + @@ -181,8 +175,6 @@ qpg_make_build("qpg_openthread_glue") { rebase_path(qpg_sdk_root, root_build_dir) + "/Libraries/Qorvo/OpenThreadQorvoGlue/Makefile.OpenThreadQorvoGlue_${qpg_target_ic}_ftd", "FREERTOS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + "/third_party/freertos/repo", - "MBEDTLS_REPO_DIR=" + rebase_path(chip_root, root_build_dir) + - "/third_party/mbedtls/repo", "OPENTHREAD_REPO_DIR =" + rebase_path(chip_root, root_build_dir) + "/third_party/openthread/repo", "WORKDIR=" + rebase_path(target_gen_dir, root_build_dir) + From bbff46a62a4c503fc656b5f700c5c88cb084337c Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 12 May 2023 09:15:55 -0400 Subject: [PATCH 03/36] Update cross compile image to 22.04.1 (#26522) * Update cross compile dockerfile * Correct the paths * Fix vscode image as well --- .../images/chip-build-crosscompile/Dockerfile | 20 +++++++++---------- .../images/chip-build-vscode/Dockerfile | 4 ++-- integrations/docker/images/chip-build/version | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/integrations/docker/images/chip-build-crosscompile/Dockerfile b/integrations/docker/images/chip-build-crosscompile/Dockerfile index 59e023ea16f688..e00428918ae312 100644 --- a/integrations/docker/images/chip-build-crosscompile/Dockerfile +++ b/integrations/docker/images/chip-build-crosscompile/Dockerfile @@ -15,19 +15,19 @@ WORKDIR /opt RUN set -x \ && git clone --depth 1 https://chromium.googlesource.com/chromium/tools/depot_tools.git /opt/depot_tools \ # TODO: Remove experimental solution to create the sysroot file in cross-compile image - && echo 'experimental/matter/sysroot/ubuntu-21.04-aarch64 latest' > ensure_file.txt \ + && echo 'experimental/matter/sysroot/ubuntu-22.04.1-aarch64 latest' > ensure_file.txt \ && ./depot_tools/cipd ensure -ensure-file ensure_file.txt -root ./ \ - && tar xfvJ ubuntu-21.04-aarch64-sysroot.tar.xz \ - && rm -rf /opt/ubuntu-21.04-aarch64-sysroot/usr/lib/firmware \ - && rm -rf /opt/ubuntu-21.04-aarch64-sysroot/usr/lib/git-core \ - && rm -rf /opt/ubuntu-21.04-aarch64-sysroot/usr/lib/modules \ - && rm -rf /opt/ubuntu-21.04-aarch64-sysroot/lib/firmware \ - && rm -rf /opt/ubuntu-21.04-aarch64-sysroot/lib/git-core \ - && rm -rf /opt/ubuntu-21.04-aarch64-sysroot/lib/modules \ + && tar xfvJ ubuntu-22.04.1-aarch64-sysroot.tar.xz \ + && rm -rf /opt/ubuntu-22.04.1-aarch64-sysroot/usr/lib/firmware \ + && rm -rf /opt/ubuntu-22.04.1-aarch64-sysroot/usr/lib/git-core \ + && rm -rf /opt/ubuntu-22.04.1-aarch64-sysroot/usr/lib/modules \ + && rm -rf /opt/ubuntu-22.04.1-aarch64-sysroot/lib/firmware \ + && rm -rf /opt/ubuntu-22.04.1-aarch64-sysroot/lib/git-core \ + && rm -rf /opt/ubuntu-22.04.1-aarch64-sysroot/lib/modules \ && : # last line FROM connectedhomeip/chip-build:${VERSION} -COPY --from=build /opt/ubuntu-21.04-aarch64-sysroot/ /opt/ubuntu-21.04-aarch64-sysroot/ +COPY --from=build /opt/ubuntu-22.04.1-aarch64-sysroot/ /opt/ubuntu-22.04-aarch64-sysroot/ -ENV SYSROOT_AARCH64=/opt/ubuntu-21.04-aarch64-sysroot +ENV SYSROOT_AARCH64=/opt/ubuntu-22.04.1-aarch64-sysroot diff --git a/integrations/docker/images/chip-build-vscode/Dockerfile b/integrations/docker/images/chip-build-vscode/Dockerfile index 6b33cc934f97fe..c195ced69d9c9e 100644 --- a/integrations/docker/images/chip-build-vscode/Dockerfile +++ b/integrations/docker/images/chip-build-vscode/Dockerfile @@ -40,7 +40,7 @@ COPY --from=telink /opt/telink/zephyr-sdk-0.15.2 /opt/telink/zephyr-sdk-0.15.2 COPY --from=tizen /opt/tizen-sdk /opt/tizen-sdk -COPY --from=crosscompile /opt/ubuntu-21.04-aarch64-sysroot /opt/ubuntu-21.04-aarch64-sysroot +COPY --from=crosscompile /opt/ubuntu-22.04.1-aarch64-sysroot /opt/ubuntu-22.04.1-aarch64-sysroot COPY --from=ameba /opt/ameba /opt/ameba @@ -105,7 +105,7 @@ ENV OPENOCD_PATH=/opt/openocd/ ENV PW_ENVIRONMENT_ROOT=/home/vscode/pigweed/env ENV QEMU_ESP32=/opt/espressif/qemu/xtensa-softmmu/qemu-system-xtensa ENV QEMU_ESP32_DIR=/opt/espressif/qemu -ENV SYSROOT_AARCH64=/opt/ubuntu-21.04-aarch64-sysroot +ENV SYSROOT_AARCH64=/opt/ubuntu-22.04.1-aarch64-sysroot ENV TELINK_ZEPHYR_BASE=/opt/telink/zephyrproject/zephyr ENV TELINK_ZEPHYR_SDK_DIR=/opt/telink/zephyr-sdk-0.15.2 ENV TI_SYSCONFIG_ROOT=/opt/ti/sysconfig_1.13.0 diff --git a/integrations/docker/images/chip-build/version b/integrations/docker/images/chip-build/version index d6fd9f4e3bd6f4..bf582d0ebee454 100644 --- a/integrations/docker/images/chip-build/version +++ b/integrations/docker/images/chip-build/version @@ -1 +1 @@ -0.7.7 Version bump reason: [Ameba] fix runtime dct error and error mapping +0.7.8 Version bump reason: Update crosscompile sysroot to Ubuntu 22.04.01 From d7079d91cf50a799764de927b61886824ed30d4a Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 12 May 2023 10:00:23 -0400 Subject: [PATCH 04/36] Add a script to mass-update cluster revisions in our .zap files. (#26514) We're going to need to do this for several clusters, and doing it by hand is really painful. Also fixes a bug in zap_convert_all.py when run in non-parallel mode. --- scripts/tools/zap/update_cluster_revisions.py | 154 ++++++++++++++++++ scripts/tools/zap_convert_all.py | 2 +- 2 files changed, 155 insertions(+), 1 deletion(-) create mode 100755 scripts/tools/zap/update_cluster_revisions.py diff --git a/scripts/tools/zap/update_cluster_revisions.py b/scripts/tools/zap/update_cluster_revisions.py new file mode 100755 index 00000000000000..e29a274cf47087 --- /dev/null +++ b/scripts/tools/zap/update_cluster_revisions.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2020 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 argparse +import json +import logging +import multiprocessing +import os +import subprocess +import sys +from pathlib import Path + +CHIP_ROOT_DIR = os.path.realpath( + os.path.join(os.path.dirname(__file__), '../../..')) + + +def getTargets(): + ROOTS_TO_SEARCH = [ + './examples', + './src/controller/data_model', + './scripts/tools/zap/tests/inputs', + ] + + targets = [] + for root in ROOTS_TO_SEARCH: + for filepath in Path(root).rglob('*.zap'): + targets.append(filepath) + + return targets + + +def checkPythonVersion(): + if sys.version_info[0] < 3: + print('Must use Python 3. Current version is ' + + str(sys.version_info[0])) + exit(1) + + +def runArgumentsParser(): + parser = argparse.ArgumentParser( + description='Update the ClusterRevision for a chosen cluster in all .zap files') + parser.add_argument('--cluster-id', default=None, action='store', + help='The id of the cluster, as hex, for which the cluster revision should be updated.') + parser.add_argument('--new-revision', default=None, action='store', + help='The new cluster revision as a decimal integer') + parser.add_argument('--old-revision', default=None, action='store', + help='If set, only clusters with this old revision will be updated. This is a decimal integer.') + parser.add_argument('--dry-run', default=False, action='store_true', + help="Don't do any generation, just log what .zap files would be updated (default: False)") + parser.add_argument('--parallel', action='store_true') + parser.add_argument('--no-parallel', action='store_false', dest='parallel') + parser.set_defaults(parallel=True) + + args = parser.parse_args() + + if args.cluster_id is None: + logging.error("Must have a cluster id") + sys.exit(1) + + if args.new_revision is None: + logging.error("Must have a new cluster revision") + sys.exit(1) + + args.cluster_id = int(args.cluster_id, 16) + + return args + + +def isClusterRevisionAttribute(attribute): + if attribute['mfgCode'] is not None: + return False + + if attribute['code'] != 0xFFFD: + return False + + if attribute['name'] != "ClusterRevision": + logging.error("Attribute has ClusterRevision id but wrong name") + return False + + return True + + +def updateOne(item): + """ + Helper method that may be run in parallel to update a single target. + """ + (args, target) = item + + with open(target, "r") as file: + data = json.load(file) + + for endpointType in data['endpointTypes']: + for cluster in endpointType['clusters']: + if cluster['mfgCode'] is None and cluster['code'] == args.cluster_id: + for attribute in cluster['attributes']: + if isClusterRevisionAttribute(attribute): + if args.old_revision is None or attribute['defaultValue'] == args.old_revision: + attribute['defaultValue'] = args.new_revision + + with open(target, "w") as file: + json.dump(data, file) + + # Now run convert.py on the file to have ZAP reformat it however it likes. + subprocess.check_call(['./scripts/tools/zap/convert.py', target]) + + +def main(): + checkPythonVersion() + + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s %(name)s %(levelname)-7s %(message)s' + ) + + args = runArgumentsParser() + + os.chdir(CHIP_ROOT_DIR) + + targets = getTargets() + + if args.dry_run: + for target in targets: + print(f"Will try to update: {target}") + sys.exit(0) + + items = [(args, target) for target in targets] + + if args.parallel: + # Ensure each zap run is independent + os.environ['ZAP_TEMPSTATE'] = '1' + with multiprocessing.Pool() as pool: + for _ in pool.imap_unordered(updateOne, items): + pass + else: + for item in items: + updateOne(item) + + +if __name__ == '__main__': + main() diff --git a/scripts/tools/zap_convert_all.py b/scripts/tools/zap_convert_all.py index 677067c93dc123..ba456ca1efeb90 100755 --- a/scripts/tools/zap_convert_all.py +++ b/scripts/tools/zap_convert_all.py @@ -105,7 +105,7 @@ def main(): pass else: for target in targets: - generateOne(target) + convertOne(target) if __name__ == '__main__': From 00d227fc83cc29801a479ee6f7f2f97672feb885 Mon Sep 17 00:00:00 2001 From: PSONALl <77670766+PSONALl@users.noreply.github.com> Date: Fri, 12 May 2023 19:32:17 +0530 Subject: [PATCH 05/36] Fixes for bluedroid and Added ChipLock to thread in ble-controller (#26504) --- src/platform/ESP32/BUILD.gn | 4 ++ src/platform/ESP32/ChipDeviceScanner.h | 5 +- .../ESP32/bluedroid/BLEManagerImpl.cpp | 59 ++++++++++--------- .../ESP32/bluedroid/ChipDeviceScanner.cpp | 12 +--- src/platform/ESP32/nimble/BLEManagerImpl.cpp | 4 ++ 5 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/platform/ESP32/BUILD.gn b/src/platform/ESP32/BUILD.gn index 0e751e7f1455ae..66cf6279dfc6f8 100644 --- a/src/platform/ESP32/BUILD.gn +++ b/src/platform/ESP32/BUILD.gn @@ -90,6 +90,10 @@ static_library("ESP32") { ] } + if (chip_enable_ble_controller) { + sources += [ "ChipDeviceScanner.h" ] + } + if (chip_bt_nimble_enabled) { sources += [ "nimble/BLEManagerImpl.cpp" ] if (chip_enable_ble_controller) { diff --git a/src/platform/ESP32/ChipDeviceScanner.h b/src/platform/ESP32/ChipDeviceScanner.h index 90e866b52a2c41..8856dd3d160629 100644 --- a/src/platform/ESP32/ChipDeviceScanner.h +++ b/src/platform/ESP32/ChipDeviceScanner.h @@ -16,7 +16,6 @@ */ #pragma once -#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER #include #include @@ -24,14 +23,13 @@ #if CONFIG_BT_NIMBLE_ENABLED #include "host/ble_hs.h" -#else +#elif CONFIG_BT_BLUEDROID_ENABLED #include "esp_bt.h" #include "esp_bt_main.h" #include "esp_gap_ble_api.h" #include "esp_gatt_common_api.h" #include "esp_gatt_defs.h" #include "esp_gattc_api.h" -#include "esp_gatts_api.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" #include @@ -111,4 +109,3 @@ class ChipDeviceScanner } // namespace Internal } // namespace DeviceLayer } // namespace chip -#endif // CONFIG_ENABLE_ESP32_BLE_CONTROLLER diff --git a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp index 46fca5f6982f2d..a43b3456e940e4 100644 --- a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp +++ b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp @@ -196,6 +196,7 @@ static struct gattc_profile_inst gl_profile_tab[PROFILE_NUM] = { .gattc_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */ }, }; +static esp_gatt_if_t chip_ctrl_gattc_if = 0; #endif CHIP_ERROR BLEManagerImpl::_Init() @@ -432,6 +433,15 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp switch (event) { case ESP_GATTC_REG_EVT: + if (param->reg.status == ESP_GATT_OK) + { + chip_ctrl_gattc_if = gattc_if; + } + else + { + ChipLogProgress(Ble, "Reg app failed, app_id %04x, status 0x%x", param->reg.app_id, param->reg.status); + return; + } break; case ESP_GATTC_CONNECT_EVT: err = sInstance.HandleGAPConnect(*p_data); @@ -452,8 +462,7 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp break; } ChipLogProgress(Ble, "discover service complete conn_id %d", param->dis_srvc_cmpl.conn_id); - esp_ble_gattc_search_service(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, param->cfg_mtu.conn_id, - &remote_filter_service_uuid); + esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, &remote_filter_service_uuid); break; case ESP_GATTC_CFG_MTU_EVT: if (param->cfg_mtu.status != ESP_GATT_OK) @@ -502,8 +511,8 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp uint16_t count = 0; uint16_t offset = 0; esp_gatt_status_t status = - esp_ble_gattc_get_attr_count(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, p_data->search_cmpl.conn_id, - ESP_GATT_DB_CHARACTERISTIC, gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, + esp_ble_gattc_get_attr_count(gattc_if, p_data->search_cmpl.conn_id, ESP_GATT_DB_CHARACTERISTIC, + gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, INVALID_HANDLE, &count); if (status != ESP_GATT_OK) { @@ -522,10 +531,9 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp } else { - status = esp_ble_gattc_get_all_char(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, p_data->search_cmpl.conn_id, - gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, - gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, char_elem_result, - &count, offset); + status = esp_ble_gattc_get_all_char( + gattc_if, p_data->search_cmpl.conn_id, gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, + gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, char_elem_result, &count, offset); if (status != 0) { ChipLogProgress(Ble, "esp_ble_gattc_get_char_by_uuid error"); @@ -547,8 +555,7 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp else if (char_elem_result[i].properties & CharProps_ReadNotify) { gl_profile_tab[PROFILE_A_APP_ID].notify_char_handle = char_elem_result[i].char_handle; - esp_ble_gattc_register_for_notify(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, - gl_profile_tab[PROFILE_A_APP_ID].remote_bda, + esp_ble_gattc_register_for_notify(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, char_elem_result[i].char_handle); } } @@ -572,7 +579,7 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp { uint16_t count = 0; esp_gatt_status_t ret_status = esp_ble_gattc_get_attr_count( - gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, ESP_GATT_DB_DESCRIPTOR, + gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, ESP_GATT_DB_DESCRIPTOR, gl_profile_tab[PROFILE_A_APP_ID].service_start_handle, gl_profile_tab[PROFILE_A_APP_ID].service_end_handle, gl_profile_tab[PROFILE_A_APP_ID].notify_char_handle, &count); if (ret_status != ESP_GATT_OK) @@ -589,9 +596,9 @@ void BLEManagerImpl::gattc_profile_event_handler(esp_gattc_cb_event_t event, esp else { memcpy(¬ify_descr_uuid.uuid.uuid16, ShortUUID_CHIPoBLE_CharTx_Desc, 2); - ret_status = esp_ble_gattc_get_descr_by_char_handle( - gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, - p_data->reg_for_notify.handle, notify_descr_uuid, descr_elem_result, &count); + ret_status = esp_ble_gattc_get_descr_by_char_handle(gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, + p_data->reg_for_notify.handle, notify_descr_uuid, + descr_elem_result, &count); ChipLogProgress(Ble, "discoverd all chars and discr.........\n\n"); ChipDeviceEvent chipEvent; @@ -722,14 +729,14 @@ void BLEManagerImpl::HandleConnectFailed(CHIP_ERROR error) void BLEManagerImpl::CancelConnect(void) { - int rc = esp_ble_gattc_close(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, connId); + int rc = esp_ble_gattc_close(chip_ctrl_gattc_if, connId); VerifyOrReturn(rc == 0, ChipLogError(Ble, "Failed to cancel connection rc=%d", rc)); } void BLEManagerImpl::ConnectDevice(esp_bd_addr_t & addr, esp_ble_addr_type_t addr_type, uint16_t timeout) { int rc; - rc = esp_ble_gattc_open(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, addr, addr_type, true); + rc = esp_ble_gattc_open(chip_ctrl_gattc_if, addr, addr_type, true); if (rc != 0) { ChipLogError(Ble, "Failed to connect to rc=%d", rc); @@ -751,13 +758,12 @@ bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const value[0] = 0x02; value[1] = 0x00; - rc = esp_ble_gattc_write_char_descr(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, - descr_elem_result[0].handle, sizeof(value), value, ESP_GATT_WRITE_TYPE_RSP, - ESP_GATT_AUTH_REQ_NONE); + rc = esp_ble_gattc_write_char_descr(chip_ctrl_gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, descr_elem_result[0].handle, + sizeof(value), value, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); if (rc != 0) { ChipLogError(Ble, "esp_ble_gattc_get_descr_by_char_handle failed: %d", rc); - esp_ble_gattc_close(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, conId); + esp_ble_gattc_close(chip_ctrl_gattc_if, conId); return false; } ChipDeviceEvent event; @@ -780,13 +786,12 @@ bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, cons value[0] = 0x00; value[1] = 0x00; - rc = esp_ble_gattc_write_char_descr(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, - descr_elem_result[0].handle, sizeof(value), value, ESP_GATT_WRITE_TYPE_RSP, - ESP_GATT_AUTH_REQ_NONE); + rc = esp_ble_gattc_write_char_descr(chip_ctrl_gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, descr_elem_result[0].handle, + sizeof(value), value, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); if (rc != 0) { ChipLogError(Ble, "ble_gattc_write_flat failed: %d", rc); - esp_ble_gattc_close(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, conId); + esp_ble_gattc_close(chip_ctrl_gattc_if, conId); return false; } ChipDeviceEvent event; @@ -874,7 +879,7 @@ bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBle ChipLogProgress(Ble, "In send write request\n"); int rc; - rc = esp_ble_gattc_write_char(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, + rc = esp_ble_gattc_write_char(chip_ctrl_gattc_if, gl_profile_tab[PROFILE_A_APP_ID].conn_id, gl_profile_tab[PROFILE_A_APP_ID].write_char_handle, pBuf->DataLength(), pBuf->Start(), ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE); if (rc != 0) @@ -1915,7 +1920,7 @@ CHIP_ERROR BLEManagerImpl::HandleGAPCentralConnect(esp_ble_gattc_cb_param_t p_da memcpy(gl_profile_tab[PROFILE_A_APP_ID].remote_bda, p_data.connect.remote_bda, sizeof(esp_bd_addr_t)); // Start the GATT discovery process - int rc = esp_ble_gattc_search_service(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, connId, &remote_filter_service_uuid); + int rc = esp_ble_gattc_search_service(chip_ctrl_gattc_if, connId, &remote_filter_service_uuid); if (rc != 0) { HandleGAPConnectionFailed(); @@ -1935,7 +1940,7 @@ CHIP_ERROR BLEManagerImpl::HandleGAPConnect(esp_ble_gattc_cb_param_t p_data) gl_profile_tab[PROFILE_A_APP_ID].conn_id = p_data.connect.conn_id; connId = p_data.connect.conn_id; memcpy(gl_profile_tab[PROFILE_A_APP_ID].remote_bda, p_data.connect.remote_bda, sizeof(esp_bd_addr_t)); - rc = esp_ble_gattc_send_mtu_req(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, p_data.connect.conn_id); + rc = esp_ble_gattc_send_mtu_req(chip_ctrl_gattc_if, p_data.connect.conn_id); if (rc != 0) { diff --git a/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp b/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp index cea4b9f8d42f14..81421cf8d5f79a 100644 --- a/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp +++ b/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp @@ -14,19 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#if CONFIG_ENABLE_ESP32_BLE_CONTROLLER #include -#include "esp_bt.h" -#include "esp_bt_main.h" -#include "esp_gap_ble_api.h" -#include "esp_gatt_common_api.h" -#include "esp_gatt_defs.h" -#include "esp_gattc_api.h" -#include "esp_gatts_api.h" -#include "esp_log.h" -#include "freertos/FreeRTOS.h" #include #include @@ -116,6 +106,7 @@ CHIP_ERROR ChipDeviceScanner::StopScan() ChipLogError(DeviceLayer, "ble_gap_disc_cancel failed: %d", rc); return CHIP_ERROR_INTERNAL; } + mIsScanning = false; mDelegate->OnScanComplete(); return CHIP_NO_ERROR; @@ -124,4 +115,3 @@ CHIP_ERROR ChipDeviceScanner::StopScan() } // namespace Internal } // namespace DeviceLayer } // namespace chip -#endif // CONFIG_ENABLE_ESP32_BLE_CONTROLLER diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index f92e4b10ce931d..52e86d4b050a7f 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -1653,6 +1653,7 @@ void BLEManagerImpl::OnDeviceScanned(const struct ble_hs_adv_fields & fields, co { if (!mBLEScanConfig.mDiscriminator.MatchesLongDiscriminator(info.GetDeviceDiscriminator())) { + printf("Discriminator didi not match \n"); return; } ChipLogProgress(Ble, "Device Discriminator match. Attempting to connect"); @@ -1667,7 +1668,10 @@ void BLEManagerImpl::OnDeviceScanned(const struct ble_hs_adv_fields & fields, co } mBLEScanConfig.mBleScanState = BleScanState::kConnecting; + chip::DeviceLayer::PlatformMgr().LockChipStack(); DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds16(kConnectTimeout), HandleConnectTimeout, nullptr); + chip::DeviceLayer::PlatformMgr().UnlockChipStack(); + mDeviceScanner.StopScan(); ConnectDevice(addr, kConnectTimeout); From 7134d23a5b7a27239f59f5766c47183ad3ce97a7 Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Fri, 12 May 2023 22:06:25 +0800 Subject: [PATCH 06/36] ESP32: Fix format errors in platform/ESP32/Logging.cpp (#26496) --- src/platform/ESP32/Logging.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/platform/ESP32/Logging.cpp b/src/platform/ESP32/Logging.cpp index a8270cbddf1412..07ec4a1690bd40 100644 --- a/src/platform/ESP32/Logging.cpp +++ b/src/platform/ESP32/Logging.cpp @@ -30,7 +30,7 @@ void ENFORCE_FORMAT(3, 0) LogV(const char * module, uint8_t category, const char { case kLogCategory_Error: { { - printf(LOG_COLOR_E "E (%u) %s: ", esp_log_timestamp(), tag); + printf(LOG_COLOR_E "E (%" PRIu32 ") %s: ", esp_log_timestamp(), tag); esp_log_writev(ESP_LOG_ERROR, tag, msg, v); printf(LOG_RESET_COLOR "\n"); } @@ -40,7 +40,7 @@ void ENFORCE_FORMAT(3, 0) LogV(const char * module, uint8_t category, const char case kLogCategory_Progress: default: { { - printf(LOG_COLOR_I "I (%u) %s: ", esp_log_timestamp(), tag); + printf(LOG_COLOR_I "I (%" PRIu32 ") %s: ", esp_log_timestamp(), tag); esp_log_writev(ESP_LOG_INFO, tag, msg, v); printf(LOG_RESET_COLOR "\n"); } @@ -49,7 +49,7 @@ void ENFORCE_FORMAT(3, 0) LogV(const char * module, uint8_t category, const char case kLogCategory_Detail: { { - printf(LOG_COLOR_D "D (%u) %s: ", esp_log_timestamp(), tag); + printf(LOG_COLOR_D "D (%" PRIu32 ") %s: ", esp_log_timestamp(), tag); esp_log_writev(ESP_LOG_DEBUG, tag, msg, v); printf(LOG_RESET_COLOR "\n"); } From a0ebf5a9c2ff64dd42a34b278bd59917b7ea81bf Mon Sep 17 00:00:00 2001 From: pankore <86098180+pankore@users.noreply.github.com> Date: Fri, 12 May 2023 22:11:18 +0800 Subject: [PATCH 07/36] [ota] cancelupdate and progress state from kApplying to kIdle when HandleApply fails (#26499) --- src/platform/Ameba/AmebaOTAImageProcessor.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/platform/Ameba/AmebaOTAImageProcessor.cpp b/src/platform/Ameba/AmebaOTAImageProcessor.cpp index 5db732fcff71d0..e605ba7741fb4a 100644 --- a/src/platform/Ameba/AmebaOTAImageProcessor.cpp +++ b/src/platform/Ameba/AmebaOTAImageProcessor.cpp @@ -400,6 +400,7 @@ void AmebaOTAImageProcessor::HandleApply(intptr_t context) if (imageProcessor == nullptr) { ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + GetRequestorInstance()->CancelImageUpdate(); return; } @@ -409,12 +410,14 @@ void AmebaOTAImageProcessor::HandleApply(intptr_t context) { ota_update_free(imageProcessor->pOtaTgtHdr); ChipLogError(SoftwareUpdate, "OTA update signature failed"); + GetRequestorInstance()->CancelImageUpdate(); return; } #elif defined(CONFIG_PLATFORM_8710C) if (update_ota_signature(imageProcessor->signature, imageProcessor->flash_addr) < 0) { ChipLogError(SoftwareUpdate, "OTA update signature failed"); + GetRequestorInstance()->CancelImageUpdate(); return; } #endif From 999ce275a8761d47e57ca028da1e2ec50d0943dc Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Fri, 12 May 2023 16:11:33 +0200 Subject: [PATCH 08/36] CI: Skip cache segment download after 3 minutes (#26500) * CI: Disable bootstrap cache until actions/cache is fixed * Set SEGMENT_DOWNLOAD_TIMEOUT_MINS to 3 minutes Re-enable bootstrap cache --- .github/workflows/build.yaml | 2 ++ .github/workflows/chef.yaml | 5 +++++ .github/workflows/cirque.yaml | 5 +++++ .github/workflows/darwin-tests.yaml | 2 ++ .github/workflows/darwin.yaml | 5 +++++ .github/workflows/examples-ameba.yaml | 2 ++ .github/workflows/examples-bouffalolab.yaml | 2 ++ .github/workflows/examples-cc13x2x7_26x2x7.yaml | 2 ++ .github/workflows/examples-cc32xx.yaml | 5 +++++ .github/workflows/examples-efr32.yaml | 2 ++ .github/workflows/examples-esp32.yaml | 2 ++ .github/workflows/examples-infineon.yaml | 2 ++ .github/workflows/examples-k32w.yaml | 2 ++ .github/workflows/examples-linux-arm.yaml | 2 ++ .github/workflows/examples-linux-imx.yaml | 2 ++ .github/workflows/examples-linux-standalone.yaml | 2 ++ .github/workflows/examples-mbed.yaml | 2 ++ .github/workflows/examples-mw320.yaml | 2 ++ .github/workflows/examples-nrfconnect.yaml | 2 ++ .github/workflows/examples-openiotsdk.yaml | 5 +++++ .github/workflows/examples-qpg.yaml | 2 ++ .github/workflows/examples-telink.yaml | 2 ++ .github/workflows/examples-tizen.yaml | 2 ++ .github/workflows/full-android.yaml | 2 ++ .github/workflows/fuzzing-build.yaml | 2 ++ .github/workflows/lint.yml | 5 ++++- .github/workflows/qemu.yaml | 2 ++ .github/workflows/release_artifacts.yaml | 5 +++++ .github/workflows/smoketest-android.yaml | 2 ++ .github/workflows/smoketest-darwin.yaml | 5 +++++ .github/workflows/tests.yaml | 2 ++ .github/workflows/zap_regeneration.yaml | 5 +++++ .github/workflows/zap_templates.yaml | 5 +++++ 33 files changed, 95 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index f659f10b5a76e8..8dfc7086417d2d 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -26,6 +26,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: build_linux_gcc_debug: diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index f6f8c4c6076986..42dba7ca4485aa 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -23,6 +23,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: chef_linux: name: Chef - Linux CI Examples diff --git a/.github/workflows/cirque.yaml b/.github/workflows/cirque.yaml index 6b2dfa7372ed6b..ba6938efb7e19e 100644 --- a/.github/workflows/cirque.yaml +++ b/.github/workflows/cirque.yaml @@ -24,6 +24,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: cirque: name: Cirque diff --git a/.github/workflows/darwin-tests.yaml b/.github/workflows/darwin-tests.yaml index face48a25e88e0..02c4f58af64b89 100644 --- a/.github/workflows/darwin-tests.yaml +++ b/.github/workflows/darwin-tests.yaml @@ -28,6 +28,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: test_suites_chip_tool_darwin: diff --git a/.github/workflows/darwin.yaml b/.github/workflows/darwin.yaml index 00c669eb81a4ce..53ea74716dd028 100644 --- a/.github/workflows/darwin.yaml +++ b/.github/workflows/darwin.yaml @@ -24,6 +24,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: darwin: name: Build Darwin diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 438df5c863a991..175261cef97618 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: ameba: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index b0216522bde2c0..e548aa4259b929 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -26,6 +26,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: bouffalolab: diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index ee76323463763b..aaeaf094910373 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: cc26x2x7: diff --git a/.github/workflows/examples-cc32xx.yaml b/.github/workflows/examples-cc32xx.yaml index c2b86972a294ae..f31cf1e8a20c28 100644 --- a/.github/workflows/examples-cc32xx.yaml +++ b/.github/workflows/examples-cc32xx.yaml @@ -23,6 +23,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: cc32xx: name: cc32xx diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index 4954d9c9af8930..ee4f04e8143846 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: efr32: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index 67872b2f186a79..637c797fe5ad90 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: esp32: diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index f270017b796cdf..b48aafbf4937da 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -26,6 +26,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: infineon: diff --git a/.github/workflows/examples-k32w.yaml b/.github/workflows/examples-k32w.yaml index cea556dbb51dc2..f71f3f26f1ae61 100644 --- a/.github/workflows/examples-k32w.yaml +++ b/.github/workflows/examples-k32w.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: k32w: diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index 17e9562baecb31..b8af253b4923aa 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: arm_crosscompile: diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index 2f9d0a26a297aa..3dd30ed119a7a0 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: imx: diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 6a18a1ab872ff2..f80a4691a7d56f 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: linux_standalone: diff --git a/.github/workflows/examples-mbed.yaml b/.github/workflows/examples-mbed.yaml index a00d7d3a463f97..5f04e7eac1a26d 100644 --- a/.github/workflows/examples-mbed.yaml +++ b/.github/workflows/examples-mbed.yaml @@ -26,6 +26,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: mbedos: diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index 8d7c59bbdc0408..9d64805bcb3b64 100755 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: mw320: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index df8204cb89903e..7f66809a2d9138 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: nrfconnect: diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index 91503e37be7e41..e34b079f2b81d7 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -24,6 +24,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: openiotsdk: name: Open IoT SDK examples building diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index b61da7a91ce0e7..4d929fb36c6b3e 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: qpg: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index f5f1b58a5fbe5b..cf0317c61c190c 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: telink: diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index 5f254879850215..dc6240fe45cbd6 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: tizen: diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index 6b79e4fa1917a9..57160e210dbc84 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -24,6 +24,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: full_android: diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index 9e7b4a4ba76a45..68b62b88d87e12 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -24,6 +24,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: build_linux_fuzzing: diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 85af069b51d8f6..fef2d3e1c8dabf 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -23,6 +23,10 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: code-lints: runs-on: ubuntu-latest @@ -210,4 +214,3 @@ jobs: if: always() run: | git grep -n 'SuccessOrExit(CHIP_ERROR' -- './*' ':(exclude).github/workflows/lint.yml' && exit 1 || exit 0 - diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 2be27598801d6a..b8d68f4a3a243e 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index c19ccaca595ff5..314600d3e588ff 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -21,6 +21,11 @@ on: description: Release Tag required: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: esp32: name: ESP32 diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index c962d705f29627..de1d5ab89e8cfb 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -25,6 +25,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: android: diff --git a/.github/workflows/smoketest-darwin.yaml b/.github/workflows/smoketest-darwin.yaml index 55271cdef05c53..0ab19f6dd92d44 100644 --- a/.github/workflows/smoketest-darwin.yaml +++ b/.github/workflows/smoketest-darwin.yaml @@ -24,6 +24,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: darwin: name: Smoke Run - Darwin diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index b882cce8330dff..4266a3abe945dc 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -28,6 +28,8 @@ concurrency: env: CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 jobs: test_suites_linux: diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 4be57110756b43..22cdb0430bc494 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -21,6 +21,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: zap_regeneration: name: ZAP Regeneration diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index 9eb38e03a8a7e0..60513c863eec92 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -23,6 +23,11 @@ concurrency: group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} cancel-in-progress: true +env: + CHIP_NO_LOG_TIMESTAMPS: true + # XXX: Workaround for https://github.com/actions/cache/issues/1141 + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 3 + jobs: zap_templates: name: ZAP templates generation From 1c06f7a766b8788f3d0d206af530ceb550cf8bcd Mon Sep 17 00:00:00 2001 From: huang zhonghao <132861645+huangzh142@users.noreply.github.com> Date: Fri, 12 May 2023 22:13:57 +0800 Subject: [PATCH 09/36] Add Room Air Conditioner device type definition (#26472) * Add Room Air Conditioner device type definition * Tidy up code in Room Air Conditioner device type definition --- .../zcl/data-model/chip/matter-devices.xml | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml index be554e8e2d2671..8e091aa7f42ecd 100644 --- a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml +++ b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml @@ -1852,6 +1852,33 @@ limitations under the License. + + MA-room-airconditioner + CHIP + Matter Room Air Conditioner + 0x0103 + 0x0072 + + + IDENTIFY_TIME + IDENTIFY_TYPE + Identify + + + ON_OFF + Off + On + Toggle + + + + + + + + + + MA-all-clusters-app CHIP From 567b7979778a0894f1461d090f0acaba70f684d4 Mon Sep 17 00:00:00 2001 From: Karsten Sperling <113487422+ksperling-apple@users.noreply.github.com> Date: Sat, 13 May 2023 02:22:28 +1200 Subject: [PATCH 10/36] Tidy up dependencies of //examples/platform/linux:app-main (#26408) * Remove CommonRpc.h (identical copy of Rpc.h) * Remove some unused GN imports * Run zap_cluster_list.py directly instead of through gn_run_binary.py * Tidy up dependencies of //examples/platform/linux:app-main - Use deps instead of public_deps where possible - Only build shell commands if chip_build_libshell is true - Remove explicit //src/lib/shell dependencies, it's already pulled in by //src/lib * Fix tv-app / tv-casting-app deps and don't import args.gni directly --- .../src/binding-handler.cpp | 18 +++---- .../contact-sensor-common/BUILD.gn | 1 - .../light-switch-common/BUILD.gn | 1 - .../lighting-app/lighting-common/BUILD.gn | 1 - examples/lighting-app/qpg/zap/BUILD.gn | 1 - examples/lock-app/lock-common/BUILD.gn | 1 - examples/lock-app/nxp/zap/BUILD.gn | 1 - examples/lock-app/qpg/zap/BUILD.gn | 1 - examples/platform/linux/AppMain.cpp | 5 +- examples/platform/linux/BUILD.gn | 51 ++++++++----------- examples/platform/linux/CommissionerMain.cpp | 4 -- examples/platform/linux/CommonRpc.h | 27 ---------- examples/platform/nxp/se05x/linux/AppMain.cpp | 2 +- examples/platform/nxp/se05x/linux/BUILD.gn | 2 - examples/tv-app/linux/AppImpl.cpp | 3 -- examples/tv-app/linux/BUILD.gn | 25 ++++----- examples/tv-app/linux/main.cpp | 2 +- examples/tv-casting-app/linux/BUILD.gn | 12 +++-- examples/tv-casting-app/linux/main.cpp | 2 +- src/app/chip_data_model.gni | 14 ++--- 20 files changed, 54 insertions(+), 120 deletions(-) delete mode 100644 examples/platform/linux/CommonRpc.h diff --git a/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp b/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp index 8aff2a6f268bd3..cd16efd4a3f054 100644 --- a/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp @@ -17,17 +17,17 @@ #include "binding-handler.h" -#include "app-common/zap-generated/ids/Clusters.h" -#include "app-common/zap-generated/ids/Commands.h" -#include "app/CommandSender.h" -#include "app/clusters/bindings/BindingManager.h" -#include "app/server/Server.h" -#include "controller/InvokeInteraction.h" -#include "lib/core/CHIPError.h" -#include "platform/CHIPDeviceLayer.h" +#include +#include +#include +#include +#include +#include +#include +#include #if defined(ENABLE_CHIP_SHELL) -#include "lib/shell/Engine.h" +#include // nogncheck using chip::Shell::Engine; using chip::Shell::shell_command_t; diff --git a/examples/contact-sensor-app/contact-sensor-common/BUILD.gn b/examples/contact-sensor-app/contact-sensor-common/BUILD.gn index ddae4d2d0defc5..d95af40a21a3ff 100755 --- a/examples/contact-sensor-app/contact-sensor-common/BUILD.gn +++ b/examples/contact-sensor-app/contact-sensor-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("contact-sensor-common") { diff --git a/examples/light-switch-app/light-switch-common/BUILD.gn b/examples/light-switch-app/light-switch-common/BUILD.gn index 15552d97dcad54..163e841678101a 100644 --- a/examples/light-switch-app/light-switch-common/BUILD.gn +++ b/examples/light-switch-app/light-switch-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("light-switch-common") { diff --git a/examples/lighting-app/lighting-common/BUILD.gn b/examples/lighting-app/lighting-common/BUILD.gn index a7e00eabe34b56..e983b3e0e0f11c 100644 --- a/examples/lighting-app/lighting-common/BUILD.gn +++ b/examples/lighting-app/lighting-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") config("config") { diff --git a/examples/lighting-app/qpg/zap/BUILD.gn b/examples/lighting-app/qpg/zap/BUILD.gn index b62bf14bf03859..ec69db0b412a8c 100644 --- a/examples/lighting-app/qpg/zap/BUILD.gn +++ b/examples/lighting-app/qpg/zap/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("zap") { diff --git a/examples/lock-app/lock-common/BUILD.gn b/examples/lock-app/lock-common/BUILD.gn index 4237883f3fb2b0..bb01a5185f80f7 100644 --- a/examples/lock-app/lock-common/BUILD.gn +++ b/examples/lock-app/lock-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("lock-common") { diff --git a/examples/lock-app/nxp/zap/BUILD.gn b/examples/lock-app/nxp/zap/BUILD.gn index ebb03aadd5a2ab..cc5fe9361c32a3 100644 --- a/examples/lock-app/nxp/zap/BUILD.gn +++ b/examples/lock-app/nxp/zap/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("zap") { diff --git a/examples/lock-app/qpg/zap/BUILD.gn b/examples/lock-app/qpg/zap/BUILD.gn index a0eb662971f4ed..67e29db5f3f249 100644 --- a/examples/lock-app/qpg/zap/BUILD.gn +++ b/examples/lock-app/qpg/zap/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("zap") { diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index d9bdbd5f87bdb2..bdfa8eba2f428e 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -19,7 +19,6 @@ #include #include -#include #include #include #include @@ -53,12 +52,12 @@ #if defined(ENABLE_CHIP_SHELL) #include -#include +#include // nogncheck #include #endif #if defined(PW_RPC_ENABLED) -#include +#include #endif #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED diff --git a/examples/platform/linux/BUILD.gn b/examples/platform/linux/BUILD.gn index 08580aad33c1f5..284a6c6116c579 100644 --- a/examples/platform/linux/BUILD.gn +++ b/examples/platform/linux/BUILD.gn @@ -35,12 +35,8 @@ source_set("app-main") { "AppMain.h", "CommissionableInit.cpp", "CommissionableInit.h", - "CommissioneeShellCommands.cpp", - "CommissioneeShellCommands.h", "CommissionerMain.cpp", "CommissionerMain.h", - "ControllerShellCommands.cpp", - "ControllerShellCommands.h", "LinuxCommissionableDataProvider.cpp", "LinuxCommissionableDataProvider.h", "NamedPipeCommands.cpp", @@ -53,29 +49,32 @@ source_set("app-main") { "testing/CustomCSRResponseOperationalKeyStore.h", ] - defines = [] + public_deps = [ + "${chip_root}/src/lib", + "${chip_root}/src/platform/logging:force_stdio", + ] + deps = [ + ":ota-test-event-trigger", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/app/server", + ] if (chip_enable_pw_rpc) { defines += [ "PW_RPC_ENABLED" ] } + if (chip_build_libshell) { defines += [ "ENABLE_CHIP_SHELL" ] + sources += [ + "CommissioneeShellCommands.cpp", + "CommissioneeShellCommands.h", + "ControllerShellCommands.cpp", + "ControllerShellCommands.h", + ] } - public_deps = [ - ":ota-test-event-trigger", - "${chip_root}/examples/providers:device_info_provider", - "${chip_root}/src/app/server", - "${chip_root}/src/credentials:default_attestation_verifier", - "${chip_root}/src/lib", - "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/shell:shell_core", - "${chip_root}/src/platform/logging:force_stdio", - ] - if (chip_enable_transport_trace) { - public_deps += - [ "${chip_root}/examples/common/tracing:trace_handlers_decoder" ] + deps += [ "${chip_root}/examples/common/tracing:trace_handlers_decoder" ] } public_configs = [ ":app-main-config" ] @@ -88,25 +87,15 @@ source_set("commissioner-main") { "CommissionerMain.h", ] - defines = [] - - if (chip_enable_pw_rpc) { - defines += [ "PW_RPC_ENABLED" ] - } if (chip_build_libshell) { defines += [ "ENABLE_CHIP_SHELL" ] } - public_deps = [ - "${chip_root}/src/app/server", - "${chip_root}/src/credentials:default_attestation_verifier", - "${chip_root}/src/lib", - "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/shell:shell_core", - ] + public_deps = [ "${chip_root}/src/lib" ] + deps = [ "${chip_root}/src/app/server" ] if (chip_enable_transport_trace) { - public_deps += [ "${chip_root}/examples/common/tracing:trace_handlers" ] + deps += [ "${chip_root}/examples/common/tracing:trace_handlers" ] } public_configs = [ ":app-main-config" ] diff --git a/examples/platform/linux/CommissionerMain.cpp b/examples/platform/linux/CommissionerMain.cpp index c2a4e8292455a8..d9c1b5557ebd50 100644 --- a/examples/platform/linux/CommissionerMain.cpp +++ b/examples/platform/linux/CommissionerMain.cpp @@ -55,10 +55,6 @@ #include #include -#if defined(PW_RPC_ENABLED) -#include -#endif - #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED #include "TraceHandlers.h" #endif // CHIP_CONFIG_TRANSPORT_TRACE_ENABLED diff --git a/examples/platform/linux/CommonRpc.h b/examples/platform/linux/CommonRpc.h deleted file mode 100644 index 85495b2bf8fbaf..00000000000000 --- a/examples/platform/linux/CommonRpc.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -namespace chip { -namespace rpc { - -int Init(); - -} // namespace rpc -} // namespace chip diff --git a/examples/platform/nxp/se05x/linux/AppMain.cpp b/examples/platform/nxp/se05x/linux/AppMain.cpp index 1ecf8052100a54..5ae726604a4c8a 100644 --- a/examples/platform/nxp/se05x/linux/AppMain.cpp +++ b/examples/platform/nxp/se05x/linux/AppMain.cpp @@ -60,7 +60,7 @@ #endif #if defined(PW_RPC_ENABLED) -#include +#include #endif #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED diff --git a/examples/platform/nxp/se05x/linux/BUILD.gn b/examples/platform/nxp/se05x/linux/BUILD.gn index 4956883bcec584..52ce3d417617e5 100644 --- a/examples/platform/nxp/se05x/linux/BUILD.gn +++ b/examples/platform/nxp/se05x/linux/BUILD.gn @@ -108,8 +108,6 @@ source_set("commissioner-main") { "${chip_root}/src/app/server", "${chip_root}/src/credentials:default_attestation_verifier", "${chip_root}/src/lib", - "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/shell:shell_core", ] if (chip_enable_transport_trace) { diff --git a/examples/tv-app/linux/AppImpl.cpp b/examples/tv-app/linux/AppImpl.cpp index 9ecb9bcb39d0c4..a07eeadaeb029a 100644 --- a/examples/tv-app/linux/AppImpl.cpp +++ b/examples/tv-app/linux/AppImpl.cpp @@ -32,9 +32,6 @@ #include #include #include -#include -#include -#include #include #include #include diff --git a/examples/tv-app/linux/BUILD.gn b/examples/tv-app/linux/BUILD.gn index 35f4af6c4542d7..c77a4feb75407d 100644 --- a/examples/tv-app/linux/BUILD.gn +++ b/examples/tv-app/linux/BUILD.gn @@ -14,28 +14,16 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("args.gni") - import("${chip_root}/build/chip/tools.gni") +import("${chip_root}/src/lib/lib.gni") assert(chip_build_tools) -config("config") { - include_dirs = [ - ".", - "${chip_root}/zzz_generated/chip-tv-app", - "${chip_root}/src/lib", - ] - - cflags = [ "-Wconversion" ] -} - executable("chip-tv-app") { sources = [ "${chip_root}/examples/tv-app/tv-common/include/CHIPProjectAppConfig.h", "AppImpl.cpp", "AppImpl.h", - "AppPlatformShellCommands.cpp", "ZclCallbacks.cpp", "include/account-login/AccountLoginManager.cpp", "include/account-login/AccountLoginManager.h", @@ -74,11 +62,16 @@ executable("chip-tv-app") { ] cflags = [ "-Wconversion" ] - - public_configs = [ ":config" ] + defines = [] + include_dirs = [ + ".", + "${chip_root}/zzz_generated/chip-tv-app", + "${chip_root}/src/lib", + ] if (chip_build_libshell) { - cflags += [ "-DENABLE_CHIP_SHELL" ] + defines += [ "ENABLE_CHIP_SHELL" ] + sources += [ "AppPlatformShellCommands.cpp" ] } output_dir = root_out_dir diff --git a/examples/tv-app/linux/main.cpp b/examples/tv-app/linux/main.cpp index 31d15a41a8421e..2609d9a2f3c6f4 100644 --- a/examples/tv-app/linux/main.cpp +++ b/examples/tv-app/linux/main.cpp @@ -41,7 +41,7 @@ #include "include/wake-on-lan/WakeOnLanManager.h" #if defined(ENABLE_CHIP_SHELL) -#include +#include // nogncheck #endif using namespace chip; diff --git a/examples/tv-casting-app/linux/BUILD.gn b/examples/tv-casting-app/linux/BUILD.gn index 0f6f12c50dd022..52d8f77cca6f65 100644 --- a/examples/tv-casting-app/linux/BUILD.gn +++ b/examples/tv-casting-app/linux/BUILD.gn @@ -14,17 +14,14 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("args.gni") - import("${chip_root}/build/chip/tools.gni") +import("${chip_root}/src/lib/lib.gni") assert(chip_build_tools) executable("chip-tv-casting-app") { sources = [ "${chip_root}/examples/tv-casting-app/tv-casting-common/include/CHIPProjectAppConfig.h", - "CastingShellCommands.cpp", - "CastingShellCommands.h", "CastingUtils.cpp", "CastingUtils.h", "main.cpp", @@ -39,13 +36,18 @@ executable("chip-tv-casting-app") { "${chip_root}/third_party/jsoncpp", ] + defines = [] include_dirs = [ "${chip_root}/examples/tv-casting-app/tv-casting-common/include" ] cflags = [ "-Wconversion" ] if (chip_build_libshell) { - cflags += [ "-DENABLE_CHIP_SHELL" ] + defines += [ "ENABLE_CHIP_SHELL" ] + sources += [ + "CastingShellCommands.cpp", + "CastingShellCommands.h", + ] } output_dir = root_out_dir diff --git a/examples/tv-casting-app/linux/main.cpp b/examples/tv-casting-app/linux/main.cpp index 6fa224518bedd1..45c53c842568f8 100644 --- a/examples/tv-casting-app/linux/main.cpp +++ b/examples/tv-casting-app/linux/main.cpp @@ -25,7 +25,7 @@ #include "CastingUtils.h" #if defined(ENABLE_CHIP_SHELL) #include "CastingShellCommands.h" -#include +#include // nogncheck #include #endif diff --git a/src/app/chip_data_model.gni b/src/app/chip_data_model.gni index 8b85c353ec7bc2..4fff92c4eaf5ff 100644 --- a/src/app/chip_data_model.gni +++ b/src/app/chip_data_model.gni @@ -15,14 +15,11 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("${chip_root}/build/chip/chip_codegen.gni") -import("${chip_root}/src/platform/python.gni") - import("${chip_root}/src/lib/core/core.gni") +import("${chip_root}/src/platform/python.gni") _app_root = get_path_info(".", "abspath") -_zap_cluster_list_script = get_path_info("zap_cluster_list.py", "abspath") - # Defines a source_set for CHIP data model. # # Arguments: @@ -193,12 +190,9 @@ template("chip_data_model") { ] if (defined(invoker.zap_file)) { - _zap_path = rebase_path(invoker.zap_file, root_build_dir) - _script_path = rebase_path(_zap_cluster_list_script, root_build_dir) - _script_args = [ "--zap_file=" + _zap_path ] - - _cluster_sources = exec_script("${build_root}/gn_run_binary.py", - [ _script_path ] + _script_args, + _zap_file = rebase_path(invoker.zap_file, root_build_dir) + _cluster_sources = exec_script("${_app_root}/zap_cluster_list.py", + [ "--zap_file=" + _zap_file ], "list lines", [ invoker.zap_file ]) } From 176b0e4ba02300ed3b9ed3a396e3428795433edf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Kr=C3=B3lik?= <66667989+Damian-Nordic@users.noreply.github.com> Date: Fri, 12 May 2023 16:23:23 +0200 Subject: [PATCH 11/36] [tools] Second take to fix bloat check (#26544) Apparently, in the previous PR I replaced the deprecated DataFrame.append with pandas.concat, but I didn't realize that our scripts add extra attributes to the data frame, which are not copied during the concatenation. This time, I verified the script locally using --github-comment and --github-dryrun-comment. Also, do not fetch submodules in the bloat check job as it takes most of the job's execution time. --- .github/workflows/bloat_check.yaml | 1 - scripts/tools/memory/gh_report.py | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 99d279c20970c6..01f041cdd0a506 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -41,7 +41,6 @@ jobs: with: action: actions/checkout@v3 with: | - submodules: true token: ${{ github.token }} attempt_limit: 3 attempt_delay: 2000 diff --git a/scripts/tools/memory/gh_report.py b/scripts/tools/memory/gh_report.py index c35c3e53840be4..ddaa23a45e79ba 100755 --- a/scripts/tools/memory/gh_report.py +++ b/scripts/tools/memory/gh_report.py @@ -375,8 +375,10 @@ def merge(df: pd.DataFrame, comment) -> pd.DataFrame: cols, rows = memdf.util.markdown.read_hierified(body) break logging.debug('REC: read %d rows', len(rows)) + attrs = df.attrs df = pd.concat([df, pd.DataFrame(data=rows, columns=cols).astype(df.dtypes)], ignore_index=True) + df.attrs = attrs return df.sort_values( by=['platform', 'target', 'config', 'section']).drop_duplicates() From a6bb71851f00e11491e86b1fbc35e296f84f5f1a Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Fri, 12 May 2023 17:21:02 +0200 Subject: [PATCH 12/36] ESP32: avoid installing gdbgui when not needed (#26542) ESP-IDF v4.4.4 requires gdbgui only when Python before 3.11 is used (see https://github.com/espressif/esp-idf/commit/3974be7fec1ea6c529ecbee795c0152b42b61d55). Avoid installing it when not needed. Fixes: #25385 --- scripts/setup/requirements.esp32.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/setup/requirements.esp32.txt b/scripts/setup/requirements.esp32.txt index d846ba4de30f5c..b9b2ddf6afa96d 100644 --- a/scripts/setup/requirements.esp32.txt +++ b/scripts/setup/requirements.esp32.txt @@ -9,4 +9,4 @@ ecdsa>=0.16.0 kconfiglib==13.7.1 construct==2.10.54 python-socketio<5 -gdbgui==0.13.2.0 ; platform_machine != 'aarch64' and sys_platform == 'linux' +gdbgui==0.13.2.0 ; python_version < "3.11" and platform_machine != 'aarch64' and sys_platform == 'linux' From 1620094767f8fe9233bae22f6ad00c4fe8b0a5e7 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 12 May 2023 14:18:45 -0400 Subject: [PATCH 13/36] Stop validating certificate lifetimes in Matter.framework. (#26546) --- .../CHIP/MTRDeviceControllerFactory.mm | 13 + .../CHIPTests/MTRCertificateValidityTests.m | 323 ++++++++++++++++++ .../Matter.xcodeproj/project.pbxproj | 4 + 3 files changed, 340 insertions(+) create mode 100644 src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index ada02b3817529b..93f7abeb91a979 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -57,6 +57,7 @@ static NSString * const kErrorDACVerifierInit = @"Init failure while creating the device attestation verifier"; static NSString * const kErrorGroupProviderInit = @"Init failure while initializing group data provider"; static NSString * const kErrorControllersInit = @"Init controllers array failure"; +static NSString * const kErrorCertificateValidityPolicyInit = @"Init certificate validity policy failure"; static NSString * const kErrorControllerFactoryInit = @"Init failure while initializing controller factory"; static NSString * const kErrorKeystoreInit = @"Init failure while initializing persistent storage keystore"; static NSString * const kErrorCertStoreInit = @"Init failure while initializing persistent storage operational certificate store"; @@ -86,6 +87,7 @@ @interface MTRDeviceControllerFactory () @property (readonly) MTROperationalBrowser * operationalBrowser; @property () chip::Credentials::DeviceAttestationVerifier * deviceAttestationVerifier; @property (readonly) BOOL advertiseOperational; +@property (nonatomic, readonly) Credentials::IgnoreCertificateValidityPeriodPolicy * certificateValidityPolicy; - (BOOL)findMatchingFabric:(FabricTable &)fabricTable params:(MTRDeviceControllerStartupParams *)params @@ -150,6 +152,11 @@ - (instancetype)init return nil; } + _certificateValidityPolicy = new Credentials::IgnoreCertificateValidityPeriodPolicy(); + if ([self checkForInitError:(_certificateValidityPolicy != nil) logMsg:kErrorCertificateValidityPolicyInit]) { + return nil; + } + return self; } @@ -204,6 +211,11 @@ - (void)cleanupInitObjects delete _sessionKeystore; _sessionKeystore = nullptr; } + + if (_certificateValidityPolicy) { + delete _certificateValidityPolicy; + _certificateValidityPolicy = nullptr; + } } - (void)cleanupStartupObjects @@ -443,6 +455,7 @@ - (BOOL)startControllerFactory:(MTRDeviceControllerFactoryParams *)startupParams params.fabricIndependentStorage = _persistentStorageDelegateBridge; params.operationalKeystore = _keystore; params.opCertStore = _opCertStore; + params.certificateValidityPolicy = _certificateValidityPolicy; errorCode = _controllerFactory->Init(params); if (errorCode != CHIP_NO_ERROR) { MTR_LOG_ERROR("Error: %@", kErrorControllerFactoryInit); diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m new file mode 100644 index 00000000000000..34fd5d5814d254 --- /dev/null +++ b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m @@ -0,0 +1,323 @@ +/* + * + * 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. + */ + +// module headers +#import + +#import "MTRErrorTestUtils.h" +#import "MTRTestKeys.h" +#import "MTRTestResetCommissioneeHelper.h" +#import "MTRTestStorage.h" + +// system dependencies +#import + +static const uint16_t kPairingTimeoutInSeconds = 10; +static const uint16_t kTimeoutInSeconds = 3; +static const uint64_t kDeviceId = 0x12341234; +static const uint64_t kControllerId = 0x56788765; +static NSString * kOnboardingPayload = @"MT:-24J0AFN00KA0648G00"; +static const uint16_t kLocalPort = 5541; +static const uint16_t kTestVendorId = 0xFFF1u; + +static MTRBaseDevice * sConnectedDevice; + +// Singleton controller we use. +static MTRDeviceController * sController = nil; + +@interface MTRCertificateValidityTestControllerDelegate : NSObject +@property (nonatomic, readonly) XCTestExpectation * expectation; +@property (nonatomic, readonly) NSNumber * commissioneeNodeID; +@end + +@implementation MTRCertificateValidityTestControllerDelegate +- (id)initWithExpectation:(XCTestExpectation *)expectation commissioneeNodeID:(NSNumber *)nodeID +{ + self = [super init]; + if (self) { + _expectation = expectation; + _commissioneeNodeID = nodeID; + } + return self; +} + +- (void)controller:(MTRDeviceController *)controller commissioningSessionEstablishmentDone:(NSError * _Nullable)error +{ + XCTAssertEqual(error.code, 0); + + NSError * commissionError = nil; + [sController commissionNodeWithID:self.commissioneeNodeID + commissioningParams:[[MTRCommissioningParameters alloc] init] + error:&commissionError]; + XCTAssertNil(commissionError); + + // Keep waiting for onCommissioningComplete +} + +- (void)controller:(MTRDeviceController *)controller commissioningComplete:(NSError *)error +{ + XCTAssertEqual(error.code, 0); + [_expectation fulfill]; + _expectation = nil; +} +@end + +@interface MTRTestCertificateIssuer : NSObject + +@property (nonatomic, readonly) MTRTestKeys * rootKey; +@property (nonatomic, copy, readonly) MTRCertificateDERBytes rootCertificate; +@property (nonatomic, copy, readonly) NSDateInterval * validityPeriod; +@property (nonatomic, copy, readonly) NSNumber * fabricID; +@property (nonatomic, readonly) BOOL shouldSkipAttestationCertificateValidation; + +- (nullable instancetype)initWithRootKey:(MTRTestKeys *)key + fabricID:(NSNumber *)fabricID + validityPeriod:(NSDateInterval *)validityPeriod; + +- (nullable MTRCertificateDERBytes)issueOperationalCertificateForNode:(NSNumber *)nodeID + operationalPublicKey:(SecKeyRef)operationalPublicKey; + +- (void)issueOperationalCertificateForRequest:(MTROperationalCSRInfo *)csrInfo + attestationInfo:(MTRDeviceAttestationInfo *)attestationInfo + controller:(MTRDeviceController *)controller + completion:(void (^)(MTROperationalCertificateChain * _Nullable info, + NSError * _Nullable error))completion; +@end + +@implementation MTRTestCertificateIssuer +- (nullable instancetype)initWithRootKey:(MTRTestKeys *)key + fabricID:(NSNumber *)fabricID + validityPeriod:(NSDateInterval *)validityPeriod +{ + if (!(self = [super init])) { + return nil; + } + + NSError * error; + __auto_type * rootCertificate = [MTRCertificates createRootCertificate:key + issuerID:nil + fabricID:fabricID + validityPeriod:validityPeriod + error:&error]; + XCTAssertNil(error); + XCTAssertNotNil(rootCertificate); + + if (rootCertificate == nil) { + return nil; + } + + _validityPeriod = validityPeriod; + _rootCertificate = rootCertificate; + _rootKey = key; + _fabricID = fabricID; + _shouldSkipAttestationCertificateValidation = NO; + + return self; +} + +- (nullable MTRCertificateDERBytes)issueOperationalCertificateForNode:(NSNumber *)nodeID + operationalPublicKey:(SecKeyRef)operationalPublicKey +{ + return [MTRCertificates createOperationalCertificate:self.rootKey + signingCertificate:self.rootCertificate + operationalPublicKey:operationalPublicKey + fabricID:self.fabricID + nodeID:nodeID + caseAuthenticatedTags:nil + validityPeriod:self.validityPeriod + error:nil]; +} + +- (void)issueOperationalCertificateForRequest:(MTROperationalCSRInfo *)csrInfo + attestationInfo:(MTRDeviceAttestationInfo *)attestationInfo + controller:(MTRDeviceController *)controller + completion:(void (^)(MTROperationalCertificateChain * _Nullable info, + NSError * _Nullable error))completion +{ + NSError * error; + __auto_type * publicKey = [MTRCertificates publicKeyFromCSR:csrInfo.csr error:&error]; + XCTAssertNil(error); + XCTAssertNotNil(publicKey); + + NSDictionary * attributes = + @{ (id) kSecAttrKeyType : (id) kSecAttrKeyTypeECSECPrimeRandom, (id) kSecAttrKeyClass : (id) kSecAttrKeyClassPublic }; + CFErrorRef keyCreationError = NULL; + SecKeyRef operationalPublicKey + = SecKeyCreateWithData((__bridge CFDataRef) publicKey, (__bridge CFDictionaryRef) attributes, &keyCreationError); + XCTAssertNotNil((__bridge id) operationalPublicKey); + XCTAssertNil((__bridge id) keyCreationError); + + __auto_type * operationalCertificate = [self issueOperationalCertificateForNode:@(kDeviceId) + operationalPublicKey:operationalPublicKey]; + XCTAssertNotNil(operationalCertificate); + + __auto_type * certChain = [[MTROperationalCertificateChain alloc] initWithOperationalCertificate:operationalCertificate + intermediateCertificate:nil + rootCertificate:self.rootCertificate + adminSubject:nil]; + XCTAssertNotNil(certChain); + completion(certChain, nil); +} +@end + +@interface MTRTestExpiredCertificateIssuer : MTRTestCertificateIssuer + +- (nullable instancetype)initWithRootKey:(MTRTestKeys *)key fabricID:(NSNumber *)fabricID; + +@end + +@implementation MTRTestExpiredCertificateIssuer +- (nullable instancetype)initWithRootKey:(MTRTestKeys *)key fabricID:(NSNumber *)fabricID +{ + // Ensure oldDate is before newDate and both are in the past. + __auto_type * oldDate = [NSDate dateWithTimeIntervalSinceNow:-5]; + __auto_type * newDate = [NSDate dateWithTimeIntervalSinceNow:-2]; + __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:oldDate endDate:newDate]; + + return [super initWithRootKey:key fabricID:fabricID validityPeriod:validityPeriod]; +} + +@end + +@interface MTRCertificateValidityTests : XCTestCase +@end + +static BOOL sNeedsStackShutdown = YES; + +@implementation MTRCertificateValidityTests + ++ (void)tearDown +{ + // Global teardown, runs once + if (sNeedsStackShutdown) { + // We don't need to worry about ResetCommissionee. If we get here, + // we're running only one of our test methods (using + // -only-testing:MatterTests/MTROTAProviderTests/testMethodName), since + // we did not run test999_TearDown. + [self shutdownStack]; + } +} + +- (void)setUp +{ + // Per-test setup, runs before each test. + [super setUp]; + [self setContinueAfterFailure:NO]; +} + +- (MTRBaseDevice *)commissionDeviceWithPayload:(NSString *)payloadString nodeID:(NSNumber *)nodeID +{ + XCTestExpectation * expectation = + [self expectationWithDescription:[NSString stringWithFormat:@"Commissioning Complete for %@", nodeID]]; + __auto_type * deviceControllerDelegate = [[MTRCertificateValidityTestControllerDelegate alloc] initWithExpectation:expectation + commissioneeNodeID:nodeID]; + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.device_controller_delegate", DISPATCH_QUEUE_SERIAL); + + [sController setDeviceControllerDelegate:deviceControllerDelegate queue:callbackQueue]; + + NSError * error; + __auto_type * payload = [MTRSetupPayload setupPayloadWithOnboardingPayload:payloadString error:&error]; + XCTAssertNotNil(payload); + XCTAssertNil(error); + + [sController setupCommissioningSessionWithPayload:payload newNodeID:nodeID error:&error]; + XCTAssertNil(error); + + [self waitForExpectations:@[ expectation ] timeout:kPairingTimeoutInSeconds]; + + return [MTRBaseDevice deviceWithNodeID:nodeID controller:sController]; +} + +- (void)initStack:(MTRTestCertificateIssuer *)certificateIssuer +{ + __auto_type * factory = [MTRDeviceControllerFactory sharedInstance]; + XCTAssertNotNil(factory); + + __auto_type * storage = [[MTRTestStorage alloc] init]; + + __auto_type * factoryParams = [[MTRDeviceControllerFactoryParams alloc] initWithStorage:storage]; + factoryParams.port = @(kLocalPort); + factoryParams.shouldStartServer = YES; + + BOOL ok = [factory startControllerFactory:factoryParams error:nil]; + XCTAssertTrue(ok); + + __auto_type * controllerOperationalKeys = [[MTRTestKeys alloc] init]; + XCTAssertNotNil(controllerOperationalKeys); + + __auto_type * controllerOperationalCert = + [certificateIssuer issueOperationalCertificateForNode:@(kControllerId) + operationalPublicKey:controllerOperationalKeys.publicKey]; + XCTAssertNotNil(controllerOperationalCert); + + __auto_type * params = [[MTRDeviceControllerStartupParams alloc] initWithIPK:certificateIssuer.rootKey.ipk + operationalKeypair:controllerOperationalKeys + operationalCertificate:controllerOperationalCert + intermediateCertificate:nil + rootCertificate:certificateIssuer.rootCertificate]; + XCTAssertNotNil(params); + + params.vendorID = @(kTestVendorId); + params.operationalCertificateIssuer = certificateIssuer; + params.operationalCertificateIssuerQueue = dispatch_get_main_queue(); + + MTRDeviceController * controller = [factory createControllerOnNewFabric:params error:nil]; + XCTAssertNotNil(controller); + + sController = controller; + + sConnectedDevice = [self commissionDeviceWithPayload:kOnboardingPayload nodeID:@(kDeviceId)]; +} + ++ (void)shutdownStack +{ + sNeedsStackShutdown = NO; + + MTRDeviceController * controller = sController; + [controller shutdown]; + XCTAssertFalse([controller isRunning]); + + [[MTRDeviceControllerFactory sharedInstance] stopControllerFactory]; +} + +- (void)test001_TestExpiredCertificates +{ + __auto_type * testKeys = [[MTRTestKeys alloc] init]; + XCTAssertNotNil(testKeys); + + __auto_type * certificateIssuer = [[MTRTestExpiredCertificateIssuer alloc] initWithRootKey:testKeys fabricID:@(1)]; + XCTAssertNotNil(certificateIssuer); + + [self initStack:certificateIssuer]; + + XCTestExpectation * toggleExpectation = [self expectationWithDescription:@"Toggle command executed"]; + + __auto_type * onOffCluster = [[MTRBaseClusterOnOff alloc] initWithDevice:sConnectedDevice + endpointID:@(1) + queue:dispatch_get_main_queue()]; + [onOffCluster toggleWithCompletion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [toggleExpectation fulfill]; + }]; + [self waitForExpectations:@[ toggleExpectation ] timeout:kTimeoutInSeconds]; + + ResetCommissionee(sConnectedDevice, dispatch_get_main_queue(), self, kTimeoutInSeconds); + + [[self class] shutdownStack]; +} + +@end diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 2561d02229b67b..406bd64a9552f8 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -132,6 +132,7 @@ 511913FB28C100EF009235E9 /* MTRBaseSubscriptionCallback.mm in Sources */ = {isa = PBXBuildFile; fileRef = 511913F928C100EF009235E9 /* MTRBaseSubscriptionCallback.mm */; }; 511913FC28C100EF009235E9 /* MTRBaseSubscriptionCallback.h in Headers */ = {isa = PBXBuildFile; fileRef = 511913FA28C100EF009235E9 /* MTRBaseSubscriptionCallback.h */; }; 5129BCFD26A9EE3300122DDF /* MTRError.h in Headers */ = {isa = PBXBuildFile; fileRef = 5129BCFC26A9EE3300122DDF /* MTRError.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 51339B1F2A0DA64D00C798C1 /* MTRCertificateValidityTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 51339B1E2A0DA64D00C798C1 /* MTRCertificateValidityTests.m */; }; 5136661328067D550025EDAE /* MTRDeviceController_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 5136660F28067D540025EDAE /* MTRDeviceController_Internal.h */; }; 5136661428067D550025EDAE /* MTRDeviceControllerFactory.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5136661028067D540025EDAE /* MTRDeviceControllerFactory.mm */; }; 5136661528067D550025EDAE /* MTRDeviceControllerFactory_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 5136661128067D540025EDAE /* MTRDeviceControllerFactory_Internal.h */; }; @@ -418,6 +419,7 @@ 511913F928C100EF009235E9 /* MTRBaseSubscriptionCallback.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRBaseSubscriptionCallback.mm; sourceTree = ""; }; 511913FA28C100EF009235E9 /* MTRBaseSubscriptionCallback.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRBaseSubscriptionCallback.h; sourceTree = ""; }; 5129BCFC26A9EE3300122DDF /* MTRError.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRError.h; sourceTree = ""; }; + 51339B1E2A0DA64D00C798C1 /* MTRCertificateValidityTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MTRCertificateValidityTests.m; sourceTree = ""; }; 5136660F28067D540025EDAE /* MTRDeviceController_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRDeviceController_Internal.h; sourceTree = ""; }; 5136661028067D540025EDAE /* MTRDeviceControllerFactory.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDeviceControllerFactory.mm; sourceTree = ""; }; 5136661128067D540025EDAE /* MTRDeviceControllerFactory_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRDeviceControllerFactory_Internal.h; sourceTree = ""; }; @@ -1060,6 +1062,7 @@ 51742B4D29CB6B88009974FE /* MTRPairingTests.m */, 5142E39729D377F000A206F0 /* MTROTAProviderTests.m */, 51A2F1312A00402A00F03298 /* MTRDataValueParserTests.m */, + 51339B1E2A0DA64D00C798C1 /* MTRCertificateValidityTests.m */, B202529D2459E34F00F97062 /* Info.plist */, ); path = CHIPTests; @@ -1458,6 +1461,7 @@ 99C65E10267282F1003402F6 /* MTRControllerTests.m in Sources */, 1E5801C328941C050033A199 /* MTRTestOTAProvider.m in Sources */, 5A6FEC9D27B5E48900F25F42 /* MTRXPCProtocolTests.m in Sources */, + 51339B1F2A0DA64D00C798C1 /* MTRCertificateValidityTests.m in Sources */, 5173A47929C0E82300F67F48 /* MTRFabricInfoTests.m in Sources */, 3D0C484B29DA4FA0006D811F /* MTRErrorTests.m in Sources */, 51742B4A29CB5FC1009974FE /* MTRTestResetCommissioneeHelper.m in Sources */, From 647dba44058665cfd836f88b616aa92def07cbfb Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Fri, 12 May 2023 20:40:03 +0200 Subject: [PATCH 14/36] [chiptool.py] Make sure to update the exit code properly if parsing fails (#26539) --- .../py_matter_yamltests/matter_yamltests/parser_builder.py | 6 +++--- scripts/py_matter_yamltests/matter_yamltests/runner.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/py_matter_yamltests/matter_yamltests/parser_builder.py b/scripts/py_matter_yamltests/matter_yamltests/parser_builder.py index 72ebae6a1fff8f..2305900d5a1435 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/parser_builder.py +++ b/scripts/py_matter_yamltests/matter_yamltests/parser_builder.py @@ -66,7 +66,7 @@ def __init__(self, config: TestParserBuilderConfig = TestParserBuilderConfig()): self.__tests = copy.copy(config.tests) self.__config = config self.__duration = 0 - self.__done = False + self.done = False def __iter__(self): self.__config.hooks.start(len(self.__tests)) @@ -76,9 +76,9 @@ def __next__(self): if len(self.__tests): return self.__get_test_parser(self.__tests.pop(0)) - if not self.__done: + if not self.done: self.__config.hooks.stop(round(self.__duration)) - self.__done = True + self.done = True raise StopIteration diff --git a/scripts/py_matter_yamltests/matter_yamltests/runner.py b/scripts/py_matter_yamltests/matter_yamltests/runner.py index fe4a091bc9676f..f87f94d53dc993 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/runner.py +++ b/scripts/py_matter_yamltests/matter_yamltests/runner.py @@ -155,7 +155,7 @@ def run(self, parser_builder_config: TestParserBuilderConfig, runner_config: Tes duration = round((time.time() - start) * 1000) runner_config.hooks.stop(duration) - return True + return parser_builder.done async def _run(self, parser: TestParser, config: TestRunnerConfig): status = True From fcf58d3b966ad7f105253cf4ed9d642ff99d7b53 Mon Sep 17 00:00:00 2001 From: joonhaengHeo <85541460+joonhaengHeo@users.noreply.github.com> Date: Sat, 13 May 2023 03:58:04 +0900 Subject: [PATCH 15/36] [Android] Implement pairing with code API (#26324) * Add pairWithCode API in Android * restyle * fix build error * Add java controller function --- .../com/google/chip/chiptool/ChipClient.kt | 2 +- .../controller/commands/common/Argument.kt | 17 + .../commands/pairing/PairCodeCommand.kt | 12 +- .../commands/pairing/PairCodeThreadCommand.kt | 12 +- .../commands/pairing/PairCodeWifiCommand.kt | 12 +- .../commands/pairing/PairingCommand.kt | 17 + .../java/CHIPDeviceController-JNI.cpp | 36 ++ .../ChipDeviceController.java | 24 + .../android/AndroidChipPlatform-JNI.cpp | 5 + src/platform/android/BLEManagerImpl.cpp | 22 +- src/platform/android/BLEManagerImpl.h | 3 + src/platform/android/BUILD.gn | 2 + .../android/BleConnectCallback-JNI.cpp | 54 ++ src/platform/android/BleConnectCallback-JNI.h | 29 ++ .../java/chip/platform/AndroidBleManager.java | 460 ++++++++++++++---- .../chip/platform/BleConnectCallback.java | 40 ++ .../java/chip/platform/BleManager.java | 3 +- 17 files changed, 642 insertions(+), 108 deletions(-) create mode 100644 src/platform/android/BleConnectCallback-JNI.cpp create mode 100644 src/platform/android/BleConnectCallback-JNI.h create mode 100644 src/platform/android/java/chip/platform/BleConnectCallback.java diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt index add408b7af9693..84a14de4714e13 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt @@ -61,7 +61,7 @@ object ChipClient { if (!this::androidPlatform.isInitialized && context != null) { //force ChipDeviceController load jni ChipDeviceController.loadJni() - androidPlatform = AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), NsdManagerServiceBrowser(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context)) + androidPlatform = AndroidChipPlatform(AndroidBleManager(context), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), NsdManagerServiceBrowser(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context)) } return androidPlatform diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt index 76e633a82a144a..77aa91a89aa31d 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt @@ -141,6 +141,23 @@ class Argument { isValidArgument = numLong.toInt() >= minValue && numLong.toInt() <= maxValue } + ArgumentType.STRING -> { + val stringBuffer = this.value as StringBuffer + stringBuffer.append(value) + val str = stringBuffer.toString() + isValidArgument = value == str + } + + ArgumentType.BOOL -> { + val atomicBoolean = this.value as AtomicBoolean + try { + atomicBoolean.set(value.toBoolean()) + isValidArgument = true + } catch (e: Exception) { + isValidArgument = false + } + } + ArgumentType.ADDRESS -> isValidArgument = try { val ipAddress = this.value as IPAddress ipAddress.setAddress(InetAddress.getByName(value)) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt index 7f2bc51e5ffb4a..bf6e18cceedafd 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt @@ -22,5 +22,15 @@ import com.matter.controller.commands.common.CredentialsIssuer class PairCodeCommand(controller: ChipDeviceController, credsIssue: CredentialsIssuer?) : PairingCommand(controller, "code", credsIssue, PairingModeType.CODE, PairingNetworkType.NONE) { - override fun runCommand() {} + override fun runCommand() { + currentCommissioner() + .pairDeviceWithCode( + getNodeId(), + getOnboardingPayload(), + null, + getWifiNetworkCredentials(), + ) + currentCommissioner().setCompletionListener(this) + waitCompleteMs(getTimeoutMillis()) + } } \ No newline at end of file diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt index 2cd822e32d467f..419525733c496a 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt @@ -22,5 +22,15 @@ import com.matter.controller.commands.common.CredentialsIssuer class PairCodeThreadCommand(controller: ChipDeviceController, credsIssue: CredentialsIssuer?) : PairingCommand(controller, "code-thread", credsIssue, PairingModeType.CODE, PairingNetworkType.THREAD) { - override fun runCommand() {} + override fun runCommand() { + currentCommissioner() + .pairDeviceWithCode( + getNodeId(), + getOnboardingPayload(), + null, + getThreadNetworkCredentials(), + ) + currentCommissioner().setCompletionListener(this) + waitCompleteMs(getTimeoutMillis()) + } } \ No newline at end of file diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt index 66f90fd7214cf9..ffecb2e9529df8 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt @@ -22,5 +22,15 @@ import com.matter.controller.commands.common.CredentialsIssuer class PairCodeWifiCommand(controller: ChipDeviceController, credsIssue: CredentialsIssuer?) : PairingCommand(controller, "code-wifi", credsIssue, PairingModeType.CODE, PairingNetworkType.WIFI) { - override fun runCommand() {} + override fun runCommand() { + currentCommissioner() + .pairDeviceWithCode( + getNodeId(), + getOnboardingPayload(), + null, + getWifiNetworkCredentials(), + ) + currentCommissioner().setCompletionListener(this) + waitCompleteMs(getTimeoutMillis()) + } } \ No newline at end of file diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt index a6df1b0b450f6a..e7f90832d0c25c 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt @@ -18,6 +18,7 @@ package com.matter.controller.commands.pairing import chip.devicecontroller.ChipDeviceController +import chip.devicecontroller.NetworkCredentials import com.matter.controller.commands.common.CredentialsIssuer import com.matter.controller.commands.common.IPAddress import com.matter.controller.commands.common.MatterCommand @@ -227,6 +228,22 @@ abstract class PairingCommand( return timeoutMillis.get() } + fun getOnboardingPayload(): String { + return onboardingPayload.toString() + } + + fun getWifiNetworkCredentials(): NetworkCredentials { + return NetworkCredentials.forWiFi(NetworkCredentials.WiFiCredentials(ssid.toString(), password.toString())) + } + + fun getThreadNetworkCredentials(): NetworkCredentials { + return NetworkCredentials.forThread(NetworkCredentials.ThreadCredentials(operationalDataset.toString().hexToByteArray())) + } + + private fun String.hexToByteArray(): ByteArray { + return chunked(2).map { byteStr -> byteStr.toUByte(16).toByte() }.toByteArray() + } + companion object { private val logger = Logger.getLogger(PairingCommand::class.java.name) } diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index b12d31b7d81ca5..9b40721795d0a4 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -653,6 +653,42 @@ JNI_METHOD(void, pairDeviceWithAddress) } } +JNI_METHOD(void, pairDeviceWithCode) +(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jstring setUpCode, jbyteArray csrNonce, jobject networkCredentials) +{ + chip::DeviceLayer::StackLock lock; + CHIP_ERROR err = CHIP_NO_ERROR; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + ChipLogProgress(Controller, "pairDeviceWithCode() called"); + + JniUtfString setUpCodeJniString(env, setUpCode); + + CommissioningParameters commissioningParams = wrapper->GetCommissioningParameters(); + if (csrNonce != nullptr) + { + JniByteArray jniCsrNonce(env, csrNonce); + commissioningParams.SetCSRNonce(jniCsrNonce.byteSpan()); + } + + if (networkCredentials != nullptr) + { + wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); + } + + if (wrapper->GetDeviceAttestationDelegateBridge() != nullptr) + { + commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); + } + err = wrapper->Controller()->PairDevice(deviceId, setUpCodeJniString.c_str(), commissioningParams, DiscoveryType::kAll); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to pair the device."); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } +} + JNI_METHOD(void, establishPaseConnection)(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jint connObj, jlong pinCode) { chip::DeviceLayer::StackLock lock; diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 652e53c038bfaa..ed8e09873fc02e 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -175,6 +175,23 @@ public void pairDeviceWithAddress( deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce); } + /** + * Pair a device connected using the scanned QR code or manual entry code. + * + * @param deviceId the node ID to assign to the device + * @param setupCode the scanned QR code or manual entry code + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly + * generated CSR nonce. + * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned + */ + public void pairDeviceWithCode( + long deviceId, + String setupCode, + @Nullable byte[] csrNonce, + @Nullable NetworkCredentials networkCredentials) { + pairDeviceWithCode(deviceControllerPtr, deviceId, setupCode, csrNonce, networkCredentials); + } + public void establishPaseConnection(long deviceId, int connId, long setupPincode) { if (connectionId == 0) { connectionId = connId; @@ -996,6 +1013,13 @@ private native void pairDeviceWithAddress( long pinCode, @Nullable byte[] csrNonce); + private native void pairDeviceWithCode( + long deviceControllerPtr, + long deviceId, + String setupCode, + @Nullable byte[] csrNonce, + @Nullable NetworkCredentials networkCredentials); + private native void establishPaseConnection( long deviceControllerPtr, long deviceId, int connId, long setupPincode); diff --git a/src/platform/android/AndroidChipPlatform-JNI.cpp b/src/platform/android/AndroidChipPlatform-JNI.cpp index f86482994cb308..b8fc9409636011 100644 --- a/src/platform/android/AndroidChipPlatform-JNI.cpp +++ b/src/platform/android/AndroidChipPlatform-JNI.cpp @@ -37,6 +37,7 @@ #include "AndroidChipPlatform-JNI.h" #include "BLEManagerImpl.h" +#include "BleConnectCallback-JNI.h" #include "CommissionableDataProviderImpl.h" #include "DiagnosticDataProviderImpl.h" #include "DnssdImpl.h" @@ -84,6 +85,9 @@ CHIP_ERROR AndroidChipPlatformJNI_OnLoad(JavaVM * jvm, void * reserved) SuccessOrExit(err); ChipLogProgress(DeviceLayer, "Java class references loaded."); + err = BleConnectCallbackJNI_OnLoad(jvm, reserved); + SuccessOrExit(err); + chip::InitializeTracing(); exit: @@ -99,6 +103,7 @@ CHIP_ERROR AndroidChipPlatformJNI_OnLoad(JavaVM * jvm, void * reserved) void AndroidChipPlatformJNI_OnUnload(JavaVM * jvm, void * reserved) { ChipLogProgress(DeviceLayer, "AndroidChipPlatform JNI_OnUnload() called"); + BleConnectCallbackJNI_OnUnload(jvm, reserved); chip::Platform::MemoryShutdown(); } diff --git a/src/platform/android/BLEManagerImpl.cpp b/src/platform/android/BLEManagerImpl.cpp index f2068dc5da7eb3..e811230c8638a6 100644 --- a/src/platform/android/BLEManagerImpl.cpp +++ b/src/platform/android/BLEManagerImpl.cpp @@ -125,7 +125,7 @@ void BLEManagerImpl::InitializeWithObject(jobject manager) env->ExceptionClear(); } - mOnNewConnectionMethod = env->GetMethodID(BLEManagerClass, "onNewConnection", "(I)V"); + mOnNewConnectionMethod = env->GetMethodID(BLEManagerClass, "onNewConnection", "(IZJJ)V"); if (mOnNewConnectionMethod == nullptr) { ChipLogError(DeviceLayer, "Failed to access BLEManager 'onNewConnection' method"); @@ -186,16 +186,19 @@ bool BLEManagerImpl::_IsAdvertising() CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) { + ChipLogDetail(DeviceLayer, "%s, %u", __FUNCTION__, static_cast(mode)); return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) { + ChipLogDetail(DeviceLayer, "%s, %s", __FUNCTION__, buf); return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { + ChipLogDetail(DeviceLayer, "%s, %s", __FUNCTION__, deviceName); return CHIP_ERROR_NOT_IMPLEMENTED; } @@ -449,6 +452,18 @@ void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) // ===== start implement virtual methods on BleConnectionDelegate. +void BLEManagerImpl::OnConnectSuccess(void * appState, BLE_CONNECTION_OBJECT connObj) +{ + chip::DeviceLayer::StackLock lock; + BleConnectionDelegate::OnConnectionComplete(appState, connObj); +} + +void BLEManagerImpl::OnConnectFailed(void * appState, CHIP_ERROR err) +{ + chip::DeviceLayer::StackLock lock; + BleConnectionDelegate::OnConnectionError(appState, err); +} + void BLEManagerImpl::NewConnection(BleLayer * bleLayer, void * appState, const SetupDiscriminator & connDiscriminator) { chip::DeviceLayer::StackUnlock unlock; @@ -474,7 +489,10 @@ void BLEManagerImpl::NewConnection(BleLayer * bleLayer, void * appState, const S { discriminator = connDiscriminator.GetLongValue(); } - env->CallVoidMethod(mBLEManagerObject, mOnNewConnectionMethod, static_cast(discriminator)); + + env->CallVoidMethod(mBLEManagerObject, mOnNewConnectionMethod, static_cast(discriminator), + static_cast(connDiscriminator.IsShortDiscriminator()), reinterpret_cast(this), + reinterpret_cast(appState)); VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); exit: diff --git a/src/platform/android/BLEManagerImpl.h b/src/platform/android/BLEManagerImpl.h index 4d6a6bf94613e9..57fe6e9a0ca217 100644 --- a/src/platform/android/BLEManagerImpl.h +++ b/src/platform/android/BLEManagerImpl.h @@ -52,6 +52,9 @@ class BLEManagerImpl final : public BLEManager, void InitializeWithObject(jobject managerObject); + void OnConnectSuccess(void * appState, BLE_CONNECTION_OBJECT connObj); + void OnConnectFailed(void * appState, CHIP_ERROR err); + private: // ===== Members that implement the BLEManager internal interface. diff --git a/src/platform/android/BUILD.gn b/src/platform/android/BUILD.gn index 8c49d86050aa87..05ab96b3e5258f 100644 --- a/src/platform/android/BUILD.gn +++ b/src/platform/android/BUILD.gn @@ -34,6 +34,7 @@ static_library("android") { "AndroidConfig.h", "BLEManagerImpl.cpp", "BLEManagerImpl.h", + "BleConnectCallback-JNI.cpp", "BlePlatformConfig.h", "CHIPDevicePlatformEvent.h", "CHIPP256KeypairBridge.cpp", @@ -81,6 +82,7 @@ android_library("java") { "java/chip/platform/AndroidChipPlatform.java", "java/chip/platform/AndroidChipPlatformException.java", "java/chip/platform/BleCallback.java", + "java/chip/platform/BleConnectCallback.java", "java/chip/platform/BleManager.java", "java/chip/platform/ChipMdnsCallback.java", "java/chip/platform/ChipMdnsCallbackImpl.java", diff --git a/src/platform/android/BleConnectCallback-JNI.cpp b/src/platform/android/BleConnectCallback-JNI.cpp new file mode 100644 index 00000000000000..fac0e255075b97 --- /dev/null +++ b/src/platform/android/BleConnectCallback-JNI.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023 Project CHIP Authors + * All rights reserved. + * + * 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 "BLEManagerImpl.h" + +using namespace chip; +using namespace chip::DeviceLayer::Internal; + +#define JNI_METHOD(RETURN, METHOD_NAME) extern "C" JNIEXPORT RETURN JNICALL Java_chip_platform_BleConnectCallback_##METHOD_NAME + +CHIP_ERROR BleConnectCallbackJNI_OnLoad(JavaVM * jvm, void * reserved) +{ + ChipLogProgress(DeviceLayer, "BleConnectCallbackJNI_OnLoad"); + return CHIP_NO_ERROR; +} + +void BleConnectCallbackJNI_OnUnload(JavaVM * jvm, void * reserved) {} + +JNI_METHOD(void, onConnectSuccess)(JNIEnv * env, jobject self, jlong managerImplPtr, jlong appStatePtr, jint connId) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + BLEManagerImpl * impl = reinterpret_cast(managerImplPtr); + void * appState = reinterpret_cast(appStatePtr); + impl->OnConnectSuccess(appState, reinterpret_cast(connId)); +#endif +} + +JNI_METHOD(void, onConnectFailed)(JNIEnv * env, jobject self, jlong managerImplPtr, jlong appStatePtr) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + BLEManagerImpl * impl = reinterpret_cast(managerImplPtr); + void * appState = reinterpret_cast(appStatePtr); + impl->OnConnectFailed(appState, BLE_ERROR_NO_CONNECTION_RECEIVED_CALLBACK); +#endif +} diff --git a/src/platform/android/BleConnectCallback-JNI.h b/src/platform/android/BleConnectCallback-JNI.h new file mode 100644 index 00000000000000..3d5c558a3257b4 --- /dev/null +++ b/src/platform/android/BleConnectCallback-JNI.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2020-2021 Project CHIP Authors + * All rights reserved. + * + * 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. + * + */ + +/** + * @file + * Implementation of JNI bridge for CHIP Device Controller for Android apps + * + */ + +#pragma once + +CHIP_ERROR BleConnectCallbackJNI_OnLoad(JavaVM * jvm, void * reserved); + +void BleConnectCallbackJNI_OnUnload(JavaVM * jvm, void * reserved); diff --git a/src/platform/android/java/chip/platform/AndroidBleManager.java b/src/platform/android/java/chip/platform/AndroidBleManager.java index 3bc484985d231d..1d440b67b18da3 100644 --- a/src/platform/android/java/chip/platform/AndroidBleManager.java +++ b/src/platform/android/java/chip/platform/AndroidBleManager.java @@ -17,15 +17,30 @@ */ package chip.platform; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; +import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; +import android.bluetooth.le.BluetoothLeScanner; +import android.bluetooth.le.ScanCallback; +import android.bluetooth.le.ScanFilter; +import android.bluetooth.le.ScanResult; +import android.bluetooth.le.ScanSettings; +import android.content.Context; import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.os.ParcelUuid; import android.util.Log; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.UUID; @@ -63,115 +78,143 @@ private static class BleMtuDenylist { private BluetoothGattCallback mGattCallback; private AndroidChipPlatform mPlatform; + private Context mContext; + private BluetoothAdapter mBluetoothAdapter; + + private BleConnectCallback mBleConnectCallback; + + private BleConnectionHandler mConnectionHandler; + private ScanCallback mScanCallback; + + private static final int MSG_BLE_SCAN = 0; + private static final int MSG_BLE_CONNECT = 1; + private static final int MSG_BLE_CONNECT_SUCCESS = 2; + private static final int MSG_BLE_FAIL = 99; + + private static final int BLE_TIMEOUT_MS = 10000; + private static final int BLUETOOTH_ENABLE_TIMEOUT_MS = 1000; + + private static final String MSG_BUNDLE_SERVICE_DATA = "serviceData"; + private static final String MSG_BUNDLE_SERVICE_DATA_MASK = "serviceDataMask"; + + public AndroidBleManager(Context context) { + this(); + mContext = context; + @SuppressWarnings("unchecked") + BluetoothManager manager = + (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); + mBluetoothAdapter = manager.getAdapter(); + mConnectionHandler = new BleConnectionHandler(Looper.getMainLooper()); + } + public AndroidBleManager() { mConnections = new ArrayList<>(INITIAL_CONNECTIONS); - mGattCallback = - new BluetoothGattCallback() { - @Override - public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - int connId = 0; - - if (newState == BluetoothProfile.STATE_DISCONNECTED) { - connId = getConnId(gatt); - if (connId > 0) { - Log.d(TAG, "onConnectionStateChange Disconnected"); - mPlatform.handleConnectionError(connId); - } else { - Log.e(TAG, "onConnectionStateChange disconnected: no active connection"); - } - } - } + mGattCallback = new AndroidBluetoothGattCallback(); + } - @Override - public void onServicesDiscovered(BluetoothGatt gatt, int status) {} + class AndroidBluetoothGattCallback extends BluetoothGattCallback { + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + int connId = 0; + + if (newState == BluetoothProfile.STATE_DISCONNECTED) { + connId = getConnId(gatt); + if (connId > 0) { + Log.d(TAG, "onConnectionStateChange Disconnected"); + mPlatform.handleConnectionError(connId); + } else { + Log.e(TAG, "onConnectionStateChange disconnected: no active connection"); + } + } + } - @Override - public void onCharacteristicRead( - BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {} + @Override + public void onServicesDiscovered(BluetoothGatt gatt, int status) {} + + @Override + public void onCharacteristicRead( + BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {} + + @Override + public void onCharacteristicWrite( + BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { + byte[] svcIdBytes = convertUUIDToBytes(characteristic.getService().getUuid()); + byte[] charIdBytes = convertUUIDToBytes(characteristic.getUuid()); + + if (status != BluetoothGatt.GATT_SUCCESS) { + Log.e( + TAG, + "onCharacteristicWrite for " + + characteristic.getUuid().toString() + + " failed with status: " + + status); + return; + } - @Override - public void onCharacteristicWrite( - BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - byte[] svcIdBytes = convertUUIDToBytes(characteristic.getService().getUuid()); - byte[] charIdBytes = convertUUIDToBytes(characteristic.getUuid()); - - if (status != BluetoothGatt.GATT_SUCCESS) { - Log.e( - TAG, - "onCharacteristicWrite for " - + characteristic.getUuid().toString() - + " failed with status: " - + status); - return; - } - - int connId = getConnId(gatt); - if (connId > 0) { - mPlatform.handleWriteConfirmation( - connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); - } else { - Log.e(TAG, "onCharacteristicWrite no active connection"); - return; - } - } + int connId = getConnId(gatt); + if (connId > 0) { + mPlatform.handleWriteConfirmation( + connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); + } else { + Log.e(TAG, "onCharacteristicWrite no active connection"); + return; + } + } - @Override - public void onCharacteristicChanged( - BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { - byte[] svcIdBytes = convertUUIDToBytes(characteristic.getService().getUuid()); - byte[] charIdBytes = convertUUIDToBytes(characteristic.getUuid()); - int connId = getConnId(gatt); - if (connId > 0) { - mPlatform.handleIndicationReceived( - connId, svcIdBytes, charIdBytes, characteristic.getValue()); - } else { - Log.e(TAG, "onCharacteristicChanged no active connection"); - return; - } - } + @Override + public void onCharacteristicChanged( + BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { + byte[] svcIdBytes = convertUUIDToBytes(characteristic.getService().getUuid()); + byte[] charIdBytes = convertUUIDToBytes(characteristic.getUuid()); + int connId = getConnId(gatt); + if (connId > 0) { + mPlatform.handleIndicationReceived( + connId, svcIdBytes, charIdBytes, characteristic.getValue()); + } else { + Log.e(TAG, "onCharacteristicChanged no active connection"); + return; + } + } - @Override - public void onDescriptorWrite( - BluetoothGatt gatt, BluetoothGattDescriptor desc, int status) { - BluetoothGattCharacteristic characteristic = desc.getCharacteristic(); - - byte[] svcIdBytes = convertUUIDToBytes(characteristic.getService().getUuid()); - byte[] charIdBytes = convertUUIDToBytes(characteristic.getUuid()); - - if (status != BluetoothGatt.GATT_SUCCESS) { - Log.e( - TAG, - "onDescriptorWrite for " - + desc.getUuid().toString() - + " failed with status: " - + status); - } - - int connId = getConnId(gatt); - if (connId == 0) { - Log.e(TAG, "onDescriptorWrite no active connection"); - return; - } - - if (desc.getValue() == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE) { - mPlatform.handleSubscribeComplete( - connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); - } else if (desc.getValue() == BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) { - mPlatform.handleSubscribeComplete( - connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); - } else if (desc.getValue() == BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE) { - mPlatform.handleUnsubscribeComplete( - connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); - } else { - Log.d(TAG, "Unexpected onDescriptorWrite()."); - } - } + @Override + public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor desc, int status) { + BluetoothGattCharacteristic characteristic = desc.getCharacteristic(); - @Override - public void onDescriptorRead( - BluetoothGatt gatt, BluetoothGattDescriptor desc, int status) {} - }; + byte[] svcIdBytes = convertUUIDToBytes(characteristic.getService().getUuid()); + byte[] charIdBytes = convertUUIDToBytes(characteristic.getUuid()); + + if (status != BluetoothGatt.GATT_SUCCESS) { + Log.e( + TAG, + "onDescriptorWrite for " + + desc.getUuid().toString() + + " failed with status: " + + status); + } + + int connId = getConnId(gatt); + if (connId == 0) { + Log.e(TAG, "onDescriptorWrite no active connection"); + return; + } + + if (desc.getValue() == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE) { + mPlatform.handleSubscribeComplete( + connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); + } else if (desc.getValue() == BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) { + mPlatform.handleSubscribeComplete( + connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); + } else if (desc.getValue() == BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE) { + mPlatform.handleUnsubscribeComplete( + connId, svcIdBytes, charIdBytes, status == BluetoothGatt.GATT_SUCCESS); + } else { + Log.d(TAG, "Unexpected onDescriptorWrite()."); + } + } + + @Override + public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor desc, int status) {} } @Override @@ -417,14 +460,229 @@ public void onNotifyChipConnectionClosed(int connId) { } @Override - public void onNewConnection(int discriminator) { + public void onNewConnection( + int discriminator, boolean isShortDiscriminator, long implPtr, long appStatePtr) { + Log.d(TAG, "onNewConnection : " + discriminator + ", " + isShortDiscriminator); + if (mContext == null) { + return; + } + mBleConnectCallback = new BleConnectCallback(implPtr, appStatePtr); + mConnectionHandler.sendEmptyMessageDelayed(MSG_BLE_FAIL, BLE_TIMEOUT_MS); + Message msg = mConnectionHandler.obtainMessage(); + msg.what = MSG_BLE_SCAN; + Bundle bundle = new Bundle(); + byte[] serviceData = getServiceData(discriminator); + byte[] serviceDataMask = getServiceDataMask(isShortDiscriminator); + bundle.putByteArray(MSG_BUNDLE_SERVICE_DATA, serviceData); + bundle.putByteArray(MSG_BUNDLE_SERVICE_DATA_MASK, serviceDataMask); + msg.setData(bundle); + if (!mBluetoothAdapter.isEnabled()) { + mBluetoothAdapter.enable(); + // TODO: Check Bluetooth enable intent + mConnectionHandler.sendMessageDelayed(msg, BLUETOOTH_ENABLE_TIMEOUT_MS); + return; + } + mConnectionHandler.sendMessage(msg); return; } + class BleConnectionHandler extends Handler { + public BleConnectionHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + + switch (msg.what) { + case MSG_BLE_SCAN: + startBleScan(msg.getData()); + break; + case MSG_BLE_CONNECT: + stopBleScan(); + connectBLE(msg.obj); + break; + case MSG_BLE_CONNECT_SUCCESS: + bleConnectSuccess(msg.obj); + break; + case MSG_BLE_FAIL: + default: + stopBleScan(); + bleConnectFail(); + break; + } + } + } + + private void startBleScan(Bundle bundle) { + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + if (scanner == null) { + Log.d(TAG, "No bluetooth scanner found"); + return; + } + + mScanCallback = + new ScanCallback() { + @Override + public void onScanResult(int callbackType, ScanResult result) { + BluetoothDevice device = result.getDevice(); + Log.i( + TAG, + "Bluetooth Device Scanned Addr: " + device.getAddress() + ", " + device.getName()); + Message msg = mConnectionHandler.obtainMessage(); + msg.what = MSG_BLE_CONNECT; + msg.obj = (Object) device; + mConnectionHandler.sendMessage(msg); + } + + @Override + public void onScanFailed(int errorCode) { + Log.e(TAG, "Scan failed " + errorCode); + } + }; + + byte[] serviceData = bundle.getByteArray(MSG_BUNDLE_SERVICE_DATA); + byte[] serviceDataMask = bundle.getByteArray(MSG_BUNDLE_SERVICE_DATA_MASK); + ScanFilter scanFilter = + new ScanFilter.Builder() + .setServiceData( + new ParcelUuid(UUID.fromString(CHIP_UUID)), serviceData, serviceDataMask) + .build(); + ScanSettings scanSettings = + new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); + Log.i(TAG, "Starting Bluetooth scan"); + scanner.startScan(Arrays.asList(scanFilter), scanSettings, mScanCallback); + } + + private void stopBleScan() { + if (mScanCallback != null) { + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + if (scanner == null) { + Log.d(TAG, "No bluetooth scanner found"); + return; + } + scanner.stopScan(mScanCallback); + mScanCallback = null; + } + } + + private void connectBLE(Object bluetoothDeviceObj) { + if (bluetoothDeviceObj == null) { + return; + } + + // Fail Timer reset. + mConnectionHandler.removeMessages(MSG_BLE_FAIL); + mConnectionHandler.sendEmptyMessageDelayed(MSG_BLE_FAIL, BLE_TIMEOUT_MS); + + @SuppressWarnings("unchecked") + BluetoothDevice device = (BluetoothDevice) bluetoothDeviceObj; + + Log.i(TAG, "Connecting"); + BluetoothGatt gatt = device.connectGatt(mContext, false, new ConnectionGattCallback()); + } + + class ConnectionGattCallback extends AndroidBluetoothGattCallback { + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + Log.i(TAG, "onConnectionStateChange status = " + status + ", newState= + " + newState); + super.onConnectionStateChange(gatt, status, newState); + if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { + Log.i(TAG, "Discovering Services..."); + gatt.discoverServices(); + return; + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + Log.i(TAG, "Services Disconnected"); + } + mConnectionHandler.sendEmptyMessage(MSG_BLE_FAIL); + } + + @Override + public void onServicesDiscovered(BluetoothGatt gatt, int status) { + Log.d(TAG, "onServicesDiscovered status = " + status); + super.onServicesDiscovered(gatt, status); + + Log.i(TAG, "Services Discovered"); + gatt.requestMtu(247); + } + + @Override + public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { + super.onMtuChanged(gatt, mtu, status); + String deviceName = ""; + if (gatt != null && gatt.getDevice() != null) { + deviceName = gatt.getDevice().getName(); + } + Log.d(TAG, deviceName + ".onMtuChanged: connecting to CHIP device : " + status); + + Message msg = mConnectionHandler.obtainMessage(); + msg.what = MSG_BLE_CONNECT_SUCCESS; + msg.obj = (Object) gatt; + + mConnectionHandler.sendMessage(msg); + } + } + + private void bleConnectSuccess(Object gattObj) { + Log.d(TAG, "bleConnectSuccess"); + mConnectionHandler.removeMessages(MSG_BLE_FAIL); + @SuppressWarnings("unchecked") + BluetoothGatt gatt = (BluetoothGatt) gattObj; + int connId = addConnection(gatt); + + setBleCallback( + new BleCallback() { + @Override + public void onCloseBleComplete(int connId) { + Log.d(TAG, "onCloseBleComplete : " + connId); + } + + @Override + public void onNotifyChipConnectionClosed(int connId) { + Log.d(TAG, "onNotifyChipConnectionClosed : " + connId); + } + }); + + if (mBleConnectCallback != null) { + mBleConnectCallback.onConnectSuccess(connId); + } else { + // Already fail returned + Log.d(TAG, "Already timeout"); + gatt.disconnect(); + removeConnection(connId); + } + mBleConnectCallback = null; + } + + private void bleConnectFail() { + Log.d(TAG, "bleConnectFail"); + if (mBleConnectCallback != null) { + mBleConnectCallback.onConnectFailed(); + } + mBleConnectCallback = null; + } + + private byte[] getServiceData(int discriminator) { + int opcode = 0; + int version = 0; + int versionDiscriminator = ((version & 0xf) << 12) | (discriminator & 0xfff); + return new byte[] { + (byte) (opcode & 0xFF), + (byte) (versionDiscriminator & 0xFF), + (byte) ((versionDiscriminator >> 8) & 0xFF) + }; + } + + private byte[] getServiceDataMask(boolean isShortDiscriminator) { + return new byte[] {(byte) 0xFF, (byte) (isShortDiscriminator ? 0x00 : 0xFF), (byte) 0xFF}; + } + // CLIENT_CHARACTERISTIC_CONFIG is the well-known UUID of the client characteristic descriptor // that has the flags for enabling and disabling notifications and indications. // c.f. https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-attribute-profile private static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"; + private static String CHIP_UUID = "0000FFF6-0000-1000-8000-00805F9B34FB"; private static byte[] convertUUIDToBytes(UUID uuid) { byte[] idBytes = new byte[16]; diff --git a/src/platform/android/java/chip/platform/BleConnectCallback.java b/src/platform/android/java/chip/platform/BleConnectCallback.java new file mode 100644 index 00000000000000..073a8b95594037 --- /dev/null +++ b/src/platform/android/java/chip/platform/BleConnectCallback.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * 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.platform; + +public class BleConnectCallback { + private long implPtr; + private long appStatePtr; + + public BleConnectCallback(long implPtr, long appStatePtr) { + this.implPtr = implPtr; + this.appStatePtr = appStatePtr; + } + + public void onConnectSuccess(int connectionId) { + onConnectSuccess(implPtr, appStatePtr, connectionId); + } + + public void onConnectFailed() { + onConnectFailed(implPtr, appStatePtr); + } + + private native void onConnectSuccess(long implPtr, long appStatePtr, int connectionId); + + private native void onConnectFailed(long implPtr, long appStatePtr); +} diff --git a/src/platform/android/java/chip/platform/BleManager.java b/src/platform/android/java/chip/platform/BleManager.java index 687bd9e5d51fc2..34bcb662b139c5 100644 --- a/src/platform/android/java/chip/platform/BleManager.java +++ b/src/platform/android/java/chip/platform/BleManager.java @@ -56,5 +56,6 @@ public interface BleManager { void onNotifyChipConnectionClosed(int connId); // BleConnectionDelegate - void onNewConnection(int discriminator); + void onNewConnection( + int discriminator, boolean isShortDiscriminator, long implPtr, long appStatePtr); } From 8b45b5c33346cd3eb636c43e562725cbd40181ba Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 12 May 2023 15:10:27 -0400 Subject: [PATCH 16/36] Fix cross compile path (#26553) Co-authored-by: Andrei Litvin --- integrations/docker/images/chip-build-crosscompile/Dockerfile | 2 +- integrations/docker/images/chip-build/version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integrations/docker/images/chip-build-crosscompile/Dockerfile b/integrations/docker/images/chip-build-crosscompile/Dockerfile index e00428918ae312..0dfb3328b79798 100644 --- a/integrations/docker/images/chip-build-crosscompile/Dockerfile +++ b/integrations/docker/images/chip-build-crosscompile/Dockerfile @@ -28,6 +28,6 @@ RUN set -x \ FROM connectedhomeip/chip-build:${VERSION} -COPY --from=build /opt/ubuntu-22.04.1-aarch64-sysroot/ /opt/ubuntu-22.04-aarch64-sysroot/ +COPY --from=build /opt/ubuntu-22.04.1-aarch64-sysroot/ /opt/ubuntu-22.04.1-aarch64-sysroot/ ENV SYSROOT_AARCH64=/opt/ubuntu-22.04.1-aarch64-sysroot diff --git a/integrations/docker/images/chip-build/version b/integrations/docker/images/chip-build/version index bf582d0ebee454..e330c9368becf5 100644 --- a/integrations/docker/images/chip-build/version +++ b/integrations/docker/images/chip-build/version @@ -1 +1 @@ -0.7.8 Version bump reason: Update crosscompile sysroot to Ubuntu 22.04.01 +0.7.9 Version bump reason: Fix path for sysroot for crosscompile image From 42f38de199e79f77e48b39a220393fcc68bbd3d7 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 12 May 2023 15:18:04 -0400 Subject: [PATCH 17/36] Remove copy of gcc since #26503 removed this (#26557) Co-authored-by: Andrei Litvin --- integrations/docker/images/chip-build-vscode/Dockerfile | 1 - 1 file changed, 1 deletion(-) diff --git a/integrations/docker/images/chip-build-vscode/Dockerfile b/integrations/docker/images/chip-build-vscode/Dockerfile index c195ced69d9c9e..276c5959f8e812 100644 --- a/integrations/docker/images/chip-build-vscode/Dockerfile +++ b/integrations/docker/images/chip-build-vscode/Dockerfile @@ -50,7 +50,6 @@ COPY --from=imx /opt/fsl-imx-xwayland /opt/fsl-imx-xwayland COPY --from=ti /opt/ti/sysconfig_1.13.0 /opt/ti/sysconfig_1.13.0 -COPY --from=openiotsdk /opt/gcc-arm-none-eabi-10.3-2021.10/ /opt/gcc-arm-none-eabi-10.3-2021.10/ COPY --from=openiotsdk /opt/FVP_Corstone_SSE-300/ /opt/FVP_Corstone_SSE-300/ COPY --from=bouffalolab /opt/bouffalolab_sdk /opt/bouffalolab_sdk From 4083b32732b04aeec63b8f03ebd1e12ade78dd0f Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Sat, 13 May 2023 12:20:38 +0200 Subject: [PATCH 18/36] [Tizen] Account for 0-terminator in WriteConfigValueStr (#26510) * [Tizen] Account for 0-terminator in WriteConfigValueStr * Fix null-terminator implementation after review * Update src/platform/Tizen/PosixConfig.cpp --------- Co-authored-by: Boris Zbarsky --- src/platform/Tizen/PosixConfig.cpp | 11 ++++++++++- src/platform/tests/TestConfigurationMgr.cpp | 5 ++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/platform/Tizen/PosixConfig.cpp b/src/platform/Tizen/PosixConfig.cpp index fc65c24bf189a9..c8b2d36d8271bf 100644 --- a/src/platform/Tizen/PosixConfig.cpp +++ b/src/platform/Tizen/PosixConfig.cpp @@ -101,7 +101,16 @@ CHIP_ERROR PosixConfig::ReadConfigValue(Key key, uint64_t & val) CHIP_ERROR PosixConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { VerifyOrReturnError(buf != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - return PersistedStorage::KeyValueStoreMgr().Get(key.Name, buf, bufSize, &outLen); + + auto err = PersistedStorage::KeyValueStoreMgr().Get(key.Name, buf, bufSize, &outLen); + VerifyOrReturnError(err == CHIP_NO_ERROR, err); + + // We are storing string values in the config store without + // the null terminator, so we need to add it here. + VerifyOrReturnError(bufSize >= outLen + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + buf[outLen] = '\0'; + + return CHIP_NO_ERROR; } CHIP_ERROR PosixConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) diff --git a/src/platform/tests/TestConfigurationMgr.cpp b/src/platform/tests/TestConfigurationMgr.cpp index dafe5b209725a2..a113594868ad2c 100644 --- a/src/platform/tests/TestConfigurationMgr.cpp +++ b/src/platform/tests/TestConfigurationMgr.cpp @@ -449,7 +449,6 @@ static void TestConfigurationMgr_GetProductId(nlTestSuite * inSuite, void * inCo * Test Suite. It lists all the test functions. */ static const nlTest sTests[] = { - NL_TEST_DEF("Test PlatformMgr::Init", TestPlatformMgr_Init), #if !defined(NDEBUG) NL_TEST_DEF("Test PlatformMgr::RunUnitTest", TestPlatformMgr_RunUnitTest), @@ -466,8 +465,8 @@ static const nlTest sTests[] = { NL_TEST_DEF("Test ConfigurationMgr::GetVendorId", TestConfigurationMgr_GetVendorId), NL_TEST_DEF("Test ConfigurationMgr::GetProductName", TestConfigurationMgr_GetProductName), NL_TEST_DEF("Test ConfigurationMgr::GetProductId", TestConfigurationMgr_GetProductId), - NL_TEST_SENTINEL() -}; // namespace + NL_TEST_SENTINEL(), +}; /** * Set up the test suite. From a33249db16d3bb351038e68d997db4c0ba5d003c Mon Sep 17 00:00:00 2001 From: adabreuti <76965454+adabreuti@users.noreply.github.com> Date: Sun, 14 May 2023 23:54:35 -0500 Subject: [PATCH 19/36] Add CC13x4 base Platform Support (#26513) * Add CC13x4 base Platform Support * Update to generic TI submodule name * Add new ot-ti submodule * Update workflow * Update legacy applications with new platform directory structure * Update test data * Revert SDK version for initial Platform support * resolve UART naming issue * Temporarily disable TI CI for initial Platform Support. To be re-enabled once 13x4 Applications/Docker image is up-to-date --- .../workflows/examples-cc13x2x7_26x2x7.yaml | 74 +- .gitmodules | 9 +- .../cc13x2x7_26x2x7/README.md | 244 ----- .../cc13x2x7_26x2x7/main/ClusterManager.cpp | 177 ---- .../cc13x2x7_26x2x7/main/Globals.cpp | 22 - .../main/include/ClusterManager.h | 51 - .../cc13x2x7_26x2x7/.gn | 1 + .../cc13x2x7_26x2x7/BUILD.gn | 30 +- .../cc13x2x7_26x2x7/args.gni | 14 +- .../cc13x2x7_26x2x7/build_overrides | 0 .../cc13x2x7_26x2x7/chip.syscfg | 78 +- .../include/CHIPProjectConfig.h | 8 +- .../cc13x2x7_26x2x7/src/AppConfig.h} | 16 +- .../cc13x2x7_26x2x7/src/AppEvent.h | 84 ++ .../cc13x2x7_26x2x7/src}/AppTask.cpp | 370 ++++--- .../cc13x2x7_26x2x7/src/AppTask.h | 93 ++ .../cc13x2x7_26x2x7/src/LightingManager.cpp | 176 ++++ .../cc13x2x7_26x2x7/src/LightingManager.h | 82 ++ .../cc13x2x7_26x2x7/src}/ZclCallbacks.cpp | 58 +- .../cc13x2x7_26x2x7/src}/main.cpp | 26 +- .../third_party/connectedhomeip | 0 examples/lock-app/cc13x2x7_26x2x7/BUILD.gn | 12 +- examples/lock-app/cc13x2x7_26x2x7/args.gni | 7 +- examples/lock-app/cc13x2x7_26x2x7/chip.syscfg | 6 +- .../include/CHIPProjectConfig.h | 130 +++ .../cc13x2x7_26x2x7/src}/AppConfig.h | 15 +- .../cc13x2x7_26x2x7/src}/AppEvent.h | 10 +- .../lock-app/cc13x2x7_26x2x7/src/AppTask.cpp | 561 +++++++++++ .../cc13x2x7_26x2x7/src}/AppTask.h | 28 +- .../cc13x2x7_26x2x7/src/LockManager.cpp | 703 ++++++++++++++ .../cc13x2x7_26x2x7/src/LockManager.h | 221 +++++ .../cc13x2x7_26x2x7/src/ZclCallbacks.cpp | 149 +++ .../lock-app/cc13x2x7_26x2x7/src/main.cpp | 105 ++ .../cc13x2x7_26x2x7/chip.syscfg | 92 +- .../cc13x2x7_26x2x7/include/AppConfig.h | 1 - examples/platform/cc13x2_26x2/BUILD.gn | 9 + .../CC13X2_26X2DeviceAttestationCreds.cpp | 8 +- examples/platform/cc13x2_26x2/args.gni | 4 +- .../project_include/OpenThreadConfig.h | 98 ++ examples/pump-app/cc13x2x7_26x2x7/BUILD.gn | 1 - examples/pump-app/cc13x2x7_26x2x7/args.gni | 6 +- examples/pump-app/cc13x2x7_26x2x7/chip.syscfg | 342 +++---- .../pump-app/cc13x2x7_26x2x7/main/AppTask.cpp | 6 +- .../cc13x2x7_26x2x7/main/ZclCallbacks.cpp | 2 +- .../cc13x2x7_26x2x7/main/include/AppConfig.h | 7 +- .../cc13x2x7_26x2x7/main/include/AppEvent.h | 2 +- .../main/include/CHIPProjectConfig.h | 2 +- .../pump-app/cc13x2x7_26x2x7/main/main.cpp | 16 +- .../cc13x2x7_26x2x7/BUILD.gn | 2 +- .../cc13x2x7_26x2x7/args.gni | 6 +- .../cc13x2x7_26x2x7/chip.syscfg | 341 +++---- .../cc13x2x7_26x2x7/main/AppTask.cpp | 11 +- .../cc13x2x7_26x2x7/main/ZclCallbacks.cpp | 2 +- .../cc13x2x7_26x2x7/main/include/AppConfig.h | 7 +- .../cc13x2x7_26x2x7/main/include/AppEvent.h | 2 +- .../main/include/CHIPProjectConfig.h | 2 +- .../cc13x2x7_26x2x7/main/main.cpp | 16 +- examples/shell/cc13x2x7_26x2x7/BUILD.gn | 1 + examples/shell/cc13x2x7_26x2x7/args.gni | 1 + examples/shell/cc13x2x7_26x2x7/chip.syscfg | 76 +- .../include/CHIPProjectConfig.h | 2 +- .../shell/cc13x2x7_26x2x7/main/AppTask.cpp | 14 +- examples/shell/cc13x2x7_26x2x7/main/main.cpp | 16 +- scripts/checkout_submodules.py | 2 +- src/lib/shell/BUILD.gn | 5 +- src/lib/shell/streamer_cc13x4_26x4.cpp | 109 +++ src/lwip/BUILD.gn | 6 +- .../{cc13x2_26x2 => cc13xx_26xx}/arch/cc.h | 0 .../{cc13x2_26x2 => cc13xx_26xx}/arch/perf.h | 0 .../{cc13x2_26x2 => cc13xx_26xx}/lwipopts.h | 7 +- .../{cc13x2_26x2 => cc13xx_26xx}/lwippools.h | 0 src/platform/BUILD.gn | 11 +- .../BLEManagerImpl.cpp | 4 +- .../CC13XX_26XXConfig.cpp} | 193 ++-- .../CC13XX_26XXConfig.h} | 20 +- .../ConfigurationManagerImpl.cpp | 44 +- .../ConnectivityManagerImpl.cpp | 0 .../DiagnosticDataProviderImpl.cpp | 2 +- .../DiagnosticDataProviderImpl.h | 0 .../KeyValueStoreManagerImpl.cpp | 8 +- .../{cc13x2_26x2 => cc13xx_26xx}/Logging.cpp | 38 +- .../OTAImageProcessorImpl.cpp | 0 .../OTAImageProcessorImpl.h | 0 .../PlatformManagerImpl.cpp | 4 +- .../{cc13x2_26x2 => cc13xx_26xx}/Random.c | 0 .../ThreadStackManagerImpl.cpp | 25 +- .../cc13x2_26x2/BLEManagerImpl.h | 6 +- .../{ => cc13xx_26xx}/cc13x2_26x2/BUILD.gn | 38 +- .../cc13x2_26x2/BlePlatformConfig.h | 2 +- .../cc13x2_26x2/CHIPDevicePlatformConfig.h | 2 +- .../cc13x2_26x2/CHIPDevicePlatformEvent.h | 2 +- .../cc13x2_26x2/CHIPPlatformConfig.h | 0 .../cc13x2_26x2/ConfigurationManagerImpl.h | 4 +- .../cc13x2_26x2/ConnectivityManagerImpl.h | 6 +- .../cc13x2_26x2/FreeRTOSConfig.h | 0 .../cc13x2_26x2/InetPlatformConfig.h | 0 .../cc13x2_26x2/KeyValueStoreManagerImpl.h | 2 +- .../cc13x2_26x2/PlatformManagerImpl.h | 4 +- .../cc13x2_26x2/SystemPlatformConfig.h | 0 .../cc13x2_26x2/ThreadStackManagerImpl.h | 7 +- .../{ => cc13xx_26xx}/cc13x2_26x2/args.gni | 2 +- .../cc13x2_26x2/ble_user_config.c | 0 .../cc13x2x7_cc26x2x7_freertos.lds | 345 +++++++ .../cc13x2x7_cc26x2x7_freertos_ota.lds | 10 +- .../cc13x2_26x2/crypto/aes_alt.c | 0 .../cc13x2_26x2/crypto/aes_alt.h | 0 .../crypto/cc13x2_26x2-mbedtls-config.h | 4 +- .../cc13x2_26x2/crypto/ecdh_alt.c | 0 .../cc13x2_26x2/crypto/ecdsa_alt.c | 0 .../cc13x2_26x2/crypto/ecjpake_alt.c | 0 .../cc13x2_26x2/crypto/ecjpake_alt.h | 0 .../cc13x2_26x2/crypto/sha256_alt.c | 0 .../cc13x2_26x2/crypto/sha256_alt.h | 0 ...openthread-core-cc13x2_26x2-config-check.h | 0 .../openthread-core-cc13x2_26x2-config.h | 0 .../cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h | 368 +++++++ src/platform/cc13xx_26xx/cc13x4_26x4/BUILD.gn | 105 ++ .../cc13x4_26x4/BlePlatformConfig.h | 10 +- .../cc13x4_26x4/CHIPDevicePlatformConfig.h | 55 ++ .../cc13x4_26x4/CHIPDevicePlatformEvent.h | 41 + .../cc13x4_26x4/CHIPPlatformConfig.h | 69 ++ .../cc13x4_26x4/ConfigurationManagerImpl.h | 91 ++ .../cc13x4_26x4/ConnectivityManagerImpl.h | 108 +++ .../cc13xx_26xx/cc13x4_26x4/FreeRTOSConfig.h | 249 +++++ .../cc13x4_26x4/InetPlatformConfig.h | 34 + .../cc13x4_26x4/KeyValueStoreManagerImpl.h | 75 ++ .../cc13x4_26x4/PlatformManagerImpl.h | 94 ++ .../cc13x4_26x4/SystemPlatformConfig.h | 39 + .../cc13x4_26x4/ThreadStackManagerImpl.h | 141 +++ src/platform/cc13xx_26xx/cc13x4_26x4/args.gni | 37 + .../cc13xx_26xx/cc13x4_26x4/ble_user_config.c | 560 +++++++++++ .../cc13x4_26x4/cc13x4_cc26x4_freertos.lds | 259 +++++ .../cc13x4_cc26x4_freertos_ota.lds | 270 ++++++ .../cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.c | 133 +++ .../cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.h | 45 + .../crypto/cc13x4_26x4-mbedtls-config.h | 134 +++ .../cc13xx_26xx/cc13x4_26x4/crypto/ecdh_alt.c | 313 ++++++ .../cc13x4_26x4/crypto/ecdsa_alt.c | 288 ++++++ .../cc13x4_26x4/crypto/ecjpake_alt.c | 900 ++++++++++++++++++ .../cc13x4_26x4/crypto/ecjpake_alt.h | 119 +++ .../cc13x4_26x4/crypto/sha256_alt.c | 192 ++++ .../cc13x4_26x4/crypto/sha256_alt.h | 44 + ...openthread-core-cc13x4_26x4-config-check.h | 33 + .../openthread-core-cc13x4_26x4-config.h | 73 ++ .../chipOBleProfile.c | 0 .../chipOBleProfile.h | 0 .../oad_image_header.c | 0 src/platform/device.gni | 11 +- third_party/openthread/ot-ti | 1 + .../openthread/platforms/cc13x2_26x2/BUILD.gn | 74 ++ .../openthread/platforms/cc13x4_26x4/BUILD.gn | 74 ++ third_party/ti_simplelink_sdk/BUILD.gn | 53 +- .../ti_simplelink_sdk/run_sysconfig.py | 4 +- .../ti_simplelink_arm_platform_config.gni | 7 + .../ti_simplelink_sdk/ti_simplelink_board.gni | 21 +- .../ti_simplelink_executable.gni | 19 +- .../ti_simplelink_sdk/ti_simplelink_sdk.gni | 377 +++++--- 157 files changed, 9528 insertions(+), 1559 deletions(-) delete mode 100644 examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md delete mode 100644 examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp delete mode 100644 examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/Globals.cpp delete mode 100644 examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h rename examples/{all-clusters-minimal-app => lighting-app}/cc13x2x7_26x2x7/.gn (99%) rename examples/{all-clusters-minimal-app => lighting-app}/cc13x2x7_26x2x7/BUILD.gn (71%) rename examples/{all-clusters-minimal-app => lighting-app}/cc13x2x7_26x2x7/args.gni (83%) rename examples/{all-clusters-minimal-app => lighting-app}/cc13x2x7_26x2x7/build_overrides (100%) rename examples/{all-clusters-minimal-app => lighting-app}/cc13x2x7_26x2x7/chip.syscfg (82%) rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main => lighting-app/cc13x2x7_26x2x7}/include/CHIPProjectConfig.h (95%) rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h => lighting-app/cc13x2x7_26x2x7/src/AppConfig.h} (75%) create mode 100644 examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main => lighting-app/cc13x2x7_26x2x7/src}/AppTask.cpp (56%) create mode 100644 examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h create mode 100644 examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp create mode 100644 examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main => lighting-app/cc13x2x7_26x2x7/src}/ZclCallbacks.cpp (57%) rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main => lighting-app/cc13x2x7_26x2x7/src}/main.cpp (79%) rename examples/{all-clusters-minimal-app => lighting-app}/cc13x2x7_26x2x7/third_party/connectedhomeip (100%) create mode 100644 examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main/include => lock-app/cc13x2x7_26x2x7/src}/AppConfig.h (74%) rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main/include => lock-app/cc13x2x7_26x2x7/src}/AppEvent.h (86%) create mode 100644 examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp rename examples/{all-clusters-minimal-app/cc13x2x7_26x2x7/main/include => lock-app/cc13x2x7_26x2x7/src}/AppTask.h (60%) create mode 100644 examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp create mode 100644 examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h create mode 100644 examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp create mode 100644 examples/lock-app/cc13x2x7_26x2x7/src/main.cpp create mode 100644 examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h create mode 100644 src/lib/shell/streamer_cc13x4_26x4.cpp rename src/lwip/{cc13x2_26x2 => cc13xx_26xx}/arch/cc.h (100%) rename src/lwip/{cc13x2_26x2 => cc13xx_26xx}/arch/perf.h (100%) rename src/lwip/{cc13x2_26x2 => cc13xx_26xx}/lwipopts.h (97%) rename src/lwip/{cc13x2_26x2 => cc13xx_26xx}/lwippools.h (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/BLEManagerImpl.cpp (99%) rename src/platform/{cc13x2_26x2/CC13X2_26X2Config.cpp => cc13xx_26xx/CC13XX_26XXConfig.cpp} (60%) rename src/platform/{cc13x2_26x2/CC13X2_26X2Config.h => cc13xx_26xx/CC13XX_26XXConfig.h} (89%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/ConfigurationManagerImpl.cpp (79%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/ConnectivityManagerImpl.cpp (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/DiagnosticDataProviderImpl.cpp (99%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/DiagnosticDataProviderImpl.h (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/KeyValueStoreManagerImpl.cpp (89%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/Logging.cpp (71%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/OTAImageProcessorImpl.cpp (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/OTAImageProcessorImpl.h (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/PlatformManagerImpl.cpp (97%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/Random.c (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/ThreadStackManagerImpl.cpp (94%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/BLEManagerImpl.h (99%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/BUILD.gn (76%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/BlePlatformConfig.h (93%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/CHIPDevicePlatformConfig.h (96%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/CHIPDevicePlatformEvent.h (94%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/CHIPPlatformConfig.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/ConfigurationManagerImpl.h (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/ConnectivityManagerImpl.h (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/FreeRTOSConfig.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/InetPlatformConfig.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/KeyValueStoreManagerImpl.h (99%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/PlatformManagerImpl.h (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/SystemPlatformConfig.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/ThreadStackManagerImpl.h (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/args.gni (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/ble_user_config.c (100%) create mode 100644 src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos.lds rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/aes_alt.c (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/aes_alt.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h (97%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/ecdh_alt.c (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/ecdsa_alt.c (100%) mode change 100755 => 100644 rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/ecjpake_alt.c (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/ecjpake_alt.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/sha256_alt.c (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/crypto/sha256_alt.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/openthread-core-cc13x2_26x2-config-check.h (100%) rename src/platform/{ => cc13xx_26xx}/cc13x2_26x2/openthread-core-cc13x2_26x2-config.h (100%) create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/BUILD.gn rename examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/OpenThreadConfig.h => src/platform/cc13xx_26xx/cc13x4_26x4/BlePlatformConfig.h (72%) create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformConfig.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformEvent.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/CHIPPlatformConfig.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/ConfigurationManagerImpl.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/ConnectivityManagerImpl.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/FreeRTOSConfig.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/InetPlatformConfig.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/KeyValueStoreManagerImpl.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/PlatformManagerImpl.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/SystemPlatformConfig.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/ThreadStackManagerImpl.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/args.gni create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/ble_user_config.c create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos.lds create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos_ota.lds create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.c create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/cc13x4_26x4-mbedtls-config.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdh_alt.c create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdsa_alt.c create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.c create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.c create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config-check.h create mode 100644 src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config.h rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/chipOBleProfile.c (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/chipOBleProfile.h (100%) rename src/platform/{cc13x2_26x2 => cc13xx_26xx}/oad_image_header.c (100%) create mode 160000 third_party/openthread/ot-ti create mode 100644 third_party/openthread/platforms/cc13x2_26x2/BUILD.gn create mode 100644 third_party/openthread/platforms/cc13x4_26x4/BUILD.gn diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index aaeaf094910373..f3703f38b85f69 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -53,7 +53,7 @@ jobs: attempt_limit: 3 attempt_delay: 2000 - name: Checkout submodules - run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform cc13x2_26x2 + run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform cc13xx_26xx - name: Set up environment for size reports if: ${{ !env.ACT }} env: @@ -79,75 +79,5 @@ jobs: path: | .environment/gn_out/.ninja_log .environment/pigweed-venv/*.log + - - name: Build examples - timeout-minutes: 100 - run: | - scripts/run_in_build_env.sh "\ - ./scripts/build/build_examples.py \ - --target cc13x2x7_26x2x7-all-clusters-mtd \ - --target cc13x2x7_26x2x7-all-clusters-minimal \ - --target cc13x2x7_26x2x7-lock-ftd \ - --target cc13x2x7_26x2x7-lock-mtd \ - --target cc13x2x7_26x2x7-pump \ - --target cc13x2x7_26x2x7-pump-controller \ - --target cc13x2x7_26x2x7-shell \ - build \ - --copy-artifacts-to out/artifacts \ - " - - name: Get lock FTD size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 lock-ftd \ - out/artifacts/cc13x2x7_26x2x7-lock-ftd/chip-LP_CC2652R7-lock-example.out \ - /tmp/bloat_reports/ - - name: Get lock MTD size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 lock-mtd \ - out/artifacts/cc13x2x7_26x2x7-lock-mtd/chip-LP_CC2652R7-lock-example.out \ - /tmp/bloat_reports/ - - name: Get Pump App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 pump-app \ - out/artifacts/cc13x2x7_26x2x7-pump/chip-LP_CC2652R7-pump-example.out \ - /tmp/bloat_reports/ - - name: Get Pump Controller App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 pump-controller-app \ - out/artifacts/cc13x2x7_26x2x7-pump-controller/chip-LP_CC2652R7-pump-controller-example.out \ - /tmp/bloat_reports/ - - name: Get All Clusters App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 all-clusters-app \ - out/artifacts/cc13x2x7_26x2x7-all-clusters-mtd/chip-LP_CC2652R7-all-clusters-example.out \ - /tmp/bloat_reports/ - - name: Get All Clusters Minimal App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 all-clusters-minimal-app \ - out/artifacts/cc13x2x7_26x2x7-all-clusters-minimal/chip-LP_CC2652R7-all-clusters-minimal-example.out \ - /tmp/bloat_reports/ - - name: Get Shell App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 shell \ - out/artifacts/cc13x2x7_26x2x7-shell/chip-LP_CC2652R7-shell-example.out \ - /tmp/bloat_reports/ - - name: Uploading Size Reports - uses: actions/upload-artifact@v3 - if: ${{ !env.ACT }} - with: - name: Size,cc13x2x7_26x2x7-Examples,${{ env.GH_EVENT_PR }},${{ env.GH_EVENT_HASH }},${{ env.GH_EVENT_PARENT }},${{ github.event_name }} - path: | - /tmp/bloat_reports/ diff --git a/.gitmodules b/.gitmodules index d368b904833686..0f5d8dfa6e39e5 100644 --- a/.gitmodules +++ b/.gitmodules @@ -58,7 +58,7 @@ path = third_party/freertos/repo url = https://github.com/FreeRTOS/FreeRTOS-Kernel.git branch = V10.3.1-kernel-only - platforms = ameba,cc13x2_26x2,bouffalolab,efr32,esp32,k32w0,infineon,qpg,cc32xx,silabs_docker + platforms = ameba,cc13xx_26xx,bouffalolab,efr32,esp32,k32w0,infineon,qpg,cc32xx,silabs_docker [submodule "simw-top-mini"] path = third_party/simw-top-mini/repo url = https://github.com/NXP/plug-and-trust.git @@ -224,12 +224,17 @@ path = third_party/ti_simplelink_sdk/repo_cc13xx_cc26xx url = https://github.com/TexasInstruments/cc13xx_cc26xx_sdk.git branch = main - platforms = cc13x2_26x2 + platforms = cc13xx_26xx [submodule "third_party/ti_simplelink_sdk/repo_cc32xx"] path = third_party/ti_simplelink_sdk/repo_cc32xx url = https://github.com/TexasInstruments/cc32xx_open_sdk.git branch = main platforms = cc32xx +[submodule "third_party/openthread/ot-ti"] + path = third_party/openthread/ot-ti + url = https://github.com/TexasInstruments/ot-ti.git + branch = main + platforms = cc13xx_26xx [submodule "third_party/nxp/mw320_sdk/repo"] path = third_party/nxp/mw320_sdk/repo url = https://github.com/nxptest/mw320_sdk diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md b/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md deleted file mode 100644 index 6f67dfa903ff0f..00000000000000 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md +++ /dev/null @@ -1,244 +0,0 @@ -# Matter CC1352 CC2652 All-clusters Example Application - -An example application showing the use of [Matter][matter] on the Texas -Instruments CC13XX_26XX family of Wireless MCUs. - ---- - -- [Matter CC1352 CC2652 All Clusters Example Application](#matter-cc1352-cc2652-all-clusters-example-application) - - [Introduction](#introduction) - - [Device UI](#device-ui) - - [Building](#building) - - [Preparation](#preparation) - - [Compilation](#compilation) - - [Programming](#programming) - - [Code Composer Studio](#code-composer-studio) - - [UniFlash](#uniflash) - - [Viewing Logging Output](#viewing-logging-output) - - [Running the Example](#running-the-example) - - [Provisioning](#provisioning) - - [Bluetooth LE Advertising](#bluetooth-le-advertising) - - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) - - [TI Support](#ti-support) - ---- - -## Introduction - -![CC1352R1_LAUNCHXL](../../pump-app/cc13x2x7_26x2x7/doc/images/cc1352r1_launchxl.jpg) - -The CC13XX_26XX all clusters example application provides the basis to query and -run commands for all currently implemented Matter clusters. This uses the -open-source Matter implementation and the Texas Instruments SimpleLinkâ„¢ CC13XX -and CC26XX software development kit. - -This example is enabled to build for CC2652R7 devices. - -The all-clusters example is intended to serve both as a means to explore the -workings of Matter, as well as a template for creating real products based on -the Texas Instruments devices. - -## Device UI - -This example application has a simple User Interface to depict the state of the -various Matter clusters and the attribute changes associated with them. The user -LEDs on the LaunchPad are used for the onoff, levelcontrol and identify clusters -to provide a working demonstration of the cluster attribute changes. The Green -LED is used to represent attribute changes to endpoint 1 while the Red LED is -used to represent changes to endpoint 2. - -Short presses (less than 1000ms) of the user buttons are used currently unused -in the all-clusters application, but stubs are provided. - -Long presses (greater than 1000ms) of the user buttons are used for controlling -BLE advertisements and resets. The left button (`BTN-1`) is used to perform a -factory reset of the device. The Right button (`BTN-2`) is used to disable BLE -advertisements (if enabled) or enable advertisements (if disabled). - -## Building - -### Preparation - -Some initial setup is necessary for preparing the build environment. This -section will need to be done when migrating to new versions of the SDK. This -guide assumes that the environment is linux based, and recommends Ubuntu 20.04. - -- Download and install [SysConfig][sysconfig] ([recommended - version][sysconfig_recommended]). This can be done simply with the following - commands. - - ``` - $ cd ~ - $ wget https://software-dl.ti.com/ccs/esd/sysconfig/sysconfig-1.11.0_2225-setup.run - $ chmod +x sysconfig-1.11.0_2225-setup.run - $ ./sysconfig-1.11.0_2225-setup.run - ``` - -- Run the bootstrap script to setup the build environment. - - ``` - $ cd ~/connectedhomeip - $ source ./scripts/bootstrap.sh - - ``` - -### Compilation - -It is necessary to activate the environment in every new shell. Then run GN and -Ninja to build the executable. - -- Activate the build environment with the repository activate script. - - ``` - $ cd ~/connectedhomeip - $ source ./scripts/activate.sh - - ``` - -- Run the build to produce a default executable. By default on Linux both the - TI SimpleLink SDK and Sysconfig are located in a `ti` folder in the user's - home directory, and you must provide the absolute path to them. For example - `/home/username/ti/sysconfig_1.11.0`. On Windows the default directory is - `C:\ti`. Take note of this install path, as it will be used in the next - step. - - ``` - $ cd ~/connectedhomeip/examples/all-clusters-minimal-app/cc13x2x7_26x2x7 - $ gn gen out/debug --args="ti_sysconfig_root=\"$HOME/ti/sysconfig_1.11.0\"" - $ ninja -C out/debug - - ``` - -## Programming - -Loading the built image onto a LaunchPad is supported through two methods; -Uniflash and Code Composer Studio (CCS). UniFlash can be used to load the image. -Code Composer Studio can be used to load the image and debug the source code. - -### Code Composer Studio - -Programming with CCS will allow for a full debug environment within the IDE. -This is accomplished by creating a target connection to the XDS110 debugger and -starting a project-less debug session. The CCS IDE will attempt to find the -source files on the local machine based on the debug information embedded within -the ELF. CCS may prompt you to find the source code if the image was built on -another machine or the source code is located in a different location than is -recorded within the ELF. - -Download and install [Code Composer Studio][ccs]. - -First open CCS and create a new workspace. - -Create a target connection (sometimes called the CCXML) for your target SoC and -debugger as described in the [Manual Method][ccs_manual_method] section of the -CCS User's Guide. - -Next initiate a project-less debug session as described in the [Manual -Launch][ccs_manual_launch] section of the CCS User's Guide. - -CCS should switch to the debug view described in the [After -Launch][ccs_after_launch] section of the User's Guide. The SoC core will likely -be disconnected and symbols will not be loaded. Connect to the core as described -in the [Debug View][ccs_debug_view] section of the User's Guide. Once the core -is connected, use the `Load` button on the toolbar to load the ELF image. - -Note that the default configuration of the CCXML uses 2-wire cJTAG instead of -the full 4-wire JTAG connection to match the default jumper configuration of the -LaunchPad. - -### UniFlash - -Uniflash is Texas Instrument's uniform programming tool for embedded processors. -This will allow you to erase, flash, and inspect the SoC without setting up a -debugging environment. - -Download and install [UniFlash][uniflash]. - -First open UniFlash. Debug probes connected to the computer will usually be -displayed under the Detected Devices due to the automatic device detection -feature. If your device does not show up in this view it my be disconnected, or -you may have to create a New Configuration. If you already have a CCXML for your -SoC and debug connection you can use that in the section at the bottom. Once -your device is selected, click the `Start` button within the section to launch -the session. - -Select the ELF image to load on the device with the `Browse` button. This file -is placed in the `out/debug` folder by this guide and ends with the `*.out` file -extension. - -Finally click the `Load Image` button to load the executable image onto the -device. You should be able to see the log output over the XDS110 User UART. - -Note that programming the device through JTAG sets the Halt-in-Boot flag and may -cause issues when performing a software reset. This flag can be reset by -power-cycling the LaunchPad. - -## Viewing Logging Output - -By default the log output will be sent to the Application/User UART. Open a -terminal emulator to that port to see the output with the following options: - -| Parameter | Value | -| ------------ | -------- | -| Speed (baud) | `115200` | -| Data bits | `8` | -| Stop bits | `1` | -| Parity | `None` | -| Flow control | `None` | - -## Running the Example - -Once a device has been flashed with this example, it can now join and operate in -an existing Thread network. The following sections assume that a Thread network -is already active, and has at least one [OpenThread Border -Router][ot_border_router_setup]. - -For insight into what other components are needed to run this example, please -refer to our [Matter Getting Started Guide][matter-e2e-faq]. - -### Provisioning - -Interacting with the application begins by enabling BLE advertisements and then -pairing the device into a Thread network. - -#### Bluetooth LE Advertising - -To provision this example onto a Thread network, the device must be discoverable -over Bluetooth LE. BLE advertising is started by long pressing the right button -(greater than 1000ms), labeled `BTN-2` on the silkscreen. Once the device is -fully provisioned, BLE advertising will stop. - -#### Bluetooth LE Rendezvous - -Pairing this application with `ble-thread` can be done with any of the enabled -[CHIP Controller](../../../src/controller/README.md) applications. Use the -information printed on the console to aide in pairing the device. The controller -application can also be used to control the example app with the cluster -commands. - -## TI Support - -For technical support, please consider creating a post on TI's [E2E forum][e2e]. -Additionally, we welcome any feedback. - -[matter]: https://github.com/project-chip/connectedhomeip -[ccs]: https://www.ti.com/tool/CCSTUDIO -[ccs_after_launch]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#after-launch -[ccs_debug_view]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#debug-view -[ccs_manual_launch]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#manual-launch -[ccs_manual_method]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#manual-method -[cc1352r1_launchxl]: https://www.ti.com/tool/LAUNCHXL-CC1352R1 -[e2e]: https://e2e.ti.com/support/wireless-connectivity/zigbee-and-thread -[matter-e2e-faq]: - https://e2e.ti.com/support/wireless-connectivity/zigbee-thread-group/zigbee-and-thread/f/zigbee-thread-forum/1082428/faq-cc2652r7-matter----getting-started-guide -[sysconfig]: https://www.ti.com/tool/SYSCONFIG -[sysconfig_recommended]: - https://software-dl.ti.com/ccs/esd/sysconfig/sysconfig-1.11.0_2225-setup.run -[ti_thread_dnd]: - https://www.ti.com/wireless-connectivity/thread/design-development.html -[ot_border_router_setup]: https://openthread.io/guides/border-router/build -[uniflash]: https://www.ti.com/tool/download/UNIFLASH diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp b/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp deleted file mode 100644 index b55ffa374e9788..00000000000000 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp +++ /dev/null @@ -1,177 +0,0 @@ - -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * 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 "ClusterManager.h" -#include "Globals.h" -#include -#include -#include -#include -#include - -#ifdef AUTO_PRINT_METRICS -#include -#endif - -using namespace ::chip; -using namespace ::chip::Inet; -using namespace ::chip::System; -using namespace ::chip::DeviceLayer; - -constexpr uint32_t kIdentifyTimerDelayMS = 250; -constexpr uint32_t kIdentifyTimerDelayPerSec = 4; -ClusterManager ClusterManager::sCluster; - -#define ENDPOINT_ID_0 (0) -#define ENDPOINT_ID_1 (1) -#define ENDPOINT_ID_2 (2) - -void OnIdentifyTriggerEffect(Identify * identify) -{ - switch (identify->mCurrentEffectIdentifier) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - break; - default: - PLAT_LOG("No identifier effect"); - break; - } - return; -} - -Identify gIdentify0 = { - chip::EndpointId{ 0 }, - [](Identify *) { PLAT_LOG("onIdentifyStart"); }, - [](Identify *) { PLAT_LOG("onIdentifyStop"); }, - EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, - OnIdentifyTriggerEffect, -}; - -Identify gIdentify1 = { - chip::EndpointId{ 1 }, - [](Identify *) { PLAT_LOG("onIdentifyStart"); }, - [](Identify *) { PLAT_LOG("onIdentifyStop"); }, - EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, - OnIdentifyTriggerEffect, -}; - -void ClusterManager::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) -{ - VerifyOrExit(attributeId == app::Clusters::OnOff::Attributes::OnOff::Id, - PLAT_LOG("Unhandled Attribute ID: '0x%04x", attributeId)); - VerifyOrExit(endpointId == ENDPOINT_ID_1 || endpointId == ENDPOINT_ID_2, - PLAT_LOG("Unexpected EndPoint ID: `0x%02x'", endpointId)); - - // At this point we can assume that value points to a bool value. - mEndpointOnOffState[endpointId - 1] = *value; - endpointId == ENDPOINT_ID_1 ? LED_write(sAppGreenHandle, *value) : LED_write(sAppRedHandle, *value); - -exit: - return; -} - -void ClusterManager::OnLevelControlAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) -{ - bool onOffState = mEndpointOnOffState[endpointId - 1]; - uint8_t brightness = onOffState ? *value : 0; - - VerifyOrExit(brightness > 0, PLAT_LOG("Brightness set to 0, ignoring")); - VerifyOrExit(attributeId == app::Clusters::LevelControl::Attributes::CurrentLevel::Id, - PLAT_LOG("Unhandled Attribute ID: '0x%04x", attributeId)); - VerifyOrExit(endpointId == ENDPOINT_ID_1 || endpointId == ENDPOINT_ID_2, - PLAT_LOG("Unexpected EndPoint ID: `0x%02x'", endpointId)); - - if (brightness > LED_BRIGHTNESS_MAX) - { - brightness = LED_BRIGHTNESS_MAX; - } - - endpointId == ENDPOINT_ID_1 ? LED_setOn(sAppGreenHandle, brightness) : LED_setOn(sAppRedHandle, brightness); - -exit: - return; -} - -void ClusterManager::OnColorControlAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) -{ - using namespace app::Clusters::ColorControl::Attributes; - - VerifyOrExit(attributeId == CurrentHue::Id || attributeId == CurrentSaturation::Id, - PLAT_LOG("Unhandled AttributeId ID: '0x%04x", attributeId)); - VerifyOrExit(endpointId == ENDPOINT_ID_1 || endpointId == ENDPOINT_ID_2, - PLAT_LOG("Unexpected EndPoint ID: `0x%02x'", endpointId)); - - if (endpointId == ENDPOINT_ID_1) - { - uint8_t hue, saturation; - if (attributeId == CurrentHue::Id) - { - hue = *value; - /* Read Current Saturation value when Attribute change callback for HUE Attribute */ - CurrentSaturation::Get(endpointId, &saturation); - } - else - { - saturation = *value; - /* Read Current Hue value when Attribute change callback for SATURATION Attribute */ - CurrentHue::Get(endpointId, &hue); - } - PLAT_LOG("Color Control triggered: Hue: %d Saturation: %d", hue, saturation); - } -exit: - return; -} - -void ClusterManager::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint16_t size, - uint8_t * value) -{ - if (attributeId == app::Clusters::Identify::Attributes::IdentifyTime::Id && size == 2) - { - uint16_t identifyTime; - memcpy(&identifyTime, value, size); - if (identifyTime) - { - // Currently we have no separate indicator LEDs on each endpoints. - // We are using LED1 for endpoint 0,1 and LED2 for endpoint 2 - if (endpointId == ENDPOINT_ID_2) - { - LED_startBlinking(sAppGreenHandle, kIdentifyTimerDelayMS, identifyTime * kIdentifyTimerDelayPerSec); - } - else - { - LED_startBlinking(sAppRedHandle, kIdentifyTimerDelayMS, identifyTime * kIdentifyTimerDelayPerSec); - } - } - else - { - bool onOffState; - endpointId == ENDPOINT_ID_0 ? onOffState = mEndpointOnOffState[0] : onOffState = mEndpointOnOffState[endpointId - 1]; - endpointId == ENDPOINT_ID_2 ? LED_write(sAppRedHandle, onOffState) : LED_write(sAppGreenHandle, onOffState); - } - } -} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/Globals.cpp b/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/Globals.cpp deleted file mode 100644 index 01a945e1a33d12..00000000000000 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/Globals.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * 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 "Globals.h" - -LED_Handle sAppRedHandle; -LED_Handle sAppGreenHandle; diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h b/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h deleted file mode 100644 index 1599ef1ef19264..00000000000000 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) - * All rights reserved. - * - * 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. - */ - -/** - * @file ClusterManager.h - * - * Declarations for the ClusterManager callbacks for this application - * - **/ - -#pragma once - -#include -#include -#include - -class ClusterManager -{ -public: - void OnOnOffPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); - void OnLevelControlAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); - void OnColorControlAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); - void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint16_t size, - uint8_t * value); - -private: - friend ClusterManager & ClusterMgr(void); - bool mEndpointOnOffState[2]; - static ClusterManager sCluster; -}; - -inline ClusterManager & ClusterMgr(void) -{ - return ClusterManager::sCluster; -} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/.gn b/examples/lighting-app/cc13x2x7_26x2x7/.gn similarity index 99% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/.gn rename to examples/lighting-app/cc13x2x7_26x2x7/.gn index 0adefc6ff99c6a..3d48789e30ab3d 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/.gn +++ b/examples/lighting-app/cc13x2x7_26x2x7/.gn @@ -23,5 +23,6 @@ check_system_includes = true default_args = { target_cpu = "arm" target_os = "freertos" + import("//args.gni") } diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/BUILD.gn b/examples/lighting-app/cc13x2x7_26x2x7/BUILD.gn similarity index 71% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/BUILD.gn rename to examples/lighting-app/cc13x2x7_26x2x7/BUILD.gn index 6c20ed346ec530..aec1e66b95939c 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/lighting-app/cc13x2x7_26x2x7/BUILD.gn @@ -26,18 +26,17 @@ import("${ti_simplelink_sdk_build_root}/ti_simplelink_sdk.gni") assert(current_os == "freertos") -project_dir = "${chip_root}/examples/all-clusters-minimal-app/cc13x2x7_26x2x7" +project_dir = "${chip_root}/examples/lighting-app/cc13x2x7_26x2x7" ti_simplelink_sdk("sdk") { - include_dirs = [ "${project_dir}/main/include" ] - public_configs = [ ":all-clusters-minimal-app_config" ] + include_dirs = [ "${project_dir}/include" ] + public_configs = [ ":lighting_app_config" ] } ti_sysconfig("sysconfig") { sources = [ "${project_dir}/chip.syscfg" ] outputs = [ - "ti_devices_config.c", "ti_radio_config.c", "ti_radio_config.h", "ti_drivers_config.c", @@ -71,25 +70,22 @@ ti_sysconfig("sysconfig") { ] } -ti_simplelink_executable("all-clusters-minimal-app") { - output_name = "chip-${ti_simplelink_board}-all-clusters-minimal-example.out" +ti_simplelink_executable("lighting_app") { + output_name = "chip-${ti_simplelink_board}-lighting-example.out" sources = [ - "${chip_root}/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp", - "${chip_root}/examples/all-clusters-app/all-clusters-common/src/bridged-actions-stub.cpp", - "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", - "${project_dir}/main/AppTask.cpp", - "${project_dir}/main/ClusterManager.cpp", - "${project_dir}/main/Globals.cpp", - "${project_dir}/main/ZclCallbacks.cpp", - "${project_dir}/main/main.cpp", + "${project_dir}/src/AppTask.cpp", + "${project_dir}/src/LightingManager.cpp", + "${project_dir}/src/ZclCallbacks.cpp", + "${project_dir}/src/main.cpp", ] deps = [ ":sdk", ":sysconfig", - "${chip_root}/examples/all-clusters-minimal-app/all-clusters-common", + "${chip_root}/examples/lighting-app/lighting-common", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/src/lib", ] @@ -101,8 +97,6 @@ ti_simplelink_executable("all-clusters-minimal-app") { include_dirs = [ "${project_dir}", - "${project_dir}/main", - "${chip_root}/examples/all-clusters-app/all-clusters-common/include", "${chip_root}/examples/providers/", ] @@ -116,7 +110,7 @@ ti_simplelink_executable("all-clusters-minimal-app") { } group("cc13x2x7_26x2x7") { - deps = [ ":all-clusters-minimal-app" ] + deps = [ ":lighting_app" ] } group("default") { diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/args.gni b/examples/lighting-app/cc13x2x7_26x2x7/args.gni similarity index 83% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/args.gni rename to examples/lighting-app/cc13x2x7_26x2x7/args.gni index 9228f70c4a0f03..a6a8662c4d14cb 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/args.gni +++ b/examples/lighting-app/cc13x2x7_26x2x7/args.gni @@ -27,17 +27,15 @@ ti_simplelink_board = "LP_CC2652R7" optimize_debug_level = "s" lwip_debug = false -chip_enable_ota_requestor = false +chip_enable_ota_requestor = true -# Disable FTD Build for all-clusters app to save Flash chip_openthread_ftd = false +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" # Disable CHIP Logging -chip_progress_logging = false - -# Dsiable verbose logs for all-clusters app to save Flash -chip_detail_logging = false -chip_automation_logging = false +#chip_progress_logging = false +#chip_detail_logging = false +#chip_automation_logging = false # BLE options chip_config_network_layer_ble = true @@ -47,6 +45,6 @@ chip_config_network_layer_ble = true chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" -matter_device_pid = "0x8006" +matter_device_pid = "0x8005" matter_software_ver = "0x0001" matter_software_ver_str = "1.0d1" diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/build_overrides b/examples/lighting-app/cc13x2x7_26x2x7/build_overrides similarity index 100% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/build_overrides rename to examples/lighting-app/cc13x2x7_26x2x7/build_overrides diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/chip.syscfg b/examples/lighting-app/cc13x2x7_26x2x7/chip.syscfg similarity index 82% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/chip.syscfg rename to examples/lighting-app/cc13x2x7_26x2x7/chip.syscfg index 4f02a9fd40da9a..995ad22af6b435 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/lighting-app/cc13x2x7_26x2x7/chip.syscfg @@ -26,11 +26,10 @@ var LED = scripting.addModule("/ti/drivers/apps/LED"); var NVS = scripting.addModule("/ti/drivers/NVS"); var RF = scripting.addModule("/ti/drivers/RF"); var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); -var RTOS = scripting.addModule("/ti/drivers/RTOS"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); var TRNG = scripting.addModule("/ti/drivers/TRNG"); -var Thread = scripting.addModule("/ti/thread/thread"); var SHA2 = scripting.addModule("/ti/drivers/SHA2"); -var UART = scripting.addModule("/ti/drivers/UART"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); var ble = scripting.addModule("/ti/ble5stack/ble"); var dmm = scripting.addModule("/ti/dmm/dmm"); var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); @@ -50,12 +49,11 @@ var LED2 = LED.addInstance(); var TRNG1 = TRNG.addInstance(); var TRNG2 = TRNG.addInstance(); var TRNG3 = TRNG.addInstance(); -var UART1 = UART.addInstance(); +var UART2 = UART2.addInstance(); var AESCTRDRBG1 = AESCTRDRBG.addInstance(); var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; AESCCM1.$name = "CONFIG_AESCCM0"; @@ -64,9 +62,6 @@ AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -/* RTOS */ -RTOS.name = "FreeRTOS"; - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -89,11 +84,11 @@ for(var setting in ccfgSettings) CCFG[setting] = ccfgSettings[setting]; } -CCFG.enableCodeGeneration = true; +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; /* NVS */ NVS1.$name = "CONFIG_NVSINTERNAL"; - NVS1.internalFlash.regionBase = 0xAA000; NVS1.internalFlash.regionSize = 0x4000; @@ -113,6 +108,58 @@ for(var setting in rfDesignSettings) RFDesign[setting] = rfDesignSettings[setting]; } +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -128,16 +175,14 @@ LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; /* Debug UART */ -UART1.$hardware = system.deviceData.board.components.XDS110UART; -UART1.$name = "CONFIG_UART_DEBUG"; +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; TRNG3.$name = "CONFIG_TRNG_APP"; -RTOS.name = "FreeRTOS"; - /* BLE */ ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; ble.maxConnNum = 1; @@ -145,11 +190,12 @@ ble.numOfAdvSets = 1; ble.lockProject = true; ble.oneLibSizeOpt = true; ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; ble.connUpdateParamsPeripheral.reqMinConnInt = 30; ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h b/examples/lighting-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h similarity index 95% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h rename to examples/lighting-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h index 4d50a5a05c08d9..0f5090d7d9f320 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h +++ b/examples/lighting-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h @@ -55,7 +55,9 @@ * physical device, a change to its packaging, and/or a change to its marketing presentation. * This value is generally *not* incremented for device software versions. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION #define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 +#endif /** * Values set by args.gni: @@ -79,7 +81,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 1 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT @@ -108,13 +110,13 @@ * * @brief Defines the maximum number of CommandHandler, limits the number of active commands transactions on server. */ -#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 1 +#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 2 /** * @def CHIP_IM_MAX_NUM_WRITE_HANDLER * * @brief Defines the maximum number of WriteHandler, limits the number of active write transactions on server. */ -#define CHIP_IM_MAX_NUM_WRITE_HANDLER 1 +#define CHIP_IM_MAX_NUM_WRITE_HANDLER 2 #endif // CHIP_PROJECT_CONFIG_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h b/examples/lighting-app/cc13x2x7_26x2x7/src/AppConfig.h similarity index 75% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h rename to examples/lighting-app/cc13x2x7_26x2x7/src/AppConfig.h index 43f9362e0341b9..a818b21d641875 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppConfig.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2020 Project CHIP Authors * All rights reserved. * @@ -16,20 +15,21 @@ * limitations under the License. */ -#pragma once +#ifndef APP_CONFIG_H +#define APP_CONFIG_H -#include // Logging #ifdef __cplusplus extern "C" { #endif -int cc13x2_26x2LogInit(void); -void cc13x2_26x2Log(const char * aFormat, ...); -#define PLAT_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); + +#define ACTUATOR_MOVEMENT_PERIOD_MS 1000 #ifdef __cplusplus } #endif -extern LED_Handle sAppRedHandle; -extern LED_Handle sAppGreenHandle; +#endif // APP_CONFIG_H diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h b/examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h new file mode 100644 index 00000000000000..9c55e1bf674531 --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h @@ -0,0 +1,84 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * 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. + */ +#ifndef APP_EVENT_H +#define APP_EVENT_H + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventType + { + kEventType_None = 0, + kEventType_ButtonLeft, + kEventType_ButtonRight, + kEventType_AppEvent, + kEventType_IdentifyStart, + kEventType_IdentifyStop, + kEventType_Light, + kEventType_Timer, + }; + + enum AppEventButtonType + { + kAppEventButtonType_None = 0, + kAppEventButtonType_Clicked, + kAppEventButtonType_LongClicked, + }; + + enum AppEventIdentifyType + { + kAppEventIdentifyType_Blink = 0, + kAppEventIdentifyType_Breathe, + kAppEventIdentifyType_Okay, + kAppEventIdentifyType_Finish, + kAppEventIdentifyType_Stop, + }; + + enum AppEventType Type; + + union + { + struct + { + enum AppEventButtonType Type; + } ButtonEvent; + + struct + { + void * Context; + } TimerEvent; + + struct + { + uint8_t Action; + int32_t Actor; + void * Context; + } LightEvent; + + struct + { + enum AppEventIdentifyType Type; + } IdentifyEvent; + }; + + EventHandler Handler; +}; + +#endif // APP_EVENT_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.cpp similarity index 56% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/AppTask.cpp rename to examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.cpp index 871a5f71d6acc0..945679b5e1e853 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.cpp @@ -20,13 +20,12 @@ #include "AppTask.h" #include "AppConfig.h" #include "AppEvent.h" -#include -#include #include "FreeRTOS.h" -#include "Globals.h" + #include #include +#include #include #include @@ -36,15 +35,19 @@ #include #include #include -#include +#include #endif + #include #include -#ifdef AUTO_PRINT_METRICS -#include -#endif +#include + +#include +#include #include +#include +#include #include #include @@ -52,10 +55,19 @@ /* syscfg */ #include -#define APP_TASK_STACK_SIZE (5000) +#define APP_TASK_STACK_SIZE (4096) #define APP_TASK_PRIORITY 4 #define APP_EVENT_QUEUE_SIZE 10 +#define IDENTIFY_TRIGGER_EFFECT_BLINK 0 +#define IDENTIFY_TRIGGER_EFFECT_BREATHE 1 +#define IDENTIFY_TRIGGER_EFFECT_OKAY 2 +#define IDENTIFY_TRIGGER_EFFECT_FINISH_STOP 3 + +static uint32_t identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + +#define LIGHTING_APPLICATION_IDENTIFY_ENDPOINT 1 + using namespace ::chip; using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; @@ -63,14 +75,14 @@ using namespace ::chip::DeviceLayer; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; +static LED_Handle sAppRedHandle; +static LED_Handle sAppGreenHandle; static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; static DeviceInfoProviderImpl sExampleDeviceInfoProvider; AppTask AppTask::sAppTask; -constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; - #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR static DefaultOTARequestor sRequestorCore; static DefaultOTARequestorStorage sRequestorStorage; @@ -91,54 +103,8 @@ void InitializeOTARequestor(void) } #endif -#ifdef AUTO_PRINT_METRICS -static void printMetrics(void) -{ - chip::DeviceLayer::ThreadMetrics *threadMetricsOut, *currThread; - uint64_t heapFree, heapUsed; - - DiagnosticDataProviderImpl::GetDefaultInstance().GetCurrentHeapUsed(heapUsed); - DiagnosticDataProviderImpl::GetDefaultInstance().GetCurrentHeapFree(heapFree); - DiagnosticDataProviderImpl::GetDefaultInstance().GetThreadMetrics(&threadMetricsOut); - - PLAT_LOG("Heap Metrics\n Heap Free: %d Heap Used: %d", (uint32_t) heapFree, (uint32_t) heapUsed); - - PLAT_LOG("Thread Metrics\n"); - - currThread = threadMetricsOut; - while (currThread) - { - PLAT_LOG("Task Name: %s ID: %d Stack Free Min: %d", currThread->name, (uint32_t) currThread->id, - (uint32_t) currThread->stackFreeMinimum); - - currThread = currThread->Next; - } - - DiagnosticDataProviderImpl::GetDefaultInstance().ReleaseThreadMetrics(threadMetricsOut); -} -#endif - -void DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEConnectionEstablished: - PLAT_LOG("CHIPoBLE connection established"); - break; - - case DeviceEventType::kCHIPoBLEConnectionClosed: - PLAT_LOG("CHIPoBLE disconnected"); - break; - - case DeviceEventType::kCommissioningComplete: - PLAT_LOG("Commissioning complete"); - break; - } - -#ifdef AUTO_PRINT_METRICS - printMetrics(); -#endif -} +::Identify stIdentify = { LIGHTING_APPLICATION_IDENTIFY_ENDPOINT, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, AppTask::TriggerIdentifyEffectHandler }; int AppTask::StartAppTask() { @@ -148,7 +114,7 @@ int AppTask::StartAppTask() if (sAppEventQueue == NULL) { PLAT_LOG("Failed to allocate app event queue"); - while (true) + while (1) ; } @@ -157,46 +123,50 @@ int AppTask::StartAppTask() pdPASS) { PLAT_LOG("Failed to create app task"); - while (true) + while (1) ; } return ret; } -int AppTask::Init() +// Action initiated callback +void uiTurnOn(void) { - LED_Params ledParams; - Button_Params buttonParams; + PLAT_LOG("Light On initiated"); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} - cc13x2_26x2LogInit(); +// Action completed callback +void uiTurnedOn(void) +{ + PLAT_LOG("Light On completed"); + LED_stopBlinking(sAppRedHandle); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); +} - // Initialize LEDs - PLAT_LOG("Initialize LEDs"); - LED_init(); +// Action initiated callback +void uiTurnOff(void) +{ + PLAT_LOG("Light Off initiated"); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} - LED_Params_init(&ledParams); // default PWM LED - sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); +// Action completed callback +void uiTurnedOff(void) +{ + PLAT_LOG("Light Off completed"); + LED_stopBlinking(sAppRedHandle); LED_setOff(sAppRedHandle); +} - LED_Params_init(&ledParams); // default PWM LED - sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); - LED_setOff(sAppGreenHandle); - - // Initialize buttons - PLAT_LOG("Initialize buttons"); - Button_init(); +int AppTask::Init() +{ + LED_Params ledParams; + Button_Params buttonParams; - Button_Params_init(&buttonParams); - buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; - buttonParams.longPressDuration = 1000U; // ms - sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); - Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); - - Button_Params_init(&buttonParams); - buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; - buttonParams.longPressDuration = 1000U; // ms - sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); - Button_setCallback(sAppRightHandle, ButtonRightEventHandler); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack Platform::MemoryInit(); @@ -205,7 +175,7 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("PlatformMgr().InitChipStack() failed"); - while (true) + while (1) ; } @@ -213,15 +183,18 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("ThreadStackMgr().InitThreadStack() failed"); - while (true) + while (1) ; } - +#if CHIP_DEVICE_CONFIG_THREAD_FTD + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#else ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif if (ret != CHIP_NO_ERROR) { PLAT_LOG("ConnectivityMgr().SetThreadDeviceType() failed"); - while (true) + while (1) ; } @@ -229,7 +202,7 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("PlatformMgr().StartEventLoopTask() failed"); - while (true) + while (1) ; } @@ -237,32 +210,68 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("ThreadStackMgr().StartThreadTask() failed"); - while (true) + while (1) ; } // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - static chip::CommonCaseDeviceServerInitParams initParams; + static CommonCaseDeviceServerInitParams initParams; (void) initParams.InitializeStaticResourcesBeforeServerInit(); // Initialize info provider sExampleDeviceInfoProvider.SetStorageDelegate(initParams.persistentStorageDelegate); SetDeviceInfoProvider(&sExampleDeviceInfoProvider); - chip::Server::GetInstance().Init(initParams); - - ConfigurationMgr().LogDeviceConfig(); + Server::GetInstance().Init(initParams); // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + // Initialize LEDs + PLAT_LOG("Initialize LEDs"); + LED_init(); + + LED_Params_init(&ledParams); // default PWM LED + sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); + LED_setOff(sAppRedHandle); + + LED_Params_init(&ledParams); // default PWM LED + sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); + LED_setOff(sAppGreenHandle); - // We only have network commissioning on endpoint 0. - emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); + // Initialize buttons + PLAT_LOG("Initialize buttons"); + Button_init(); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); + Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); + Button_setCallback(sAppRightHandle, ButtonRightEventHandler); + + ret = LightMgr().Init(); + + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("LightMgr().Init() failed"); + while (1) + ; + } + + LightMgr().SetCallbacks(ActionInitiated, ActionCompleted); - // Register a function to receive events from the CHIP device layer. Note that calls to - // this function will happen on the CHIP event loop thread, not the app_main thread. - PlatformMgr().AddEventHandler(DeviceEventCallback, reinterpret_cast(nullptr)); + ConfigurationMgr().LogDeviceConfig(); #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR InitializeOTARequestor(); @@ -279,7 +288,7 @@ void AppTask::AppTaskMain(void * pvParameter) sAppTask.Init(); - while (true) + while (1) { /* Task pend until we have stuff to do */ if (xQueueReceive(sAppEventQueue, &event, portMAX_DELAY) == pdTRUE) @@ -289,14 +298,6 @@ void AppTask::AppTaskMain(void * pvParameter) } } -void AppTask::PostEvent(const AppEvent * aEvent) -{ - if (xQueueSend(sAppEventQueue, aEvent, 0) != pdPASS) - { - /* Failed to post the message */ - } -} - void AppTask::ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events) { AppEvent event; @@ -337,13 +338,80 @@ void AppTask::ButtonRightEventHandler(Button_Handle handle, Button_EventMask eve } } +void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) +{ + if (aAction == LightingManager::ON_ACTION) + { + uiTurnOn(); + } + else if (aAction == LightingManager::OFF_ACTION) + { + uiTurnOff(); + } +} + +void AppTask::ActionCompleted(LightingManager::Action_t aAction) +{ + if (aAction == LightingManager::ON_ACTION) + { + uiTurnedOn(); + } + else if (aAction == LightingManager::OFF_ACTION) + { + uiTurnedOff(); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (xPortIsInsideInterrupt()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (status != pdTRUE) + { + PLAT_LOG("Failed to post event to app task event queue"); + } + } + else + { + PLAT_LOG("Event Queue is NULL should never happen"); + } +} + void AppTask::DispatchEvent(AppEvent * aEvent) { + int32_t actor; + switch (aEvent->Type) { + case AppEvent::kEventType_Light: { + actor = aEvent->LightEvent.Actor; + LightMgr().IsLightOn() ? LightMgr().InitiateAction(actor, LightingManager::OFF_ACTION) + : LightMgr().InitiateAction(actor, LightingManager::ON_ACTION); + } case AppEvent::kEventType_ButtonLeft: if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) { + actor = AppEvent::kEventType_ButtonLeft; + LightMgr().InitiateAction(actor, LightingManager::ON_ACTION); } else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) { @@ -354,6 +422,8 @@ void AppTask::DispatchEvent(AppEvent * aEvent) case AppEvent::kEventType_ButtonRight: if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) { + actor = AppEvent::kEventType_ButtonRight; + LightMgr().InitiateAction(actor, LightingManager::OFF_ACTION); } else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) { @@ -378,6 +448,33 @@ void AppTask::DispatchEvent(AppEvent * aEvent) } break; + case AppEvent::kEventType_IdentifyStart: + switch (identify_trigger_effect) + { + case IDENTIFY_TRIGGER_EFFECT_BLINK: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 1000, LED_BLINK_FOREVER); + break; + case IDENTIFY_TRIGGER_EFFECT_BREATHE: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 100, LED_BLINK_FOREVER); + break; + case IDENTIFY_TRIGGER_EFFECT_OKAY: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 500, LED_BLINK_FOREVER); + break; + default: + break; + } + PLAT_LOG("Identify started"); + break; + + case AppEvent::kEventType_IdentifyStop: + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); + PLAT_LOG("Identify stopped"); + break; + case AppEvent::kEventType_AppEvent: if (NULL != aEvent->Handler) { @@ -390,3 +487,54 @@ void AppTask::DispatchEvent(AppEvent * aEvent) break; } } + +void AppTask::IdentifyStartHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + sAppTask.PostEvent(&event); +} + +void AppTask::IdentifyStopHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStop; + sAppTask.PostEvent(&event); +} + +void AppTask::TriggerIdentifyEffectHandler(::Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + PLAT_LOG("Starting blink identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_BLINK; + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + PLAT_LOG("Starting breathe identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_BREATHE; + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + PLAT_LOG("Starting okay identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_OKAY; + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + PLAT_LOG("Channel Change identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + PLAT_LOG("Finish identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + IdentifyStopHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + PLAT_LOG("Stop identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + IdentifyStopHandler(identify); + break; + default: + PLAT_LOG("No identifier effect"); + } +} diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h new file mode 100644 index 00000000000000..3d305601bc12f7 --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "FreeRTOS.h" +#include "semphr.h" +#include "task.h" + +#include "AppEvent.h" +#include "LightingManager.h" + +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) +#define APP_ERROR_ALLOCATION_FAILED CHIP_APPLICATION_ERROR(0x07) +struct Identify; + +class AppTask +{ + +public: + int StartAppTask(); + static void AppTaskMain(void * pvParameter); + + static AppTask & GetAppTask() { return sAppTask; } + + void PostLightActionRequest(int32_t aActor, LightingManager::Action_t aAction); + void PostEvent(const AppEvent * event); + + static void IdentifyStartHandler(::Identify *); + static void IdentifyStopHandler(::Identify *); + static void TriggerIdentifyEffectHandler(::Identify * identify); + +private: + friend AppTask & GetAppTask(void); + + int Init(); + + static void ActionInitiated(LightingManager::Action_t aAction, int32_t aActor); + static void ActionCompleted(LightingManager::Action_t aAction); + + void DispatchEvent(AppEvent * event); + static void UpdateClusterState(intptr_t context); + static void SingleButtonEventHandler(AppEvent * aEvent); + static void ButtonTimerEventHandler(AppEvent * aEvent); + + static void ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events); + static void ButtonRightEventHandler(Button_Handle handle, Button_EventMask events); + static void TimerEventHandler(void * p_context); + + enum Function_t + { + kFunction_NoneSelected = 0, + kFunction_SoftwareUpdate = 0, + kFunction_FactoryReset, + kFunction_Invalid + } Function; + + Function_t mFunction; + bool mFunctionTimerActive; + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp new file mode 100644 index 00000000000000..ed5fc52e7e5638 --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp @@ -0,0 +1,176 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * 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 "LightingManager.h" + +#include "AppConfig.h" +#include "AppTask.h" +#include + +using namespace chip; +using namespace ::chip::DeviceLayer; + +LightingManager LightingManager::sLight; + +TimerHandle_t sLightTimer; + +CHIP_ERROR LightingManager::Init() +{ + // Create FreeRTOS sw timer for light timer. + sLightTimer = xTimerCreate("lightTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = light obj context + TimerEventHandler // timer callback handler + ); + + if (sLightTimer == NULL) + { + PLAT_LOG("sLightTimer timer create failed"); + } + + bool currentLedState; + // read current on/off value on endpoint one. + OnOffServer::Instance().getOnOffValue(1, ¤tLedState); + + mState = currentLedState ? kState_OnCompleted : kState_OffCompleted; + + return CHIP_NO_ERROR; +} + +void LightingManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) +{ + mActionInitiated_CB = aActionInitiated_CB; + mActionCompleted_CB = aActionCompleted_CB; +} + +bool LightingManager::IsActionInProgress() +{ + return (mState == kState_OffInitiated || mState == kState_OnInitiated); +} + +bool LightingManager::IsLightOn() +{ + return (mState == kState_OnCompleted); +} + +bool LightingManager::InitiateAction(int32_t aActor, Action_t aAction) +{ + bool action_initiated = false; + State_t new_state; + + // Initiate Turn On/Off Action only when the previous one is complete. + if (mState == kState_OffCompleted && aAction == ON_ACTION) + { + action_initiated = true; + + new_state = kState_OnInitiated; + } + else if (mState == kState_OnCompleted && aAction == OFF_ACTION) + { + action_initiated = true; + + new_state = kState_OffInitiated; + } + + if (action_initiated) + { + StartTimer(ACTUATOR_MOVEMENT_PERIOD_MS); + + // Since the timer started successfully, update the state and trigger callback + mState = new_state; + + if (mActionInitiated_CB) + { + mActionInitiated_CB(aAction, aActor); + } + } + + return action_initiated; +} + +void LightingManager::StartTimer(uint32_t aTimeoutMs) +{ + if (xTimerIsTimerActive(sLightTimer)) + { + PLAT_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sLightTimer, pdMS_TO_TICKS(aTimeoutMs), 100) != pdPASS) + { + PLAT_LOG("sLightTimer timer start() failed"); + } +} + +void LightingManager::CancelTimer(void) +{ + if (xTimerStop(sLightTimer, 0) == pdFAIL) + { + PLAT_LOG("sLightTimer stop() failed"); + } +} + +void LightingManager::TimerEventHandler(TimerHandle_t xTimer) +{ + // Get light obj context from timer id. + LightingManager * light = static_cast(pvTimerGetTimerID(xTimer)); + + // The timer event handler will be called in the context of the timer task + // once sLightTimer expires. Post an event to apptask queue with the actual handler + // so that the event can be handled in the context of the apptask. + AppEvent event; + event.Type = AppEvent::kEventType_AppEvent; + event.LightEvent.Context = light; + + event.Handler = ActuatorMovementTimerEventHandler; + + AppTask::GetAppTask().PostEvent(&event); +} + +void LightingManager::ActuatorMovementTimerEventHandler(AppEvent * aEvent) +{ + Action_t actionCompleted = INVALID_ACTION; + + LightingManager * light = static_cast(aEvent->LightEvent.Context); + + if (light->mState == kState_OffInitiated) + { + light->mState = kState_OffCompleted; + actionCompleted = OFF_ACTION; + OnOffServer::Instance().setOnOffValue(1, 0, false); + } + else if (light->mState == kState_OnInitiated) + { + light->mState = kState_OnCompleted; + actionCompleted = ON_ACTION; + OnOffServer::Instance().setOnOffValue(1, 1, false); + } + + if (actionCompleted != INVALID_ACTION) + { + if (light->mActionCompleted_CB) + { + light->mActionCompleted_CB(actionCompleted); + } + } +} diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h new file mode 100644 index 00000000000000..818feed45ee87a --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h @@ -0,0 +1,82 @@ +/* + * + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include + +#include + +class LightingManager +{ +public: + enum Action_t + { + ON_ACTION = 0, + OFF_ACTION, + + INVALID_ACTION + } Action; + + enum State_t + { + kState_OffInitiated = 0, + kState_OffCompleted, + kState_OnInitiated, + kState_OnCompleted, + } State; + + CHIP_ERROR Init(); + bool IsLightOn(); + bool IsActionInProgress(); + bool InitiateAction(int32_t aActor, Action_t aAction); + + typedef void (*Callback_fn_initiated)(Action_t, int32_t aActor); + typedef void (*Callback_fn_completed)(Action_t); + void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); + + static void OnTriggerOffWithEffect(OnOffEffect * effect); + +private: + friend LightingManager & LightMgr(void); + State_t mState; + + Callback_fn_initiated mActionInitiated_CB; + Callback_fn_completed mActionCompleted_CB; + + void CancelTimer(void); + void StartTimer(uint32_t aTimeoutMs); + + static void TimerEventHandler(TimerHandle_t xTimer); + static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); + static void OffEffectTimerEventHandler(AppEvent * aEvent); + + static LightingManager sLight; +}; + +inline LightingManager & LightMgr(void) +{ + return LightingManager::sLight; +} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp similarity index 57% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp rename to examples/lighting-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp index ba3f7bd1c205f8..7bb20a45944545 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors - * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * Copyright (c) 2020 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. @@ -22,17 +21,12 @@ */ #include "AppConfig.h" -#include "Globals.h" -#include - -#include "ClusterManager.h" +#include "LightingManager.h" #include #include -#include -#include -#include -#include +#include +#include using namespace ::chip; using namespace ::chip::app::Clusters; @@ -40,35 +34,26 @@ using namespace ::chip::app::Clusters; void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, uint8_t * value) { - EndpointId endpoint = attributePath.mEndpointId; ClusterId clusterId = attributePath.mClusterId; AttributeId attributeId = attributePath.mAttributeId; - PLAT_LOG("MatterPostAttributeChangeCallback - Cluster ID: " ChipLogFormatMEI - ", EndPoint ID: '0x%02x', Attribute ID: " ChipLogFormatMEI, - ChipLogValueMEI(clusterId), endpoint, ChipLogValueMEI(attributeId)); + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); - switch (clusterId) + if (clusterId == OnOff::Id && attributeId == OnOff::Attributes::OnOff::Id) { - case OnOff::Id: - ClusterMgr().OnOnOffPostAttributeChangeCallback(endpoint, attributeId, value); - break; - - case Identify::Id: - ClusterMgr().OnIdentifyPostAttributeChangeCallback(endpoint, attributeId, size, value); - break; - - case LevelControl::Id: - ClusterMgr().OnLevelControlAttributeChangeCallback(endpoint, attributeId, value); - break; - - case ColorControl::Id: - ClusterMgr().OnColorControlAttributeChangeCallback(endpoint, attributeId, value); - break; - default: - PLAT_LOG("Unhandled cluster ID: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); - break; + LightMgr().InitiateAction(AppEvent::kEventType_Light, *value ? LightingManager::ON_ACTION : LightingManager::OFF_ACTION); + } + else if (clusterId == Identify::Id) + { + ChipLogProgress(Zcl, "Identify attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + } + else if (clusterId == Groups::Id) + { + ChipLogProgress(Zcl, "Groups attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); } } + /** @brief OnOff Cluster Init * * This function is called when a specific cluster is initialized. It gives the @@ -76,6 +61,13 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & * It is called exactly once for each endpoint where cluster is present. * * @param endpoint Ver.: always + * + * TODO Issue #3841 + * emberAfOnOffClusterInitCallback happens before the stack initialize the cluster + * attributes to the default value. + * The logic here expects something similar to the deprecated Plugins callback + * emberAfPluginOnOffClusterServerPostInitCallback. + * */ void emberAfOnOffClusterInitCallback(EndpointId endpoint) { diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/main.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/main.cpp similarity index 79% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/main.cpp rename to examples/lighting-app/cc13x2x7_26x2x7/src/main.cpp index 8311c8990aa5c6..4fdb88703acab6 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/main.cpp @@ -21,8 +21,8 @@ #include -#include -#include +#include "AppConfig.h" +#include "AppTask.h" #include @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xc800) +#define TOTAL_ICALL_HEAP_SIZE (0xc600) using namespace ::chip; using namespace ::chip::Inet; @@ -52,12 +51,23 @@ uint32_t heapSize = TOTAL_ICALL_HEAP_SIZE; // ================================================================================ extern "C" void vApplicationStackOverflowHook(void) { - while (true) + while (1) { ; } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -70,8 +80,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); @@ -85,13 +93,13 @@ int main(void) { // can't log until the kernel is started // PLAT_LOG("GetAppTask().StartAppTask() failed"); - while (true) + while (1) ; } vTaskStartScheduler(); // Should never get here. - while (true) + while (1) ; } diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/third_party/connectedhomeip b/examples/lighting-app/cc13x2x7_26x2x7/third_party/connectedhomeip similarity index 100% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/third_party/connectedhomeip rename to examples/lighting-app/cc13x2x7_26x2x7/third_party/connectedhomeip diff --git a/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn b/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn index ba2b327339e516..0bd2dfef85d615 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn @@ -29,7 +29,7 @@ assert(current_os == "freertos") project_dir = "${chip_root}/examples/lock-app/cc13x2x7_26x2x7" ti_simplelink_sdk("sdk") { - include_dirs = [ "${project_dir}/main/include" ] + include_dirs = [ "${project_dir}/include" ] public_configs = [ ":lock_app_config" ] } @@ -75,16 +75,17 @@ ti_simplelink_executable("lock_app") { sources = [ "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", - "${project_dir}/main/AppTask.cpp", - "${project_dir}/main/BoltLockManager.cpp", - "${project_dir}/main/ZclCallbacks.cpp", - "${project_dir}/main/main.cpp", + "${project_dir}/src/AppTask.cpp", + "${project_dir}/src/LockManager.cpp", + "${project_dir}/src/ZclCallbacks.cpp", + "${project_dir}/src/main.cpp", ] deps = [ ":sdk", ":sysconfig", "${chip_root}/examples/lock-app/lock-common", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/src/lib", ] @@ -96,7 +97,6 @@ ti_simplelink_executable("lock_app") { include_dirs = [ "${project_dir}", - "${project_dir}/main", "${chip_root}/examples/providers/", ] diff --git a/examples/lock-app/cc13x2x7_26x2x7/args.gni b/examples/lock-app/cc13x2x7_26x2x7/args.gni index 58a0bbbf2f366b..bd3e05a0055114 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/args.gni +++ b/examples/lock-app/cc13x2x7_26x2x7/args.gni @@ -29,8 +29,11 @@ lwip_debug = false chip_enable_ota_requestor = true +chip_openthread_ftd = false +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" + # Disable CHIP Logging -#chip_progress_logging = false +chip_progress_logging = false chip_detail_logging = false chip_automation_logging = false @@ -41,8 +44,6 @@ chip_config_network_layer_ble = true # INCLUDE_xSemaphoreGetMutexHolder chip_stack_lock_tracking = "none" -chip_openthread_ftd = false - matter_device_vid = "0xFFF1" matter_device_pid = "0x8006" matter_software_ver = "0x0001" diff --git a/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg b/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg index b55c57b9c364be..47cd09c1a31165 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg @@ -133,8 +133,8 @@ UART1.$name = "CONFIG_UART_DEBUG"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; -TRNG3.$name = "CONFIG_TRNG_APP"; +TRNG2.$name = "CONFIG_TRNG_APP"; +TRNG3.$name = "CONFIG_TRNG_THREAD"; RTOS.name = "FreeRTOS"; @@ -152,6 +152,8 @@ ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; +ble.advSet1.advParam1.primIntMin = 100; +ble.advSet1.advParam1.primIntMax = 200; /* DMM */ dmm.project = "ti_thread_thermostat_remote_display"; diff --git a/examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h b/examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h new file mode 100644 index 00000000000000..a808f37a72d7b5 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * 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. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#ifndef CHIP_PROJECT_CONFIG_H +#define CHIP_PROJECT_CONFIG_H + +#if BUILD_RELEASE // release build +// Note: Default Pairing/PIN/Serial Numbers being used. These should not be enabled for production builds +#endif // BUILD_RELEASE + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_PAIRING_CODE "CHIPUS" + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in CHIP NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 +#endif + +/** + * Values set by args.gni: + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + */ + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for CHIP-over-BLE (CHIPOBLE). + */ +#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC + * + * Enables synchronizing the device's real time clock with a remote CHIP Time service + * using the CHIP Time Sync protocol. + */ +// #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + * + * Enable the OpenThread SRP client to allow for CHIP device discovery. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 + +/** + * CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE + * + * For a development build, set the default importance of events to be logged as Debug. + * Since debug is the lowest importance level, this means all standard, critical, info and + * debug importance level vi events get logged. + */ +#if BUILD_RELEASE +#define CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE chip::Profiles::DataManagement::Production +#else +#define CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE chip::Profiles::DataManagement::Debug +#endif // BUILD_RELEASE + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +/** + * @def CHIP_IM_MAX_NUM_COMMAND_HANDLER + * + * @brief Defines the maximum number of CommandHandler, limits the number of active commands transactions on server. + */ +#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 2 + +/** + * @def CHIP_IM_MAX_NUM_WRITE_HANDLER + * + * @brief Defines the maximum number of WriteHandler, limits the number of active write transactions on server. + */ +#define CHIP_IM_MAX_NUM_WRITE_HANDLER 2 + +#endif // CHIP_PROJECT_CONFIG_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppConfig.h b/examples/lock-app/cc13x2x7_26x2x7/src/AppConfig.h similarity index 74% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppConfig.h rename to examples/lock-app/cc13x2x7_26x2x7/src/AppConfig.h index f7302b6efd10cd..a818b21d641875 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppConfig.h +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,4 +18,18 @@ #ifndef APP_CONFIG_H #define APP_CONFIG_H +// Logging +#ifdef __cplusplus +extern "C" { +#endif + +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); + +#define ACTUATOR_MOVEMENT_PERIOD_MS 1000 + +#ifdef __cplusplus +} +#endif #endif // APP_CONFIG_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppEvent.h b/examples/lock-app/cc13x2x7_26x2x7/src/AppEvent.h similarity index 86% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppEvent.h rename to examples/lock-app/cc13x2x7_26x2x7/src/AppEvent.h index ad9e93ee3ad1a5..dc4ce143338e1e 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppEvent.h +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2018 Nest Labs, Inc. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,6 +30,8 @@ struct AppEvent kEventType_ButtonLeft, kEventType_ButtonRight, kEventType_AppEvent, + kEventType_IdentifyStart, + kEventType_IdentifyStop, }; enum AppEventButtonType @@ -52,6 +54,12 @@ struct AppEvent { void * Context; } BoltLockEvent; + + struct + { + uint8_t Action; + int32_t Actor; + } LockEvent; }; EventHandler Handler; diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp new file mode 100644 index 00000000000000..772070fc7a0eab --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp @@ -0,0 +1,561 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * All rights reserved. + * + * 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 "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" + +#include "FreeRTOS.h" + +#include +#include + +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +#include +#include +#include +#include +#include +#endif + +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include + +/* syscfg */ +#include + +#define APP_TASK_STACK_SIZE (4096) +#define APP_TASK_PRIORITY 4 +#define APP_EVENT_QUEUE_SIZE 10 + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; +using namespace ::chip::app::Clusters::DoorLock; + +static TaskHandle_t sAppTaskHandle; +static QueueHandle_t sAppEventQueue; + +static LED_Handle sAppRedHandle; +static LED_Handle sAppGreenHandle; +static Button_Handle sAppLeftHandle; +static Button_Handle sAppRightHandle; +static DeviceInfoProviderImpl sExampleDeviceInfoProvider; + +AppTask AppTask::sAppTask; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +static DefaultOTARequestor sRequestorCore; +static DefaultOTARequestorStorage sRequestorStorage; +static DefaultOTARequestorDriver sRequestorUser; +static BDXDownloader sDownloader; +static OTAImageProcessorImpl sImageProcessor; + +void InitializeOTARequestor(void) +{ + // Initialize and interconnect the Requestor and Image Processor objects + SetRequestorInstance(&sRequestorCore); + + sRequestorStorage.Init(Server::GetInstance().GetPersistentStorage()); + sRequestorCore.Init(Server::GetInstance(), sRequestorStorage, sRequestorUser, sDownloader); + sImageProcessor.SetOTADownloader(&sDownloader); + sDownloader.SetImageProcessorDelegate(&sImageProcessor); + sRequestorUser.Init(&sRequestorCore, &sImageProcessor); +} +#endif + +::Identify stIdentify = { 0, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, AppTask::TriggerIdentifyEffectHandler }; + +int AppTask::StartAppTask() +{ + int ret = 0; + + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + PLAT_LOG("Failed to allocate app event queue"); + while (1) + ; + } + + // Start App task. + if (xTaskCreate(AppTaskMain, "APP", APP_TASK_STACK_SIZE / sizeof(StackType_t), NULL, APP_TASK_PRIORITY, &sAppTaskHandle) != + pdPASS) + { + PLAT_LOG("Failed to create app task"); + while (1) + ; + } + return ret; +} + +void uiLocking(void) +{ + PLAT_LOG("Lock initiated"); + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 50 /* ms */, LED_BLINK_FOREVER); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} + +void uiLocked(void) +{ + PLAT_LOG("Lock completed"); + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); + LED_stopBlinking(sAppRedHandle); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); +} + +void uiUnlocking(void) +{ + PLAT_LOG("Unlock initiated"); + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 50 /* ms */, LED_BLINK_FOREVER); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} + +void uiUnlocked(void) +{ + PLAT_LOG("Unlock completed"); + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); + LED_stopBlinking(sAppRedHandle); + LED_setOff(sAppRedHandle); +} + +int AppTask::Init() +{ + LED_Params ledParams; + Button_Params buttonParams; + + cc13xx_26xxLogInit(); + + // Init Chip memory management before the stack + Platform::MemoryInit(); + + CHIP_ERROR ret = PlatformMgr().InitChipStack(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("PlatformMgr().InitChipStack() failed"); + while (1) + ; + } + + ret = ThreadStackMgr().InitThreadStack(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ThreadStackMgr().InitThreadStack() failed"); + while (1) + ; + } +#if CHIP_DEVICE_CONFIG_THREAD_FTD + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#else + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ConnectivityMgr().SetThreadDeviceType() failed"); + while (1) + ; + } + + ret = PlatformMgr().StartEventLoopTask(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("PlatformMgr().StartEventLoopTask() failed"); + while (1) + ; + } + + ret = ThreadStackMgrImpl().StartThreadTask(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ThreadStackMgr().StartThreadTask() failed"); + while (1) + ; + } + + // Init ZCL Data Model and start server + PLAT_LOG("Initialize Server"); + static CommonCaseDeviceServerInitParams initParams; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + + // Initialize info provider + sExampleDeviceInfoProvider.SetStorageDelegate(initParams.persistentStorageDelegate); + SetDeviceInfoProvider(&sExampleDeviceInfoProvider); + + Server::GetInstance().Init(initParams); + + // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + // Initialize LEDs + PLAT_LOG("Initialize LEDs"); + LED_init(); + + LED_Params_init(&ledParams); // default PWM LED + sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); + LED_setOff(sAppRedHandle); + + LED_Params_init(&ledParams); // default PWM LED + sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); + LED_setOff(sAppGreenHandle); + + // Initialize buttons + PLAT_LOG("Initialize buttons"); + Button_init(); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); + Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); + Button_setCallback(sAppRightHandle, ButtonRightEventHandler); + + PlatformMgr().LockChipStack(); + { + uint8_t numberOfCredentialsPerUser = 0; + uint16_t numberOfUsers = 0; + uint8_t numberOfWeekdaySchedulesPerUser = 0; + uint8_t numberOfYeardaySchedulesPerUser = 0; + uint8_t numberOfHolidaySchedules = 0; + chip::app::DataModel::Nullable state; + EndpointId endpointId{ 1 }; + + if (!DoorLockServer::Instance().GetNumberOfCredentialsSupportedPerUser(endpointId, numberOfCredentialsPerUser)) + { + numberOfCredentialsPerUser = 5; + } + + if (!DoorLockServer::Instance().GetNumberOfUserSupported(endpointId, numberOfUsers)) + { + numberOfUsers = 10; + } + + if (!DoorLockServer::Instance().GetNumberOfWeekDaySchedulesPerUserSupported(endpointId, numberOfWeekdaySchedulesPerUser)) + { + numberOfWeekdaySchedulesPerUser = 10; + } + + if (!DoorLockServer::Instance().GetNumberOfYearDaySchedulesPerUserSupported(endpointId, numberOfYeardaySchedulesPerUser)) + { + numberOfYeardaySchedulesPerUser = 10; + } + + if (!DoorLockServer::Instance().GetNumberOfHolidaySchedulesSupported(endpointId, numberOfHolidaySchedules)) + { + numberOfHolidaySchedules = 10; + } + + Attributes::LockState::Get(endpointId, state); + ret = LockMgr().Init(state, + CC13X2_26X2DoorLock::LockInitParams::ParamBuilder() + .SetNumberOfUsers(numberOfUsers) + .SetNumberOfCredentialsPerUser(numberOfCredentialsPerUser) + .SetNumberOfWeekdaySchedulesPerUser(numberOfWeekdaySchedulesPerUser) + .SetNumberOfYeardaySchedulesPerUser(numberOfYeardaySchedulesPerUser) + .SetNumberOfHolidaySchedules(numberOfHolidaySchedules) + .GetLockParam()); + + if (state.Value() == DlLockState::kLocked) + { + uiLocked(); + } + else + { + uiUnlocked(); + } + } + + PlatformMgr().UnlockChipStack(); + + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("LockMgr().Init() failed"); + while (1) + ; + } + + LockMgr().SetCallbacks(ActionInitiated, ActionCompleted); + + ConfigurationMgr().LogDeviceConfig(); + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + InitializeOTARequestor(); +#endif + // QR code will be used with CHIP Tool + PrintOnboardingCodes(RendezvousInformationFlags(RendezvousInformationFlag::kBLE)); + + return 0; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + + sAppTask.Init(); + + LockMgr().ReadConfigValues(); + + while (1) + { + /* Task pend until we have stuff to do */ + if (xQueueReceive(sAppEventQueue, &event, portMAX_DELAY) == pdTRUE) + { + sAppTask.DispatchEvent(&event); + } + } +} + +void AppTask::ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events) +{ + AppEvent event; + event.Type = AppEvent::kEventType_ButtonLeft; + + if (events & Button_EV_CLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_Clicked; + } + else if (events & Button_EV_LONGCLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_LongClicked; + } + // button callbacks are in ISR context + if (xQueueSendFromISR(sAppEventQueue, &event, NULL) != pdPASS) + { + /* Failed to post the message */ + } +} + +void AppTask::ButtonRightEventHandler(Button_Handle handle, Button_EventMask events) +{ + AppEvent event; + event.Type = AppEvent::kEventType_ButtonRight; + + if (events & Button_EV_CLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_Clicked; + } + else if (events & Button_EV_LONGCLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_LongClicked; + } + // button callbacks are in ISR context + if (xQueueSendFromISR(sAppEventQueue, &event, NULL) != pdPASS) + { + /* Failed to post the message */ + } +} + +void AppTask::ActionInitiated(LockManager::Action_t aAction) +{ + if (aAction == LockManager::LOCK_ACTION) + { + uiLocking(); + } + else if (aAction == LockManager::UNLOCK_ACTION) + { + uiUnlocking(); + } +} + +void AppTask::ActionCompleted(LockManager::Action_t aAction) +{ + if (aAction == LockManager::LOCK_ACTION) + { + uiLocked(); + } + else if (aAction == LockManager::UNLOCK_ACTION) + { + uiUnlocked(); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (xPortIsInsideInterrupt()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (status != pdTRUE) + { + PLAT_LOG("Failed to post event to app task event queue"); + } + } + else + { + PLAT_LOG("Event Queue is NULL should never happen"); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + switch (aEvent->Type) + { + case AppEvent::kEventType_ButtonLeft: + if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) + { + LockMgr().InitiateAction(LockManager::UNLOCK_ACTION); + } + else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + break; + + case AppEvent::kEventType_ButtonRight: + if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) + { + LockMgr().InitiateAction(LockManager::LOCK_ACTION); + } + else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) + { + // Enable BLE advertisements + if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) + { + if (Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) + { + PLAT_LOG("Enabled BLE Advertisements"); + } + else + { + PLAT_LOG("OpenBasicCommissioningWindow() failed"); + } + } + else + { + // Disable BLE advertisements + ConnectivityMgr().SetBLEAdvertisingEnabled(false); + PLAT_LOG("Disabled BLE Advertisements"); + } + } + break; + + case AppEvent::kEventType_IdentifyStart: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 500, LED_BLINK_FOREVER); + PLAT_LOG("Identify started"); + break; + + case AppEvent::kEventType_IdentifyStop: + LED_stopBlinking(sAppGreenHandle); + + LED_setOff(sAppGreenHandle); + PLAT_LOG("Identify stopped"); + break; + + case AppEvent::kEventType_AppEvent: + if (NULL != aEvent->Handler) + { + aEvent->Handler(aEvent); + } + break; + + case AppEvent::kEventType_None: + default: + break; + } +} + +void AppTask::IdentifyStartHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + sAppTask.PostEvent(&event); +} + +void AppTask::IdentifyStopHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStop; + sAppTask.PostEvent(&event); +} + +void AppTask::TriggerIdentifyEffectHandler(::Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + PLAT_LOG("Starting blink identifier effect"); + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + PLAT_LOG("Breathe identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + PLAT_LOG("Okay identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + PLAT_LOG("Channel Change identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + PLAT_LOG("Finish identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + PLAT_LOG("Stop identifier effect"); + IdentifyStopHandler(identify); + break; + default: + PLAT_LOG("No identifier effect"); + } +} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppTask.h b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.h similarity index 60% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppTask.h rename to examples/lock-app/cc13x2x7_26x2x7/src/AppTask.h index 002e1b3f70557c..15939e6581737b 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppTask.h +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.h @@ -16,8 +16,7 @@ * limitations under the License. */ -#ifndef APP_TASK_H -#define APP_TASK_H +#pragma once #include #include @@ -27,22 +26,44 @@ #include "task.h" #include "AppEvent.h" +#include "LockManager.h" #include +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) +#define APP_ERROR_ALLOCATION_FAILED CHIP_APPLICATION_ERROR(0x07) + +struct Identify; + class AppTask { + public: int StartAppTask(); static void AppTaskMain(void * pvParameter); + void PostLockActionRequest(int32_t aActor, LockManager::Action_t aAction); void PostEvent(const AppEvent * event); + static void IdentifyStartHandler(::Identify *); + static void IdentifyStopHandler(::Identify *); + static void TriggerIdentifyEffectHandler(::Identify * identify); + private: friend AppTask & GetAppTask(void); int Init(); + // should this be done by BoltLock Manager? I don't want to unravel this spaghetti quite yet + static void ActionInitiated(LockManager::Action_t aAction); + static void ActionCompleted(LockManager::Action_t aAction); + void DispatchEvent(AppEvent * event); static void ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events); @@ -60,6 +81,7 @@ class AppTask Function_t mFunction; bool mFunctionTimerActive; + bool mSyncClusterToButtonAction; static AppTask sAppTask; }; @@ -68,5 +90,3 @@ inline AppTask & GetAppTask(void) { return AppTask::sAppTask; } - -#endif // APP_TASK_H diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp new file mode 100644 index 00000000000000..acd9c00b41c4d5 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp @@ -0,0 +1,703 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * 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 "LockManager.h" + +#include "AppConfig.h" +#include "AppTask.h" +#include "platform/KeyValueStoreManager.h" +#include +#include +#include +#include + +LockManager LockManager::sLock; + +TimerHandle_t sLockTimer; + +using namespace CC13X2_26X2DoorLock::LockInitParams; +using namespace chip::DeviceLayer::PersistedStorage; + +// persisted storage keys +const char LockUser[] = "a/lu"; +const char Credential[] = "a/c"; +const char LockUserName[] = "a/lun"; +const char CredentialData[] = "a/cd"; +const char UserCredentials[] = "a/uc"; +const char WeekDaySchedules[] = "a/wds"; +const char YearDaySchedules[] = "a/yds"; +const char HolidaySchedules[] = "a/hs"; + +CHIP_ERROR LockManager::Init(chip::app::DataModel::Nullable state, LockParam lockParam) +{ + + LockParams = lockParam; + + if (LockParams.numberOfUsers > kMaxUsers) + { + PLAT_LOG("Max number of users is greater than %d, the maximum amount of users currently supported on this platform", + kMaxUsers); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfCredentialsPerUser > kMaxCredentialsPerUser) + { + PLAT_LOG("Max number of credentials per user is greater than %d, the maximum amount of users currently supported on this " + "platform", + kMaxCredentialsPerUser); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfWeekdaySchedulesPerUser > kMaxWeekdaySchedulesPerUser) + { + PLAT_LOG("Max number of schedules is greater than %d, the maximum amount of schedules currently supported on this platform", + kMaxWeekdaySchedulesPerUser); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfYeardaySchedulesPerUser > kMaxYeardaySchedulesPerUser) + { + PLAT_LOG("Max number of schedules is greater than %d, the maximum amount of schedules currently supported on this platform", + kMaxYeardaySchedulesPerUser); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfHolidaySchedules > kMaxHolidaySchedules) + { + PLAT_LOG("Max number of schedules is greater than %d, the maximum amount of schedules currently supported on this platform", + kMaxHolidaySchedules); + return APP_ERROR_ALLOCATION_FAILED; + } + + // Create FreeRTOS sw timer for lock timer. + sLockTimer = xTimerCreate("lockTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = lock obj context + TimerEventHandler // timer callback handler + ); + + if (sLockTimer == NULL) + { + PLAT_LOG("sLockTimer timer create failed"); + return APP_ERROR_CREATE_TIMER_FAILED; + } + + if (state.Value() == DlLockState::kUnlocked) + { + mState = kState_UnlockCompleted; + } + else + { + mState = kState_LockCompleted; + } + + return CHIP_NO_ERROR; +} + +bool LockManager::IsValidUserIndex(uint16_t userIndex) +{ + return (userIndex < kMaxUsers); +} + +bool LockManager::IsValidCredentialIndex(uint16_t credentialIndex, CredentialTypeEnum type) +{ + if (CredentialTypeEnum::kProgrammingPIN == type) + { + return (0 == credentialIndex); // 0 is required index for Programming PIN + } + return (credentialIndex < kMaxCredentialsPerUser); +} + +bool LockManager::IsValidWeekdayScheduleIndex(uint8_t scheduleIndex) +{ + return (scheduleIndex < kMaxWeekdaySchedulesPerUser); +} + +bool LockManager::IsValidYeardayScheduleIndex(uint8_t scheduleIndex) +{ + return (scheduleIndex < kMaxYeardaySchedulesPerUser); +} + +bool LockManager::IsValidHolidayScheduleIndex(uint8_t scheduleIndex) +{ + return (scheduleIndex < kMaxHolidaySchedules); +} + +bool LockManager::ReadConfigValues() +{ + size_t outLen; + KeyValueStoreMgr().Get(LockUser, reinterpret_cast(&mLockUsers), + sizeof(EmberAfPluginDoorLockUserInfo) * ArraySize(mLockUsers), &outLen); + + KeyValueStoreMgr().Get(Credential, reinterpret_cast(&mLockCredentials), + sizeof(EmberAfPluginDoorLockCredentialInfo) * ArraySize(mLockCredentials), &outLen); + + KeyValueStoreMgr().Get(LockUserName, reinterpret_cast(mUserNames), sizeof(mUserNames), &outLen); + + KeyValueStoreMgr().Get(CredentialData, reinterpret_cast(mCredentialData), sizeof(mCredentialData), &outLen); + + KeyValueStoreMgr().Get(UserCredentials, reinterpret_cast(mCredentials), + sizeof(CredentialStruct) * LockParams.numberOfUsers * LockParams.numberOfCredentialsPerUser, &outLen); + + KeyValueStoreMgr().Get(WeekDaySchedules, reinterpret_cast(mWeekdaySchedule), + sizeof(EmberAfPluginDoorLockWeekDaySchedule) * LockParams.numberOfWeekdaySchedulesPerUser * + LockParams.numberOfUsers, + &outLen); + + KeyValueStoreMgr().Get(YearDaySchedules, reinterpret_cast(mYeardaySchedule), + sizeof(EmberAfPluginDoorLockYearDaySchedule) * LockParams.numberOfYeardaySchedulesPerUser * + LockParams.numberOfUsers, + &outLen); + + KeyValueStoreMgr().Get(HolidaySchedules, reinterpret_cast(&(mHolidaySchedule)), + sizeof(EmberAfPluginDoorLockHolidaySchedule) * LockParams.numberOfHolidaySchedules, &outLen); + + return true; +} + +void LockManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) +{ + mActionInitiated_CB = aActionInitiated_CB; + mActionCompleted_CB = aActionCompleted_CB; +} + +bool LockManager::InitiateAction(Action_t aAction) +{ + bool action_initiated = false; + State_t new_state; + + // Initiate Turn Lock/Unlock Action only when the previous one is complete. + if (mState == kState_LockCompleted && aAction == UNLOCK_ACTION) + { + action_initiated = true; + + new_state = kState_UnlockInitiated; + } + else if (mState == kState_UnlockCompleted && aAction == LOCK_ACTION) + { + action_initiated = true; + + new_state = kState_LockInitiated; + } + + if (action_initiated) + { + + StartTimer(ACTUATOR_MOVEMENT_PERIOD_MS); + + // Since the timer started successfully, update the state and trigger callback + mState = new_state; + + if (mActionInitiated_CB) + { + mActionInitiated_CB(aAction); + } + } + + return action_initiated; +} + +void LockManager::StartTimer(uint32_t aTimeoutMs) +{ + if (xTimerIsTimerActive(sLockTimer)) + { + PLAT_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sLockTimer, pdMS_TO_TICKS(aTimeoutMs), 100) != pdPASS) + { + PLAT_LOG("sLockTimer timer start() failed"); + } +} + +void LockManager::CancelTimer(void) +{ + if (xTimerStop(sLockTimer, 0) == pdFAIL) + { + PLAT_LOG("sLockTimer stop() failed"); + } +} + +void LockManager::TimerEventHandler(TimerHandle_t xTimer) +{ + // Get lock obj context from timer id. + LockManager * lock = static_cast(pvTimerGetTimerID(xTimer)); + + // The timer event handler will be called in the context of the timer task + // once sLockTimer expires. Post an event to apptask queue with the actual handler + // so that the event can be handled in the context of the apptask. + AppEvent event; + event.Type = AppEvent::kEventType_AppEvent; + event.BoltLockEvent.Context = lock; + event.Handler = ActuatorMovementTimerEventHandler; + GetAppTask().PostEvent(&event); +} + +void LockManager::ActuatorMovementTimerEventHandler(AppEvent * aEvent) +{ + Action_t actionCompleted = INVALID_ACTION; + + LockManager * lock = static_cast(aEvent->BoltLockEvent.Context); + + if (lock->mState == kState_LockInitiated) + { + lock->mState = kState_LockCompleted; + actionCompleted = LOCK_ACTION; + DoorLockServer::Instance().SetLockState(1, DlLockState::kLocked); + } + else if (lock->mState == kState_UnlockInitiated) + { + lock->mState = kState_UnlockCompleted; + actionCompleted = UNLOCK_ACTION; + DoorLockServer::Instance().SetLockState(1, DlLockState::kUnlocked); + } + + if (actionCompleted != INVALID_ACTION) + { + if (lock->mActionCompleted_CB) + { + lock->mActionCompleted_CB(actionCompleted); + } + } +} + +bool LockManager::Lock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err) +{ + return checkPin(endpointId, DlLockState::kLocked, pin, err); +} + +bool LockManager::Unlock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err) +{ + return checkPin(endpointId, DlLockState::kUnlocked, pin, err); +} + +bool LockManager::GetUser(chip::EndpointId endpointId, uint16_t userIndex, EmberAfPluginDoorLockUserInfo & user) +{ + VerifyOrReturnValue(userIndex > 0, false); // indices are one-indexed + + userIndex--; + + VerifyOrReturnValue(IsValidUserIndex(userIndex), false); + + ChipLogProgress(Zcl, "Door Lock App: LockManager::GetUser [endpoint=%d,userIndex=%hu]", endpointId, userIndex); + + const auto & userInDb = mLockUsers[userIndex]; + + user.userStatus = userInDb.userStatus; + if (UserStatusEnum::kAvailable == user.userStatus) + { + ChipLogDetail(Zcl, "Found unoccupied user [endpoint=%d]", endpointId); + return true; + } + + user.userName = chip::CharSpan(userInDb.userName.data(), userInDb.userName.size()); + user.credentials = chip::Span(mCredentials[userIndex], userInDb.credentials.size()); + user.userUniqueId = userInDb.userUniqueId; + user.userType = userInDb.userType; + user.credentialRule = userInDb.credentialRule; + // So far there's no way to actually create the credential outside Matter, so here we always set the creation/modification + // source to Matter + user.creationSource = DlAssetSource::kMatterIM; + user.createdBy = userInDb.createdBy; + user.modificationSource = DlAssetSource::kMatterIM; + user.lastModifiedBy = userInDb.lastModifiedBy; + + ChipLogDetail(Zcl, + "Found occupied user " + "[endpoint=%d,name=\"%.*s\",credentialsCount=%u,uniqueId=%lx,type=%u,credentialRule=%u," + "createdBy=%d,lastModifiedBy=%d]", + endpointId, static_cast(user.userName.size()), user.userName.data(), user.credentials.size(), + user.userUniqueId, to_underlying(user.userType), to_underlying(user.credentialRule), user.createdBy, + user.lastModifiedBy); + + return true; +} + +bool LockManager::SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip::FabricIndex creator, chip::FabricIndex modifier, + const chip::CharSpan & userName, uint32_t uniqueId, UserStatusEnum userStatus, UserTypeEnum usertype, + CredentialRuleEnum credentialRule, const CredentialStruct * credentials, size_t totalCredentials) +{ + ChipLogProgress(Zcl, + "Door Lock App: LockManager::SetUser " + "[endpoint=%d,userIndex=%d,creator=%d,modifier=%d,userName=%s,uniqueId=%ld " + "userStatus=%u,userType=%u,credentialRule=%u,credentials=%p,totalCredentials=%u]", + endpointId, userIndex, creator, modifier, userName.data(), uniqueId, to_underlying(userStatus), + to_underlying(usertype), to_underlying(credentialRule), credentials, totalCredentials); + + VerifyOrReturnValue(userIndex > 0, false); // indices are one-indexed + + userIndex--; + + VerifyOrReturnValue(IsValidUserIndex(userIndex), false); + + auto & userInStorage = mLockUsers[userIndex]; + + if (userName.size() > DOOR_LOCK_MAX_USER_NAME_SIZE) + { + ChipLogError(Zcl, "Cannot set user - user name is too long [endpoint=%d,index=%d]", endpointId, userIndex); + return false; + } + + if (totalCredentials > LockParams.numberOfCredentialsPerUser) + { + ChipLogError(Zcl, "Cannot set user - total number of credentials is too big [endpoint=%d,index=%d,totalCredentials=%u]", + endpointId, userIndex, totalCredentials); + return false; + } + + chip::Platform::CopyString(mUserNames[userIndex], userName); + userInStorage.userName = chip::CharSpan(mUserNames[userIndex], userName.size()); + userInStorage.userUniqueId = uniqueId; + userInStorage.userStatus = userStatus; + userInStorage.userType = usertype; + userInStorage.credentialRule = credentialRule; + userInStorage.lastModifiedBy = modifier; + userInStorage.createdBy = creator; + + for (size_t i = 0; i < totalCredentials; ++i) + { + mCredentials[userIndex][i] = credentials[i]; + mCredentials[userIndex][i].credentialType = CredentialTypeEnum::kPin; + mCredentials[userIndex][i].credentialIndex = i + 1; + } + + userInStorage.credentials = chip::Span(mCredentials[userIndex], totalCredentials); + + // Save user information in NVM flash + KeyValueStoreMgr().Put(LockUser, reinterpret_cast(&mLockUsers), + sizeof(EmberAfPluginDoorLockUserInfo) * LockParams.numberOfUsers); + + KeyValueStoreMgr().Put(UserCredentials, reinterpret_cast(mCredentials), + sizeof(CredentialStruct) * LockParams.numberOfUsers * LockParams.numberOfCredentialsPerUser); + + KeyValueStoreMgr().Put(LockUserName, reinterpret_cast(mUserNames), sizeof(mUserNames)); + + ChipLogProgress(Zcl, "Successfully set the user [mEndpointId=%d,index=%d]", endpointId, userIndex); + + return true; +} + +bool LockManager::GetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, + EmberAfPluginDoorLockCredentialInfo & credential) +{ + + if (CredentialTypeEnum::kProgrammingPIN == credentialType) + { + VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), + false); // programming pin index is only index allowed to contain 0 + } + else + { + VerifyOrReturnValue(IsValidCredentialIndex(--credentialIndex, credentialType), false); // otherwise, indices are one-indexed + } + + ChipLogProgress(Zcl, "Lock App: LockManager::GetCredential [credentialType=%u], credentialIndex=%d", + to_underlying(credentialType), credentialIndex); + + const auto & credentialInStorage = mLockCredentials[credentialIndex]; + + credential.status = credentialInStorage.status; + ChipLogDetail(Zcl, "CredentialStatus: %d, CredentialIndex: %d ", (int) credential.status, credentialIndex); + + if (DlCredentialStatus::kAvailable == credential.status) + { + ChipLogDetail(Zcl, "Found unoccupied credential "); + return true; + } + credential.credentialType = credentialInStorage.credentialType; + credential.credentialData = credentialInStorage.credentialData; + credential.createdBy = credentialInStorage.createdBy; + credential.lastModifiedBy = credentialInStorage.lastModifiedBy; + // So far there's no way to actually create the credential outside Matter, so here we always set the creation/modification + // source to Matter + credential.creationSource = DlAssetSource::kMatterIM; + credential.modificationSource = DlAssetSource::kMatterIM; + + ChipLogDetail(Zcl, "Found occupied credential [type=%u,dataSize=%u]", to_underlying(credential.credentialType), + credential.credentialData.size()); + + return true; +} + +bool LockManager::SetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, chip::FabricIndex creator, + chip::FabricIndex modifier, DlCredentialStatus credentialStatus, CredentialTypeEnum credentialType, + const chip::ByteSpan & credentialData) +{ + + if (CredentialTypeEnum::kProgrammingPIN == credentialType) + { + VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), + false); // programming pin index is only index allowed to contain 0 + } + else + { + VerifyOrReturnValue(IsValidCredentialIndex(--credentialIndex, credentialType), false); // otherwise, indices are one-indexed + } + + ChipLogProgress(Zcl, + "Door Lock App: LockManager::SetCredential " + "[credentialStatus=%u,credentialType=%u,credentialDataSize=%u,creator=%d,modifier=%d]", + to_underlying(credentialStatus), to_underlying(credentialType), credentialData.size(), creator, modifier); + + auto & credentialInStorage = mLockCredentials[credentialIndex]; + + credentialInStorage.status = credentialStatus; + credentialInStorage.credentialType = credentialType; + credentialInStorage.createdBy = creator; + credentialInStorage.lastModifiedBy = modifier; + + memcpy(mCredentialData[credentialIndex], credentialData.data(), credentialData.size()); + credentialInStorage.credentialData = chip::ByteSpan{ mCredentialData[credentialIndex], credentialData.size() }; + + // Save credential information in NVM flash + KeyValueStoreMgr().Put(Credential, reinterpret_cast(&mLockCredentials), + sizeof(EmberAfPluginDoorLockCredentialInfo) * LockParams.numberOfCredentialsPerUser); + + KeyValueStoreMgr().Put(CredentialData, reinterpret_cast(&mCredentialData), sizeof(mCredentialData)); + + ChipLogProgress(Zcl, "Successfully set the credential [credentialType=%u]", to_underlying(credentialType)); + + return true; +} + +DlStatus LockManager::GetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + EmberAfPluginDoorLockWeekDaySchedule & schedule) +{ + + VerifyOrReturnValue(weekdayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + weekdayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidWeekdayScheduleIndex(weekdayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + const auto & scheduleInStorage = mWeekdaySchedule[userIndex][weekdayIndex]; + if (DlScheduleStatus::kAvailable == scheduleInStorage.status) + { + return DlStatus::kNotFound; + } + + schedule = scheduleInStorage.schedule; + + return DlStatus::kSuccess; +} + +DlStatus LockManager::SetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + DlScheduleStatus status, DaysMaskMap daysMask, uint8_t startHour, uint8_t startMinute, + uint8_t endHour, uint8_t endMinute) +{ + + VerifyOrReturnValue(weekdayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + weekdayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidWeekdayScheduleIndex(weekdayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + auto & scheduleInStorage = mWeekdaySchedule[userIndex][weekdayIndex]; + + scheduleInStorage.schedule.daysMask = daysMask; + scheduleInStorage.schedule.startHour = startHour; + scheduleInStorage.schedule.startMinute = startMinute; + scheduleInStorage.schedule.endHour = endHour; + scheduleInStorage.schedule.endMinute = endMinute; + scheduleInStorage.status = status; + + // Save schedule information in NVM flash + KeyValueStoreMgr().Put(WeekDaySchedules, reinterpret_cast(mWeekdaySchedule), + sizeof(EmberAfPluginDoorLockWeekDaySchedule) * LockParams.numberOfWeekdaySchedulesPerUser * + LockParams.numberOfUsers); + + return DlStatus::kSuccess; +} + +DlStatus LockManager::GetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + EmberAfPluginDoorLockYearDaySchedule & schedule) +{ + VerifyOrReturnValue(yearDayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + yearDayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidYeardayScheduleIndex(yearDayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + const auto & scheduleInStorage = mYeardaySchedule[userIndex][yearDayIndex]; + if (DlScheduleStatus::kAvailable == scheduleInStorage.status) + { + return DlStatus::kNotFound; + } + + schedule = scheduleInStorage.schedule; + + return DlStatus::kSuccess; +} + +DlStatus LockManager::SetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + DlScheduleStatus status, uint32_t localStartTime, uint32_t localEndTime) +{ + VerifyOrReturnValue(yearDayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + yearDayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidYeardayScheduleIndex(yearDayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + auto & scheduleInStorage = mYeardaySchedule[userIndex][yearDayIndex]; + + scheduleInStorage.schedule.localStartTime = localStartTime; + scheduleInStorage.schedule.localEndTime = localEndTime; + scheduleInStorage.status = status; + + // Save schedule information in NVM flash + KeyValueStoreMgr().Put(YearDaySchedules, reinterpret_cast(mYeardaySchedule), + sizeof(EmberAfPluginDoorLockYearDaySchedule) * LockParams.numberOfYeardaySchedulesPerUser * + LockParams.numberOfUsers); + + return DlStatus::kSuccess; +} + +DlStatus LockManager::GetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, + EmberAfPluginDoorLockHolidaySchedule & schedule) +{ + VerifyOrReturnValue(holidayIndex > 0, DlStatus::kFailure); // indices are one-indexed + + holidayIndex--; + + VerifyOrReturnValue(IsValidHolidayScheduleIndex(holidayIndex), DlStatus::kFailure); + + const auto & scheduleInStorage = mHolidaySchedule[holidayIndex]; + if (DlScheduleStatus::kAvailable == scheduleInStorage.status) + { + return DlStatus::kNotFound; + } + + schedule = scheduleInStorage.schedule; + + return DlStatus::kSuccess; +} + +DlStatus LockManager::SetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, DlScheduleStatus status, + uint32_t localStartTime, uint32_t localEndTime, OperatingModeEnum operatingMode) +{ + VerifyOrReturnValue(holidayIndex > 0, DlStatus::kFailure); // indices are one-indexed + + holidayIndex--; + + VerifyOrReturnValue(IsValidHolidayScheduleIndex(holidayIndex), DlStatus::kFailure); + + auto & scheduleInStorage = mHolidaySchedule[holidayIndex]; + + scheduleInStorage.schedule.localStartTime = localStartTime; + scheduleInStorage.schedule.localEndTime = localEndTime; + scheduleInStorage.schedule.operatingMode = operatingMode; + scheduleInStorage.status = status; + + // Save schedule information in NVM flash + KeyValueStoreMgr().Put(HolidaySchedules, reinterpret_cast(&(mHolidaySchedule)), + sizeof(EmberAfPluginDoorLockHolidaySchedule) * LockParams.numberOfHolidaySchedules); + + return DlStatus::kSuccess; +} + +const char * LockManager::lockStateToString(DlLockState lockState) const +{ + switch (lockState) + { + case DlLockState::kNotFullyLocked: + return "Not Fully Locked"; + case DlLockState::kLocked: + return "Locked"; + case DlLockState::kUnlocked: + return "Unlocked"; + case DlLockState::kUnknownEnumValue: + break; + } + + return "Unknown"; +} + +bool LockManager::checkPin(chip::EndpointId endpointId, DlLockState lockState, const Optional & pin, + OperationErrorEnum & err) +{ + // Assume pin is required until told otherwise + bool requirePin = true; + chip::app::Clusters::DoorLock::Attributes::RequirePINforRemoteOperation::Get(endpointId, &requirePin); + + // If a pin code is not given + if (!pin.HasValue()) + { + ChipLogDetail(Zcl, "Door Lock App: PIN code is not specified [endpointId=%d]", endpointId); + + // If a pin code is not required + if (!requirePin) + { + ChipLogDetail(Zcl, "Door Lock App: setting door lock state to \"%s\" [endpointId=%d]", lockStateToString(lockState), + endpointId); + + return true; + } + + ChipLogError(Zcl, "Door Lock App: PIN code is not specified, but it is required [endpointId=%d]", endpointId); + + err = OperationErrorEnum::kInvalidCredential; + DoorLockServer::Instance().HandleWrongCodeEntry(endpointId); + return false; + } + + // Check the PIN code + for (uint8_t i = 0; i < kMaxCredentials; i++) + { + if (mLockCredentials[i].credentialType != CredentialTypeEnum::kPin || + mLockCredentials[i].status == DlCredentialStatus::kAvailable) + { + continue; + } + + if (mLockCredentials[i].credentialData.data_equal(pin.Value())) + { + ChipLogDetail(Zcl, + "Lock App: specified PIN code was found in the database, setting lock state to \"%s\" [endpointId=%d]", + lockStateToString(lockState), endpointId); + + return true; + } + } + + ChipLogDetail(Zcl, + "Door Lock App: specified PIN code was not found in the database, ignoring command to set lock state to \"%s\" " + "[endpointId=%d]", + lockStateToString(lockState), endpointId); + + err = OperationErrorEnum::kInvalidCredential; + DoorLockServer::Instance().HandleWrongCodeEntry(endpointId); + return false; +} diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h new file mode 100644 index 00000000000000..74129260bd9172 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h @@ -0,0 +1,221 @@ +/* + * + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include + +#include "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support + +#include + +struct WeekDaysScheduleInfo +{ + DlScheduleStatus status; + EmberAfPluginDoorLockWeekDaySchedule schedule; +}; + +struct YearDayScheduleInfo +{ + DlScheduleStatus status; + EmberAfPluginDoorLockYearDaySchedule schedule; +}; + +struct HolidayScheduleInfo +{ + DlScheduleStatus status; + EmberAfPluginDoorLockHolidaySchedule schedule; +}; + +namespace CC13X2_26X2DoorLock { +namespace ResourceRanges { +// Used to size arrays +static constexpr uint16_t kMaxUsers = 10; +static constexpr uint8_t kMaxCredentialsPerUser = 10; +static constexpr uint8_t kMaxWeekdaySchedulesPerUser = 10; +static constexpr uint8_t kMaxYeardaySchedulesPerUser = 10; +static constexpr uint8_t kMaxHolidaySchedules = 10; +static constexpr uint8_t kMaxCredentialSize = 8; + +// Indices received for user/credential/schedules are 1-indexed +static constexpr uint8_t kStartIndexValue = 1; + +static constexpr uint8_t kMaxCredentials = kMaxUsers * kMaxCredentialsPerUser; +} // namespace ResourceRanges + +namespace LockInitParams { + +struct LockParam +{ + // Read from zap attributes + uint16_t numberOfUsers = 0; + uint8_t numberOfCredentialsPerUser = 0; + uint8_t numberOfWeekdaySchedulesPerUser = 0; + uint8_t numberOfYeardaySchedulesPerUser = 0; + uint8_t numberOfHolidaySchedules = 0; +}; + +class ParamBuilder +{ +public: + ParamBuilder & SetNumberOfUsers(uint16_t numberOfUsers) + { + lockParam_.numberOfUsers = numberOfUsers; + return *this; + } + ParamBuilder & SetNumberOfCredentialsPerUser(uint8_t numberOfCredentialsPerUser) + { + lockParam_.numberOfCredentialsPerUser = numberOfCredentialsPerUser; + return *this; + } + ParamBuilder & SetNumberOfWeekdaySchedulesPerUser(uint8_t numberOfWeekdaySchedulesPerUser) + { + lockParam_.numberOfWeekdaySchedulesPerUser = numberOfWeekdaySchedulesPerUser; + return *this; + } + ParamBuilder & SetNumberOfYeardaySchedulesPerUser(uint8_t numberOfYeardaySchedulesPerUser) + { + lockParam_.numberOfYeardaySchedulesPerUser = numberOfYeardaySchedulesPerUser; + return *this; + } + ParamBuilder & SetNumberOfHolidaySchedules(uint8_t numberOfHolidaySchedules) + { + lockParam_.numberOfHolidaySchedules = numberOfHolidaySchedules; + return *this; + } + LockParam GetLockParam() { return lockParam_; } + +private: + LockParam lockParam_; +}; + +} // namespace LockInitParams +} // namespace CC13X2_26X2DoorLock + +using namespace ::chip; +using namespace CC13X2_26X2DoorLock::ResourceRanges; + +class LockManager +{ +public: + enum Action_t + { + LOCK_ACTION = 0, + UNLOCK_ACTION, + + INVALID_ACTION + } Action; + + enum State_t + { + kState_LockInitiated = 0, + kState_LockCompleted, + kState_UnlockInitiated, + kState_UnlockCompleted, + } State; + + CHIP_ERROR Init(chip::app::DataModel::Nullable state, + CC13X2_26X2DoorLock::LockInitParams::LockParam lockParam); + bool InitiateAction(Action_t aAction); + + typedef void (*Callback_fn_initiated)(Action_t); + typedef void (*Callback_fn_completed)(Action_t); + void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); + + bool Lock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err); + bool Unlock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err); + + bool GetUser(chip::EndpointId endpointId, uint16_t userIndex, EmberAfPluginDoorLockUserInfo & user); + bool SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip::FabricIndex creator, chip::FabricIndex modifier, + const chip::CharSpan & userName, uint32_t uniqueId, UserStatusEnum userStatus, UserTypeEnum usertype, + CredentialRuleEnum credentialRule, const CredentialStruct * credentials, size_t totalCredentials); + + bool GetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, + EmberAfPluginDoorLockCredentialInfo & credential); + + bool SetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, chip::FabricIndex creator, chip::FabricIndex modifier, + DlCredentialStatus credentialStatus, CredentialTypeEnum credentialType, + const chip::ByteSpan & credentialData); + + DlStatus GetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + EmberAfPluginDoorLockWeekDaySchedule & schedule); + + DlStatus SetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, DlScheduleStatus status, + DaysMaskMap daysMask, uint8_t startHour, uint8_t startMinute, uint8_t endHour, uint8_t endMinute); + + DlStatus GetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + EmberAfPluginDoorLockYearDaySchedule & schedule); + + DlStatus SetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, DlScheduleStatus status, + uint32_t localStartTime, uint32_t localEndTime); + + DlStatus GetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, EmberAfPluginDoorLockHolidaySchedule & schedule); + + DlStatus SetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, DlScheduleStatus status, uint32_t localStartTime, + uint32_t localEndTime, OperatingModeEnum operatingMode); + + bool IsValidUserIndex(uint16_t userIndex); + bool IsValidCredentialIndex(uint16_t credentialIndex, CredentialTypeEnum type); + bool IsValidWeekdayScheduleIndex(uint8_t scheduleIndex); + bool IsValidYeardayScheduleIndex(uint8_t scheduleIndex); + bool IsValidHolidayScheduleIndex(uint8_t scheduleIndex); + + bool checkPin(chip::EndpointId endpointId, DlLockState lockState, const Optional & pin, + OperationErrorEnum & err); + const char * lockStateToString(DlLockState lockState) const; + + bool ReadConfigValues(); + +private: + friend LockManager & LockMgr(); + State_t mState; + + Callback_fn_initiated mActionInitiated_CB; + Callback_fn_completed mActionCompleted_CB; + + void CancelTimer(void); + void StartTimer(uint32_t aTimeoutMs); + + static void TimerEventHandler(TimerHandle_t xTimer); + static void AutoLockTimerEventHandler(AppEvent * aEvent); + static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); + + EmberAfPluginDoorLockUserInfo mLockUsers[kMaxUsers]; + EmberAfPluginDoorLockCredentialInfo mLockCredentials[kMaxCredentials]; + WeekDaysScheduleInfo mWeekdaySchedule[kMaxUsers][kMaxWeekdaySchedulesPerUser]; + YearDayScheduleInfo mYeardaySchedule[kMaxUsers][kMaxYeardaySchedulesPerUser]; + HolidayScheduleInfo mHolidaySchedule[kMaxHolidaySchedules]; + + char mUserNames[ArraySize(mLockUsers)][DOOR_LOCK_MAX_USER_NAME_SIZE]; + uint8_t mCredentialData[kMaxCredentials][kMaxCredentialSize]; + CredentialStruct mCredentials[kMaxUsers][kMaxCredentialsPerUser]; + + static LockManager sLock; + CC13X2_26X2DoorLock::LockInitParams::LockParam LockParams; +}; + +inline LockManager & LockMgr() +{ + return LockManager::sLock; +} diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp new file mode 100644 index 00000000000000..0fb673f020c5c5 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp @@ -0,0 +1,149 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * This file implements the handler for data model messages. + */ + +#include "AppConfig.h" +#include "LockManager.h" +#include + +#include +#include +#include +#include + +using namespace ::chip::app::Clusters; +using namespace ::chip::DeviceLayer::Internal; + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, + uint8_t * value) +{ + ClusterId clusterId = attributePath.mClusterId; + AttributeId attributeId = attributePath.mAttributeId; + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + + if (clusterId == DoorLock::Id && attributeId == DoorLock::Attributes::LockState::Id) + { + ChipLogProgress(Zcl, "Door lock cluster: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + } +} + +/** @brief DoorLock Cluster Init + * + * This function is called when a specific cluster is initialized. It gives the + * application an opportunity to take care of cluster initialization procedures. + * It is called exactly once for each endpoint where cluster is present. + * + * @param endpoint Ver.: always + * + */ +void emberAfDoorLockClusterInitCallback(EndpointId endpoint) {} + +bool emberAfPluginDoorLockOnDoorLockCommand(chip::EndpointId endpointId, const Optional & pinCode, + OperationErrorEnum & err) +{ + ChipLogProgress(Zcl, "Door Lock App: Lock Command endpoint=%d", endpointId); + bool status = LockMgr().Lock(endpointId, pinCode, err); + if (status == true) + { + LockMgr().InitiateAction(LockManager::LOCK_ACTION); + } + return status; +} + +bool emberAfPluginDoorLockOnDoorUnlockCommand(chip::EndpointId endpointId, const Optional & pinCode, + OperationErrorEnum & err) +{ + ChipLogProgress(Zcl, "Door Lock App: Unlock Command endpoint=%d", endpointId); + bool status = LockMgr().Unlock(endpointId, pinCode, err); + if (status == true) + { + LockMgr().InitiateAction(LockManager::UNLOCK_ACTION); + } + + return status; +} + +bool emberAfPluginDoorLockGetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, + EmberAfPluginDoorLockCredentialInfo & credential) +{ + return LockMgr().GetCredential(endpointId, credentialIndex, credentialType, credential); +} + +bool emberAfPluginDoorLockSetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, chip::FabricIndex creator, + chip::FabricIndex modifier, DlCredentialStatus credentialStatus, + CredentialTypeEnum credentialType, const chip::ByteSpan & credentialData) +{ + return LockMgr().SetCredential(endpointId, credentialIndex, creator, modifier, credentialStatus, credentialType, + credentialData); +} + +bool emberAfPluginDoorLockGetUser(chip::EndpointId endpointId, uint16_t userIndex, EmberAfPluginDoorLockUserInfo & user) +{ + return LockMgr().GetUser(endpointId, userIndex, user); +} + +bool emberAfPluginDoorLockSetUser(chip::EndpointId endpointId, uint16_t userIndex, chip::FabricIndex creator, + chip::FabricIndex modifier, const chip::CharSpan & userName, uint32_t uniqueId, + UserStatusEnum userStatus, UserTypeEnum usertype, CredentialRuleEnum credentialRule, + const CredentialStruct * credentials, size_t totalCredentials) +{ + + return LockMgr().SetUser(endpointId, userIndex, creator, modifier, userName, uniqueId, userStatus, usertype, credentialRule, + credentials, totalCredentials); +} + +DlStatus emberAfPluginDoorLockGetSchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + EmberAfPluginDoorLockWeekDaySchedule & schedule) +{ + return LockMgr().GetWeekdaySchedule(endpointId, weekdayIndex, userIndex, schedule); +} + +DlStatus emberAfPluginDoorLockGetSchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + EmberAfPluginDoorLockYearDaySchedule & schedule) +{ + return LockMgr().GetYeardaySchedule(endpointId, yearDayIndex, userIndex, schedule); +} + +DlStatus emberAfPluginDoorLockGetSchedule(chip::EndpointId endpointId, uint8_t holidayIndex, + EmberAfPluginDoorLockHolidaySchedule & holidaySchedule) +{ + return LockMgr().GetHolidaySchedule(endpointId, holidayIndex, holidaySchedule); +} + +DlStatus emberAfPluginDoorLockSetSchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + DlScheduleStatus status, DaysMaskMap daysMask, uint8_t startHour, uint8_t startMinute, + uint8_t endHour, uint8_t endMinute) +{ + return LockMgr().SetWeekdaySchedule(endpointId, weekdayIndex, userIndex, status, daysMask, startHour, startMinute, endHour, + endMinute); +} + +DlStatus emberAfPluginDoorLockSetSchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + DlScheduleStatus status, uint32_t localStartTime, uint32_t localEndTime) +{ + return LockMgr().SetYeardaySchedule(endpointId, yearDayIndex, userIndex, status, localStartTime, localEndTime); +} + +DlStatus emberAfPluginDoorLockSetSchedule(chip::EndpointId endpointId, uint8_t holidayIndex, DlScheduleStatus status, + uint32_t localStartTime, uint32_t localEndTime, OperatingModeEnum operatingMode) +{ + return LockMgr().SetHolidaySchedule(endpointId, holidayIndex, status, localStartTime, localEndTime, operatingMode); +} diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/main.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/main.cpp new file mode 100644 index 00000000000000..4fdb88703acab6 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/main.cpp @@ -0,0 +1,105 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * + * 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 "AppConfig.h" +#include "AppTask.h" + +#include + +/* Driver Header files */ +#include +#include +#include + +#include +#include +#include +#include + +#include +#define TOTAL_ICALL_HEAP_SIZE (0xc600) + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; + +__attribute__((section(".heap"))) uint8_t GlobalHeapZoneBuffer[TOTAL_ICALL_HEAP_SIZE]; +uint32_t heapSize = TOTAL_ICALL_HEAP_SIZE; + +// ================================================================================ +// FreeRTOS Callbacks +// ================================================================================ +extern "C" void vApplicationStackOverflowHook(void) +{ + while (1) + { + ; + } +} + +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + Board_init(); + bpool((void *) GlobalHeapZoneBuffer, TOTAL_ICALL_HEAP_SIZE); + + GPIO_init(); + + NVS_init(); + + ECDH_init(); + + ECDSA_init(); + + AESECB_init(); + + SHA2_init(); + + int ret = GetAppTask().StartAppTask(); + if (ret != 0) + { + // can't log until the kernel is started + // PLAT_LOG("GetAppTask().StartAppTask() failed"); + while (1) + ; + } + + vTaskStartScheduler(); + + // Should never get here. + while (1) + ; +} diff --git a/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg b/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg index b2409535110003..995ad22af6b435 100644 --- a/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg @@ -22,16 +22,14 @@ var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); var AESECB = scripting.addModule("/ti/drivers/AESECB"); var Button = scripting.addModule("/ti/drivers/apps/Button"); -var ECJPAKE = scripting.addModule("/ti/drivers/ECJPAKE"); var LED = scripting.addModule("/ti/drivers/apps/LED"); var NVS = scripting.addModule("/ti/drivers/NVS"); var RF = scripting.addModule("/ti/drivers/RF"); var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); -var RTOS = scripting.addModule("/ti/drivers/RTOS"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); var TRNG = scripting.addModule("/ti/drivers/TRNG"); -var Thread = scripting.addModule("/ti/thread/thread"); var SHA2 = scripting.addModule("/ti/drivers/SHA2"); -var UART = scripting.addModule("/ti/drivers/UART"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); var ble = scripting.addModule("/ti/ble5stack/ble"); var dmm = scripting.addModule("/ti/dmm/dmm"); var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); @@ -43,20 +41,19 @@ var AESECB1 = AESECB.addInstance(); var AESECB2 = AESECB.addInstance(); var Button1 = Button.addInstance(); var Button2 = Button.addInstance(); -var ECJPAKE = ECJPAKE.addInstance(); var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); var SHA21 = SHA2.addInstance(); var LED1 = LED.addInstance(); var LED2 = LED.addInstance(); var TRNG1 = TRNG.addInstance(); var TRNG2 = TRNG.addInstance(); var TRNG3 = TRNG.addInstance(); -var UART1 = UART.addInstance(); +var UART2 = UART2.addInstance(); var AESCTRDRBG1 = AESCTRDRBG.addInstance(); var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; AESCCM1.$name = "CONFIG_AESCCM0"; @@ -65,9 +62,6 @@ AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -/* RTOS */ -RTOS.name = "FreeRTOS"; - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -84,23 +78,24 @@ Button2.gpioPin.interruptTrigger = "Falling Edge"; /* ======== CCFG ======== */ var CCFG = scripting.addModule("/ti/devices/CCFG"); -const deviceName = system.getScript("/ti/ti154stack/ti154stack_common.js").getLaunchPadFromDevice(); const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; for(var setting in ccfgSettings) { CCFG[setting] = ccfgSettings[setting]; } -// Update LF Clock Source for CC2652RB devices -if(deviceName.includes("RB")) -{ - CCFG.srcClkLF = "Derived from HF XOSC"; -} +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; + /* NVS */ NVS1.$name = "CONFIG_NVSINTERNAL"; NVS1.internalFlash.regionBase = 0xAA000; NVS1.internalFlash.regionSize = 0x4000; +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + /* RF */ /* if an antenna component exists, assign it to the rf instance */ if (system.deviceData.board && system.deviceData.board.components.RF) { @@ -113,6 +108,58 @@ for(var setting in rfDesignSettings) RFDesign[setting] = rfDesignSettings[setting]; } +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -128,16 +175,14 @@ LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; /* Debug UART */ -UART1.$hardware = system.deviceData.board.components.XDS110UART; -UART1.$name = "CONFIG_UART_DEBUG"; +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; TRNG3.$name = "CONFIG_TRNG_APP"; -RTOS.name = "FreeRTOS"; - /* BLE */ ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; ble.maxConnNum = 1; @@ -145,15 +190,14 @@ ble.numOfAdvSets = 1; ble.lockProject = true; ble.oneLibSizeOpt = true; ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; ble.connUpdateParamsPeripheral.reqMinConnInt = 30; ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; -ble.advSet1.advParam1.primIntMin = 100; -ble.advSet1.advParam1.primIntMax = 200; /* DMM */ dmm.project = "ti_thread_thermostat_remote_display"; diff --git a/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h b/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h index 3cead418532caa..77f2cc37421d36 100644 --- a/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h +++ b/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/platform/cc13x2_26x2/BUILD.gn b/examples/platform/cc13x2_26x2/BUILD.gn index 619ecdfa446dc5..06beceb9d75d01 100644 --- a/examples/platform/cc13x2_26x2/BUILD.gn +++ b/examples/platform/cc13x2_26x2/BUILD.gn @@ -14,6 +14,15 @@ import("//build_overrides/chip.gni") +config("chip_examples_project_config") { + include_dirs = [ "project_include" ] +} + +source_set("openthread_core_config_cc13x2_26x2_chip_examples") { + sources = [ "project_include/OpenThreadConfig.h" ] + public_configs = [ ":chip_examples_project_config" ] +} + config("attestation-credentials-config") { include_dirs = [ "${chip_root}" ] diff --git a/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp index 9e39a54c263668..ddde42c932d590 100644 --- a/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp +++ b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp @@ -15,8 +15,6 @@ * limitations under the License. */ #include "CC13X2_26X2DeviceAttestationCreds.h" -#include -#include #include #include #include @@ -30,6 +28,10 @@ namespace CC13X2_26X2 { namespace { +extern "C" { + +extern void cc13x2_26x2Log(const char * aFormat, ...); + typedef struct { const uint32_t len; @@ -127,6 +129,8 @@ const factoryData gFactoryData = { }, }; +} // extern "C" + CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) { Crypto::P256SerializedKeypair serialized_keypair; diff --git a/examples/platform/cc13x2_26x2/args.gni b/examples/platform/cc13x2_26x2/args.gni index 7d18cc869d4831..ff1f8159857fc6 100644 --- a/examples/platform/cc13x2_26x2/args.gni +++ b/examples/platform/cc13x2_26x2/args.gni @@ -14,10 +14,10 @@ import("//build_overrides/chip.gni") -import("${chip_root}/src/platform/cc13x2_26x2/args.gni") +import("${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/args.gni") openthread_config_file = "" -openthread_core_config_deps = [] +openthread_core_config_deps = [ "${chip_root}/examples/platform/cc13x2_26x2:openthread_core_config_cc13x2_26x2_chip_examples" ] chip_ble_project_config_include = "" chip_device_project_config_include = "" diff --git a/examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h b/examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h new file mode 100644 index 00000000000000..7747508d80bfdb --- /dev/null +++ b/examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h @@ -0,0 +1,98 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * 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. + */ + +/** + * @file + * Overrides to default OpenThread configuration. + * + */ + +#pragma once + +#ifdef DeviceFamily_CC13X2_CC26X2 + +/* Number of message buffers reduced to fit into CC26x2x3 RAM */ +#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 22 + +#endif // DeviceFamily_CC13X2_CC26X2 + +#define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_APP + +// When operating in a less than ideal RF environment, having a more forgiving configuration +// of OpenThread makes thread a great deal more reliable. +#define OPENTHREAD_CONFIG_TMF_ADDRESS_QUERY_MAX_RETRY_DELAY 120 // default is 28800 +#define OPENTHREAD_CONFIG_MAC_DEFAULT_MAX_FRAME_RETRIES_DIRECT 15 // default is 3 +#define OPENTHREAD_CONFIG_MAC_DEFAULT_MAX_FRAME_RETRIES_INDIRECT 1 // default is 0 +#define OPENTHREAD_CONFIG_MAC_MAX_TX_ATTEMPTS_INDIRECT_POLLS 16 // default is 4 + +// Enable periodic parent search to speed up finding a better parent. +#define OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE 1 // default is 0 +#define OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD -45 // default is -65 +#define OPENTHREAD_CONFIG_MLE_INFORM_PREVIOUS_PARENT_ON_REATTACH 1 // default is 0 + +// Use smaller maximum interval to speed up reattaching. +#define OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_MAXIMUM_INTERVAL (60 * 10 * 1000) // default 1200000 ms + +#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 1 +//#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 0 +#define UART_AS_SERIAL_TRANSPORT 1 +#define OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1 +#define OPENTHREAD_CONFIG_ECDSA_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_SERVICE_DISCOVERY_ENABLE 1 + +#define OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE 0 +#define OPENTHREAD_CONFIG_BORDER_AGENT_ENABLE 0 +#define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 0 +#define OPENTHREAD_CONFIG_JOINER_ENABLE 0 + +#define OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS 0 +// TCP disabled until OpenThread has a GN/Ninja build for the tcplp library +#define OPENTHREAD_CONFIG_TCP_ENABLE 0 + +#define OPENTHREAD_CONFIG_THREAD_VERSION OT_THREAD_VERSION_1_3 + +//#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 1 +//#define OPENTHREAD_CONFIG_COAP_API_ENABLE 1 +#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 0 +#define OPENTHREAD_CONFIG_COAP_API_ENABLE 0 +#define OPENTHREAD_CONFIG_DHCP6_CLIENT_ENABLE 0 +#define OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_DIAG_ENABLE 0 +#define OPENTHREAD_CONFIG_DNSSD_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_DUA_ENABLE 1 +#define OPENTHREAD_CONFIG_LINK_RAW_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_FILTER_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_ACK_TIMEOUT_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_CSMA_BACKOFF_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_RETRANSMIT_ENABLE 1 +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE 1 +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE 1 +#define OPENTHREAD_CONFIG_MLR_ENABLE 1 +#define OPENTHREAD_CONFIG_NETDATA_PUBLISHER_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_DEFAULT_MODE 1 +#define OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE 1 + +// Use the TI-supplied default platform configuration for remainder +#include "openthread-core-cc13xx_cc26xx-config.h" diff --git a/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn b/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn index 7eadbc73e8c4a9..5a9aed051d28fc 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn @@ -36,7 +36,6 @@ ti_sysconfig("sysconfig") { sources = [ "${project_dir}/chip.syscfg" ] outputs = [ - "ti_devices_config.c", "ti_radio_config.c", "ti_radio_config.h", "ti_drivers_config.c", diff --git a/examples/pump-app/cc13x2x7_26x2x7/args.gni b/examples/pump-app/cc13x2x7_26x2x7/args.gni index 8baf8977c88bb2..aeeb0708a235e7 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/args.gni +++ b/examples/pump-app/cc13x2x7_26x2x7/args.gni @@ -29,10 +29,12 @@ lwip_debug = false chip_enable_ota_requestor = true +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" + # Disable CHIP Logging #chip_progress_logging = false -#chip_detail_logging = false -#chip_automation_logging = false +chip_detail_logging = false +chip_automation_logging = false # BLE options chip_config_network_layer_ble = true diff --git a/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg b/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg index 6bbd36becbf9cc..995ad22af6b435 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg @@ -17,159 +17,51 @@ * limitations under the License. */ -/** - * These arguments were used when this file was generated. They will be automatically applied on subsequent loads - * via the GUI or CLI. Run CLI with '--help' for additional information on how to override these arguments. - * @cliArgs --board "/ti/boards/CC26X2R1_LAUNCHXL" --product "simplelink_cc13x2_26x2_sdk@4.40.05.02_eng" - * @versions {"tool":"1.9.0+2015","templates":null} - */ - -/** - * Import the modules used in this configuration. - */ -const ble = scripting.addModule("/ti/ble5stack/ble"); -const CCFG = scripting.addModule("/ti/devices/CCFG"); -const rfdesign = scripting.addModule("/ti/devices/radioconfig/rfdesign"); -const dmm = scripting.addModule("/ti/dmm/dmm"); -const AESCCM = scripting.addModule("/ti/drivers/AESCCM"); -const AESCCM1 = AESCCM.addInstance(); -const AESCCM2 = AESCCM.addInstance(); -const AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); -const AESCTRDRBG1 = AESCTRDRBG.addInstance(); -const AESECB = scripting.addModule("/ti/drivers/AESECB"); -const AESECB1 = AESECB.addInstance(); -const AESECB2 = AESECB.addInstance(); -const ECDH = scripting.addModule("/ti/drivers/ECDH"); -const ECDH1 = ECDH.addInstance(); -const ECDH2 = ECDH.addInstance(); -const NVS = scripting.addModule("/ti/drivers/NVS"); -const NVS1 = NVS.addInstance(); -const NVS2 = NVS.addInstance(); -const RF = scripting.addModule("/ti/drivers/RF"); -const RTOS = scripting.addModule("/ti/drivers/RTOS"); -const SHA2 = scripting.addModule("/ti/drivers/SHA2"); -const SHA21 = SHA2.addInstance(); -const TRNG = scripting.addModule("/ti/drivers/TRNG"); -const TRNG1 = TRNG.addInstance(); -const TRNG2 = TRNG.addInstance(); -const TRNG3 = TRNG.addInstance(); -const UART = scripting.addModule("/ti/drivers/UART"); -const UART1 = UART.addInstance(); -const UART2 = UART.addInstance(); -const Button = scripting.addModule("/ti/drivers/apps/Button"); -const Button1 = Button.addInstance(); -const Button2 = Button.addInstance(); -const LED = scripting.addModule("/ti/drivers/apps/LED"); -const LED1 = LED.addInstance(); -const LED2 = LED.addInstance(); -const thread = scripting.addModule("/ti/thread/thread"); - -/** - * Write custom configuration values to the imported modules. - */ -ble.maxConnNum = 1; -ble.numOfAdvSets = 1; -ble.lockProject = true; -ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; -ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; -ble.connUpdateParamsPeripheral.reqMinConnInt = 30; -ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; -ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; -ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; -ble.advSet1.advData1.$name = "ti_ble5stack_broadcaster_advertisement_data0"; -ble.advSet1.scanRes1.$name = "ti_ble5stack_broadcaster_advertisement_data1"; - -CCFG.enableBootloader = true; -CCFG.enableBootloaderBackdoor = true; -CCFG.dioBootloaderBackdoor = 13; -CCFG.levelBootloaderBackdoor = "Active low"; -CCFG.srcClkLF = "Derived from HF XOSC"; -CCFG.ccfgTemplate.$name = "ti_devices_CCFGTemplate0"; - -dmm.project = "ti_thread_thermostat_remote_display"; -dmm.stackRoles = ["blePeripheral","threadFTD"]; -dmm.lockStackRoles = true; -dmm.numApplicationStates = 10; -dmm.applicationState0 = "ANY"; -dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; -dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; -dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; -dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; -dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; -dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; -dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; -dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; -dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; -dmm.policyArray.create(4); -dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; -dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; -dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; -dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; -dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; -dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; -dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; -dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; -dmm.policyArray[1].blePeripheral.weight = 25; -dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; -dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; -dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; -dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; -dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; -dmm.policyArray[2].threadFTD.weight = 30; -dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; -dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; -dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; -dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; -dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; -dmm.policyArray[3].threadFTD.weight = 1; -AESCCM1.$name = "CONFIG_AESCCM0"; - -AESCCM2.$name = "CONFIG_AESCCM_1"; +/* Modules */ +var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); +var AESECB = scripting.addModule("/ti/drivers/AESECB"); +var Button = scripting.addModule("/ti/drivers/apps/Button"); +var LED = scripting.addModule("/ti/drivers/apps/LED"); +var NVS = scripting.addModule("/ti/drivers/NVS"); +var RF = scripting.addModule("/ti/drivers/RF"); +var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); +var TRNG = scripting.addModule("/ti/drivers/TRNG"); +var SHA2 = scripting.addModule("/ti/drivers/SHA2"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); +var ble = scripting.addModule("/ti/ble5stack/ble"); +var dmm = scripting.addModule("/ti/dmm/dmm"); +var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); +var ECDH = scripting.addModule("/ti/drivers/ECDH"); + +/* Instances */ +var AESCCM1 = AESCCM.addInstance(); +var AESECB1 = AESECB.addInstance(); +var AESECB2 = AESECB.addInstance(); +var Button1 = Button.addInstance(); +var Button2 = Button.addInstance(); +var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); +var SHA21 = SHA2.addInstance(); +var LED1 = LED.addInstance(); +var LED2 = LED.addInstance(); +var TRNG1 = TRNG.addInstance(); +var TRNG2 = TRNG.addInstance(); +var TRNG3 = TRNG.addInstance(); +var UART2 = UART2.addInstance(); +var AESCTRDRBG1 = AESCTRDRBG.addInstance(); +var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; -AESECB1.$name = "CONFIG_AESECB0"; +AESCCM1.$name = "CONFIG_AESCCM0"; +AESECB1.$name = "CONFIG_AESECB0"; AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -ECDH2.$name = "CONFIG_ECDH_1"; - -NVS1.$name = "CONFIG_NVSINTERNAL"; -NVS1.internalFlash.$name = "ti_drivers_nvs_NVSCC26XX0"; -NVS1.internalFlash.regionBase = 0xAA000; -NVS1.internalFlash.regionSize = 0x4000; - -NVS2.$name = "CONFIG_NVSEXTERNAL"; -NVS2.nvsType = "External"; // NVS Region Type -NVS2.$hardware = system.deviceData.board.components.MX25R8035F; - -RTOS.name = "FreeRTOS"; - -SHA21.$name = "CONFIG_SHA2_0"; - -TRNG1.$name = "CONFIG_TRNG_0"; - -TRNG2.$name = "CONFIG_TRNG_1"; - -TRNG3.$name = "CONFIG_TRNG_APP"; - -UART1.$name = "CONFIG_UART_DEBUG"; -UART1.uart.$assign = "UART1"; -UART1.uart.txPin.$assign = "boosterpack.4"; -UART1.uart.rxPin.$assign = "boosterpack.3"; -UART1.txPinInstance.$name = "CONFIG_PIN_4"; -UART1.rxPinInstance.$name = "CONFIG_PIN_5"; - -UART2.$name = "CONFIG_DISPLAY_UART"; -UART2.txPinInstance.$name = "CONFIG_PIN_6"; -UART2.rxPinInstance.$name = "CONFIG_PIN_7"; - - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -184,6 +76,90 @@ Button2.gpioPin.$name = "CONFIG_GPIO_BTN2"; Button2.gpioPin.pull = "Pull Up"; Button2.gpioPin.interruptTrigger = "Falling Edge"; +/* ======== CCFG ======== */ +var CCFG = scripting.addModule("/ti/devices/CCFG"); +const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; +for(var setting in ccfgSettings) +{ + CCFG[setting] = ccfgSettings[setting]; +} + +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; + +/* NVS */ +NVS1.$name = "CONFIG_NVSINTERNAL"; +NVS1.internalFlash.regionBase = 0xAA000; +NVS1.internalFlash.regionSize = 0x4000; + +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + +/* RF */ +/* if an antenna component exists, assign it to the rf instance */ +if (system.deviceData.board && system.deviceData.board.components.RF) { + RF.$hardware = system.deviceData.board.components.RF; +} + +const rfDesignSettings = system.getScript("/ti/common/lprf_rf_design_settings.js").rfDesignSettings; +for(var setting in rfDesignSettings) +{ + RFDesign[setting] = rfDesignSettings[setting]; +} + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -198,19 +174,65 @@ LED2.gpioPin.$name = "CONFIG_GPIO_GLED"; LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; -thread.deviceTypeReadOnly = true; -thread.pm.$name = "ti_thread_pm_thread_pm0"; -thread.rf.$name = "ti_thread_rf_thread_rf0"; -thread.rf.radioConfig.$name = "ti_devices_radioconfig_settings_ieee_15_40"; -thread.rf.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param0"; -thread.network.$name = "ti_thread_network_thread_network0"; -thread.security.$name = "ti_thread_security_thread_security0"; - -/** - * Pinmux solution for unlocked pins/peripherals. This ensures that minor changes to the automatic solver in a future - * version of the tool will not impact the pinmux you originally saw. These lines can be completely deleted in order to - * re-solve from scratch. - */ -UART2.uart.$suggestSolution = "UART0"; -UART2.uart.txPin.$suggestSolution = "boosterpack.30"; -UART2.uart.rxPin.$suggestSolution = "boosterpack.29"; +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; + +/* TRNG */ +TRNG1.$name = "CONFIG_TRNG_0"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; +TRNG3.$name = "CONFIG_TRNG_APP"; + +/* BLE */ +ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; +ble.maxConnNum = 1; +ble.numOfAdvSets = 1; +ble.lockProject = true; +ble.oneLibSizeOpt = true; +ble.maxPDUSize = 255; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; +ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; +ble.connUpdateParamsPeripheral.reqMinConnInt = 30; +ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + + +ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; +ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; + +/* DMM */ +dmm.project = "ti_thread_thermostat_remote_display"; +dmm.stackRoles = ["blePeripheral","threadFTD"]; +dmm.lockStackRoles = true; +dmm.numApplicationStates = 10; +dmm.applicationState0 = "ANY"; +dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; +dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; +dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; +dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; +dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; +dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; +dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; +dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; +dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; +dmm.policyArray.create(4); +dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; +dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; +dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; +dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; +dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; +dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; +dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; +dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; +dmm.policyArray[1].blePeripheral.weight = 25; +dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; +dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; +dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; +dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; +dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; +dmm.policyArray[2].threadFTD.weight = 30; +dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; +dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; +dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; +dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; +dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; +dmm.policyArray[3].threadFTD.weight = 1; diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp index 5eb903e6ca0688..4514cd7cd8b8d8 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -38,7 +38,7 @@ #include #include #include -#include +#include #endif #include #include @@ -135,7 +135,7 @@ int AppTask::Init() LED_Params ledParams; Button_Params buttonParams; - cc13x2_26x2LogInit(); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack Platform::MemoryInit(); @@ -221,7 +221,7 @@ int AppTask::Init() (void) initParams.InitializeStaticResourcesBeforeServerInit(); chip::Server::GetInstance().Init(initParams); -// Initialize device attestation config + // Initialize device attestation config #ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); #else diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp index a66a9e1a7ba1b4..54faa0db6e7314 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp @@ -7,7 +7,7 @@ * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 - *BoltLockManager + * * 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. diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h index 3cead418532caa..b925344ddb4c9a 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h +++ b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,9 +23,9 @@ extern "C" { #endif -int cc13x2_26x2LogInit(void); -void cc13x2_26x2Log(const char * aFormat, ...); -#define PLAT_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); #ifdef __cplusplus } diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h index 0f501990b2ab76..3a9c606e95c330 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h +++ b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2018 Nest Labs, Inc. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h b/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h index 5cb1c4369f9dd7..f99523c278db0c 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h +++ b/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h @@ -74,7 +74,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 1 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp index 6137478fc2ffcc..2b4be76e9c33da 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xCB00) +#define TOTAL_ICALL_HEAP_SIZE (0xC700) using namespace ::chip; using namespace ::chip::Inet; @@ -58,6 +57,17 @@ extern "C" void vApplicationStackOverflowHook(void) } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -70,8 +80,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn b/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn index d3031712c04a58..0155ff6461ddd9 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn @@ -37,7 +37,6 @@ ti_sysconfig("sysconfig") { sources = [ "${project_dir}/chip.syscfg" ] outputs = [ - "ti_devices_config.c", "ti_radio_config.c", "ti_radio_config.h", "ti_drivers_config.c", @@ -84,6 +83,7 @@ ti_simplelink_executable("pump_controller_app") { deps = [ ":sdk", ":sysconfig", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/examples/pump-controller-app/pump-controller-common", "${chip_root}/src/lib", ] diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni b/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni index 7d386dc216df2f..fb13057bc99474 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni @@ -29,10 +29,12 @@ lwip_debug = false chip_enable_ota_requestor = true +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" + # Disable CHIP Logging #chip_progress_logging = false -#chip_detail_logging = false -#chip_automation_logging = false +chip_detail_logging = false +chip_automation_logging = false # BLE options chip_config_network_layer_ble = true diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg b/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg index 47c7ded81c1b56..995ad22af6b435 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg @@ -17,158 +17,51 @@ * limitations under the License. */ -/** - * These arguments were used when this file was generated. They will be automatically applied on subsequent loads - * via the GUI or CLI. Run CLI with '--help' for additional information on how to override these arguments. - * @cliArgs --board "/ti/boards/CC26X2R1_LAUNCHXL" --product "simplelink_cc13x2_26x2_sdk@4.40.05.02_eng" - * @versions {"tool":"1.9.0+2015","templates":null} - */ - -/** - * Import the modules used in this configuration. - */ -const ble = scripting.addModule("/ti/ble5stack/ble"); -const CCFG = scripting.addModule("/ti/devices/CCFG"); -const rfdesign = scripting.addModule("/ti/devices/radioconfig/rfdesign"); -const dmm = scripting.addModule("/ti/dmm/dmm"); -const AESCCM = scripting.addModule("/ti/drivers/AESCCM"); -const AESCCM1 = AESCCM.addInstance(); -const AESCCM2 = AESCCM.addInstance(); -const AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); -const AESCTRDRBG1 = AESCTRDRBG.addInstance(); -const AESECB = scripting.addModule("/ti/drivers/AESECB"); -const AESECB1 = AESECB.addInstance(); -const AESECB2 = AESECB.addInstance(); -const ECDH = scripting.addModule("/ti/drivers/ECDH"); -const ECDH1 = ECDH.addInstance(); -const ECDH2 = ECDH.addInstance(); -const NVS = scripting.addModule("/ti/drivers/NVS"); -const NVS1 = NVS.addInstance(); -const NVS2 = NVS.addInstance(); -const RF = scripting.addModule("/ti/drivers/RF"); -const RTOS = scripting.addModule("/ti/drivers/RTOS"); -const SHA2 = scripting.addModule("/ti/drivers/SHA2"); -const SHA21 = SHA2.addInstance(); -const TRNG = scripting.addModule("/ti/drivers/TRNG"); -const TRNG1 = TRNG.addInstance(); -const TRNG2 = TRNG.addInstance(); -const TRNG3 = TRNG.addInstance(); -const UART = scripting.addModule("/ti/drivers/UART"); -const UART1 = UART.addInstance(); -const UART2 = UART.addInstance(); -const Button = scripting.addModule("/ti/drivers/apps/Button"); -const Button1 = Button.addInstance(); -const Button2 = Button.addInstance(); -const LED = scripting.addModule("/ti/drivers/apps/LED"); -const LED1 = LED.addInstance(); -const LED2 = LED.addInstance(); -const thread = scripting.addModule("/ti/thread/thread"); - -/** - * Write custom configuration values to the imported modules. - */ -ble.maxConnNum = 1; -ble.numOfAdvSets = 1; -ble.lockProject = true; -ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; -ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; -ble.connUpdateParamsPeripheral.reqMinConnInt = 30; -ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; -ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; -ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; -ble.advSet1.advData1.$name = "ti_ble5stack_broadcaster_advertisement_data0"; -ble.advSet1.scanRes1.$name = "ti_ble5stack_broadcaster_advertisement_data1"; - -CCFG.enableBootloader = true; -CCFG.enableBootloaderBackdoor = true; -CCFG.dioBootloaderBackdoor = 13; -CCFG.levelBootloaderBackdoor = "Active low"; -CCFG.srcClkLF = "Derived from HF XOSC"; -CCFG.ccfgTemplate.$name = "ti_devices_CCFGTemplate0"; - -dmm.project = "ti_thread_thermostat_remote_display"; -dmm.stackRoles = ["blePeripheral","threadFTD"]; -dmm.lockStackRoles = true; -dmm.numApplicationStates = 10; -dmm.applicationState0 = "ANY"; -dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; -dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; -dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; -dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; -dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; -dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; -dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; -dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; -dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; -dmm.policyArray.create(4); -dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; -dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; -dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; -dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; -dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; -dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; -dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; -dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; -dmm.policyArray[1].blePeripheral.weight = 25; -dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; -dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; -dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; -dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; -dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; -dmm.policyArray[2].threadFTD.weight = 30; -dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; -dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; -dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; -dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; -dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; -dmm.policyArray[3].threadFTD.weight = 1; -AESCCM1.$name = "CONFIG_AESCCM0"; - -AESCCM2.$name = "CONFIG_AESCCM_1"; +/* Modules */ +var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); +var AESECB = scripting.addModule("/ti/drivers/AESECB"); +var Button = scripting.addModule("/ti/drivers/apps/Button"); +var LED = scripting.addModule("/ti/drivers/apps/LED"); +var NVS = scripting.addModule("/ti/drivers/NVS"); +var RF = scripting.addModule("/ti/drivers/RF"); +var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); +var TRNG = scripting.addModule("/ti/drivers/TRNG"); +var SHA2 = scripting.addModule("/ti/drivers/SHA2"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); +var ble = scripting.addModule("/ti/ble5stack/ble"); +var dmm = scripting.addModule("/ti/dmm/dmm"); +var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); +var ECDH = scripting.addModule("/ti/drivers/ECDH"); + +/* Instances */ +var AESCCM1 = AESCCM.addInstance(); +var AESECB1 = AESECB.addInstance(); +var AESECB2 = AESECB.addInstance(); +var Button1 = Button.addInstance(); +var Button2 = Button.addInstance(); +var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); +var SHA21 = SHA2.addInstance(); +var LED1 = LED.addInstance(); +var LED2 = LED.addInstance(); +var TRNG1 = TRNG.addInstance(); +var TRNG2 = TRNG.addInstance(); +var TRNG3 = TRNG.addInstance(); +var UART2 = UART2.addInstance(); +var AESCTRDRBG1 = AESCTRDRBG.addInstance(); +var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; -AESECB1.$name = "CONFIG_AESECB0"; +AESCCM1.$name = "CONFIG_AESCCM0"; +AESECB1.$name = "CONFIG_AESECB0"; AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -ECDH2.$name = "CONFIG_ECDH_1"; - -NVS1.$name = "CONFIG_NVSINTERNAL"; -NVS1.internalFlash.$name = "ti_drivers_nvs_NVSCC26XX0"; -NVS1.internalFlash.regionBase = 0xAA000; -NVS1.internalFlash.regionSize = 0x4000; - -NVS2.$name = "CONFIG_NVSEXTERNAL"; -NVS2.nvsType = "External"; // NVS Region Type -NVS2.$hardware = system.deviceData.board.components.MX25R8035F; - -RTOS.name = "FreeRTOS"; - -SHA21.$name = "CONFIG_SHA2_0"; - -TRNG1.$name = "CONFIG_TRNG_0"; - -TRNG2.$name = "CONFIG_TRNG_1"; - -TRNG3.$name = "CONFIG_TRNG_APP"; - -UART1.$name = "CONFIG_UART_DEBUG"; -UART1.uart.$assign = "UART1"; -UART1.uart.txPin.$assign = "boosterpack.4"; -UART1.uart.rxPin.$assign = "boosterpack.3"; -UART1.txPinInstance.$name = "CONFIG_PIN_4"; -UART1.rxPinInstance.$name = "CONFIG_PIN_5"; - -UART2.$name = "CONFIG_DISPLAY_UART"; -UART2.txPinInstance.$name = "CONFIG_PIN_6"; -UART2.rxPinInstance.$name = "CONFIG_PIN_7"; - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -183,6 +76,90 @@ Button2.gpioPin.$name = "CONFIG_GPIO_BTN2"; Button2.gpioPin.pull = "Pull Up"; Button2.gpioPin.interruptTrigger = "Falling Edge"; +/* ======== CCFG ======== */ +var CCFG = scripting.addModule("/ti/devices/CCFG"); +const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; +for(var setting in ccfgSettings) +{ + CCFG[setting] = ccfgSettings[setting]; +} + +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; + +/* NVS */ +NVS1.$name = "CONFIG_NVSINTERNAL"; +NVS1.internalFlash.regionBase = 0xAA000; +NVS1.internalFlash.regionSize = 0x4000; + +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + +/* RF */ +/* if an antenna component exists, assign it to the rf instance */ +if (system.deviceData.board && system.deviceData.board.components.RF) { + RF.$hardware = system.deviceData.board.components.RF; +} + +const rfDesignSettings = system.getScript("/ti/common/lprf_rf_design_settings.js").rfDesignSettings; +for(var setting in rfDesignSettings) +{ + RFDesign[setting] = rfDesignSettings[setting]; +} + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -197,19 +174,65 @@ LED2.gpioPin.$name = "CONFIG_GPIO_GLED"; LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; -thread.deviceTypeReadOnly = true; -thread.pm.$name = "ti_thread_pm_thread_pm0"; -thread.rf.$name = "ti_thread_rf_thread_rf0"; -thread.rf.radioConfig.$name = "ti_devices_radioconfig_settings_ieee_15_40"; -thread.rf.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param0"; -thread.network.$name = "ti_thread_network_thread_network0"; -thread.security.$name = "ti_thread_security_thread_security0"; - -/** - * Pinmux solution for unlocked pins/peripherals. This ensures that minor changes to the automatic solver in a future - * version of the tool will not impact the pinmux you originally saw. These lines can be completely deleted in order to - * re-solve from scratch. - */ -UART2.uart.$suggestSolution = "UART0"; -UART2.uart.txPin.$suggestSolution = "boosterpack.30"; -UART2.uart.rxPin.$suggestSolution = "boosterpack.29"; +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; + +/* TRNG */ +TRNG1.$name = "CONFIG_TRNG_0"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; +TRNG3.$name = "CONFIG_TRNG_APP"; + +/* BLE */ +ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; +ble.maxConnNum = 1; +ble.numOfAdvSets = 1; +ble.lockProject = true; +ble.oneLibSizeOpt = true; +ble.maxPDUSize = 255; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; +ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; +ble.connUpdateParamsPeripheral.reqMinConnInt = 30; +ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + + +ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; +ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; + +/* DMM */ +dmm.project = "ti_thread_thermostat_remote_display"; +dmm.stackRoles = ["blePeripheral","threadFTD"]; +dmm.lockStackRoles = true; +dmm.numApplicationStates = 10; +dmm.applicationState0 = "ANY"; +dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; +dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; +dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; +dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; +dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; +dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; +dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; +dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; +dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; +dmm.policyArray.create(4); +dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; +dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; +dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; +dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; +dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; +dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; +dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; +dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; +dmm.policyArray[1].blePeripheral.weight = 25; +dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; +dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; +dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; +dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; +dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; +dmm.policyArray[2].threadFTD.weight = 30; +dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; +dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; +dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; +dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; +dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; +dmm.policyArray[3].threadFTD.weight = 1; diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp index e8611622fc28dd..8c4e51f44431fd 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -24,7 +24,8 @@ #include "FreeRTOS.h" #include -#include + +#include #include #include @@ -34,7 +35,7 @@ #include #include #include -#include +#include #endif #include #include @@ -122,7 +123,7 @@ int AppTask::Init() LED_Params ledParams; Button_Params buttonParams; - cc13x2_26x2LogInit(); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack chip::Platform::MemoryInit(); @@ -174,7 +175,11 @@ int AppTask::Init() chip::Server::GetInstance().Init(initParams); // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif // Initialize LEDs PLAT_LOG("Initialize LEDs"); diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp index 9dfc7e22e76687..e450a4b233eddb 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp @@ -7,7 +7,7 @@ * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 - *BoltLockManager + * * 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. diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h index 3cead418532caa..b925344ddb4c9a 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,9 +23,9 @@ extern "C" { #endif -int cc13x2_26x2LogInit(void); -void cc13x2_26x2Log(const char * aFormat, ...); -#define PLAT_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); #ifdef __cplusplus } diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h index 0f501990b2ab76..3a9c606e95c330 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2018 Nest Labs, Inc. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h index aca4a63dc9798f..97dac7bf1fe313 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h @@ -74,7 +74,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 1 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp index 6137478fc2ffcc..2b4be76e9c33da 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xCB00) +#define TOTAL_ICALL_HEAP_SIZE (0xC700) using namespace ::chip; using namespace ::chip::Inet; @@ -58,6 +57,17 @@ extern "C" void vApplicationStackOverflowHook(void) } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -70,8 +80,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); diff --git a/examples/shell/cc13x2x7_26x2x7/BUILD.gn b/examples/shell/cc13x2x7_26x2x7/BUILD.gn index 1b4716017365b7..691853a6f8ebc8 100644 --- a/examples/shell/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/shell/cc13x2x7_26x2x7/BUILD.gn @@ -85,6 +85,7 @@ ti_simplelink_executable("shell_app") { ":sdk", ":sysconfig", "${chip_root}/examples/all-clusters-app/all-clusters-common", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/examples/shell/shell_common:shell_common", "${chip_root}/src/lib", "${chip_root}/src/lib/shell:shell", diff --git a/examples/shell/cc13x2x7_26x2x7/args.gni b/examples/shell/cc13x2x7_26x2x7/args.gni index 58ec5edf1dbb5a..92dd1dcdfdd0b2 100644 --- a/examples/shell/cc13x2x7_26x2x7/args.gni +++ b/examples/shell/cc13x2x7_26x2x7/args.gni @@ -30,6 +30,7 @@ chip_enable_ota_requestor = false # Disable FTD Build for all-clusters app to save Flash chip_openthread_ftd = false +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" # Disable CHIP Logging chip_progress_logging = false diff --git a/examples/shell/cc13x2x7_26x2x7/chip.syscfg b/examples/shell/cc13x2x7_26x2x7/chip.syscfg index 738502f344e309..ed0e4a5c8d5fd6 100644 --- a/examples/shell/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/shell/cc13x2x7_26x2x7/chip.syscfg @@ -18,19 +18,16 @@ */ - /* Modules */ var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); var AESECB = scripting.addModule("/ti/drivers/AESECB"); -var ECJPAKE = scripting.addModule("/ti/drivers/ECJPAKE"); var NVS = scripting.addModule("/ti/drivers/NVS"); var RF = scripting.addModule("/ti/drivers/RF"); var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); -var RTOS = scripting.addModule("/ti/drivers/RTOS"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); var TRNG = scripting.addModule("/ti/drivers/TRNG"); -var Thread = scripting.addModule("/ti/thread/thread"); var SHA2 = scripting.addModule("/ti/drivers/SHA2"); -var UART = scripting.addModule("/ti/drivers/UART"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); var ble = scripting.addModule("/ti/ble5stack/ble"); var dmm = scripting.addModule("/ti/dmm/dmm"); var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); @@ -40,19 +37,17 @@ var ECDH = scripting.addModule("/ti/drivers/ECDH"); var AESCCM1 = AESCCM.addInstance(); var AESECB1 = AESECB.addInstance(); var AESECB2 = AESECB.addInstance(); -var ECJPAKE = ECJPAKE.addInstance(); var NVS1 = NVS.addInstance(); var NVS2 = NVS.addInstance(); var SHA21 = SHA2.addInstance(); var TRNG1 = TRNG.addInstance(); var TRNG2 = TRNG.addInstance(); var TRNG3 = TRNG.addInstance(); -var UART1 = UART.addInstance(); +var UART2 = UART2.addInstance(); var AESCTRDRBG1 = AESCTRDRBG.addInstance(); var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; AESCCM1.$name = "CONFIG_AESCCM0"; @@ -92,17 +87,68 @@ for(var setting in rfDesignSettings) RFDesign[setting] = rfDesignSettings[setting]; } -/* Streamer UART */ -UART1.$hardware = system.deviceData.board.components.XDS110UART; -UART1.$name = "CONFIG_UART_STREAMER"; + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART_STREAMER"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; TRNG3.$name = "CONFIG_TRNG_APP"; -RTOS.name = "FreeRTOS"; - /* BLE */ ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; ble.maxConnNum = 1; @@ -110,7 +156,7 @@ ble.numOfAdvSets = 1; ble.lockProject = true; ble.oneLibSizeOpt = true; ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; ble.connUpdateParamsPeripheral.reqMinConnInt = 30; ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; diff --git a/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h b/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h index 969a02acb089ca..1e8f718031e90f 100644 --- a/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h +++ b/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h @@ -75,7 +75,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (256) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 0 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 0 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT diff --git a/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp index 8e29789d2639cd..dda97f4e566ef5 100644 --- a/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp @@ -25,17 +25,18 @@ #include #include -#include #include #include #include +#include + #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR #include #include #include #include -#include +#include #endif #include #include @@ -60,7 +61,7 @@ static TaskHandle_t sAppTaskHandle; // Logging extern "C" { -int cc13x2_26x2LogInit(void); +int cc13xx_26xxLogInit(void); } #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR @@ -102,7 +103,7 @@ CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; - cc13x2_26x2LogInit(); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack Platform::MemoryInit(); @@ -150,7 +151,12 @@ CHIP_ERROR AppTask::Init() chip::Server::GetInstance().Init(initParams); // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR InitializeOTARequestor(); #endif diff --git a/examples/shell/cc13x2x7_26x2x7/main/main.cpp b/examples/shell/cc13x2x7_26x2x7/main/main.cpp index 198e5c906b3f94..884744230dfc56 100644 --- a/examples/shell/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/shell/cc13x2x7_26x2x7/main/main.cpp @@ -29,7 +29,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xc800) +#define TOTAL_ICALL_HEAP_SIZE (0xc700) using namespace ::chip; using namespace ::chip::Inet; @@ -58,6 +57,17 @@ extern "C" void vApplicationStackOverflowHook(void) } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -72,8 +82,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); diff --git a/scripts/checkout_submodules.py b/scripts/checkout_submodules.py index ec4f67bc60fdf9..a401cf8bdbe3e8 100755 --- a/scripts/checkout_submodules.py +++ b/scripts/checkout_submodules.py @@ -29,7 +29,7 @@ 'android', 'bl602', 'bouffalolab', - 'cc13x2_26x2', + 'cc13xx_26xx', 'cc32xx', 'darwin', 'efr32', diff --git a/src/lib/shell/BUILD.gn b/src/lib/shell/BUILD.gn index 68af8be17cb766..67d6b1d69ab5b6 100644 --- a/src/lib/shell/BUILD.gn +++ b/src/lib/shell/BUILD.gn @@ -92,10 +92,11 @@ static_library("shell") { "MainLoopDefault.cpp", "streamer_bouffalolab.cpp", ] - } else if (chip_device_platform == "cc13x2_26x2") { + } else if (chip_device_platform == "cc13x2_26x2" || + chip_device_platform == "cc13x4_26x4") { sources += [ "MainLoopDefault.cpp", - "streamer_cc13x2_26x2.cpp", + "streamer_cc13x4_26x4.cpp", ] } else if (chip_device_platform == "mw320") { sources += [ diff --git a/src/lib/shell/streamer_cc13x4_26x4.cpp b/src/lib/shell/streamer_cc13x4_26x4.cpp new file mode 100644 index 00000000000000..259674a96e1fb7 --- /dev/null +++ b/src/lib/shell/streamer_cc13x4_26x4.cpp @@ -0,0 +1,109 @@ +/* + * + * 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. + */ + +/** + * @file + * Source implementation of an input / output stream for cc13xx_26xx targets + */ + +#include "streamer.h" +#include +#include +#include +#include + +#include "ti_drivers_config.h" + +#include + +namespace chip { +namespace Shell { + +#ifndef SHELL_STREAMER_APP_SPECIFIC + +UART2_Handle sStreamUartHandle = NULL; + +#if !MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED +extern "C" int cc13xx_26xxLogInit(void) +{ + return 0; +} + +extern "C" void cc13xx_26xxVLog(const char * msg, va_list v) +{ + if (NULL != sStreamUartHandle) + { + static char sDebugUartBuffer[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; + size_t ret; + + ret = vsnprintf(sDebugUartBuffer, sizeof(sDebugUartBuffer), msg, v); + if (0 < ret) + { + // PuTTY likes \r\n + size_t len = (ret + 2U) < sizeof(sDebugUartBuffer) ? (ret + 2) : sizeof(sDebugUartBuffer); + sDebugUartBuffer[len - 2] = '\r'; + sDebugUartBuffer[len - 1] = '\n'; + + UART2_write(sStreamUartHandle, sDebugUartBuffer, len, NULL); + } + } +} +#endif // !MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED + +int streamer_cc13xx_26xx_init(streamer_t * streamer) +{ + UART2_Params uartParams; + + UART2_Params_init(&uartParams); + // Most params can be default because we only send data, we don't receive + uartParams.baudRate = 115200; + + sStreamUartHandle = UART2_open(CONFIG_UART_STREAMER, &uartParams); + return 0; +} + +ssize_t streamer_cc13xx_26xx_read(streamer_t * streamer, char * buf, size_t len) +{ + (void) streamer; + size_t ret; + + UART2_read(sStreamUartHandle, buf, len, &ret); + + return ret; +} + +ssize_t streamer_cc13xx_26xx_write(streamer_t * streamer, const char * buf, size_t len) +{ + (void) streamer; + return UART2_write(sStreamUartHandle, buf, len, NULL); +} + +static streamer_t streamer_cc13xx_26xx = { + .init_cb = streamer_cc13xx_26xx_init, + .read_cb = streamer_cc13xx_26xx_read, + .write_cb = streamer_cc13xx_26xx_write, +}; + +streamer_t * streamer_get() +{ + return &streamer_cc13xx_26xx; +} + +#endif //#ifndef SHELL_STREAMER_APP_SPECIFIC + +} // namespace Shell +} // namespace chip diff --git a/src/lwip/BUILD.gn b/src/lwip/BUILD.gn index 013310053c0f6d..8f91f9ec2685da 100644 --- a/src/lwip/BUILD.gn +++ b/src/lwip/BUILD.gn @@ -29,7 +29,7 @@ if (lwip_platform == "") { } assert(lwip_platform == "external" || lwip_platform == "standalone" || - lwip_platform == "cc13x2_26x2" || lwip_platform == "cc32xx" || + lwip_platform == "cc13xx_26xx" || lwip_platform == "cc32xx" || lwip_platform == "silabs" || lwip_platform == "k32w0" || lwip_platform == "qpg" || lwip_platform == "mbed" || lwip_platform == "psoc6" || lwip_platform == "cyw30739" || @@ -44,7 +44,7 @@ if (lwip_platform != "external") { } } -if (lwip_platform == "cc13x2_26x2") { +if (lwip_platform == "cc13xx_26xx") { import("//build_overrides/ti_simplelink_sdk.gni") } else if (lwip_platform == "cc32xx") { import("//build_overrides/ti_simplelink_sdk.gni") @@ -180,7 +180,7 @@ if (current_os == "zephyr" || current_os == "mbed") { } public_deps = [ ":lwip_buildconfig" ] - if (lwip_platform == "cc13x2_26x2") { + if (lwip_platform == "cc13xx_26xx") { public_deps += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk" ] } else if (lwip_platform == "cc32xx") { public_deps += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk" ] diff --git a/src/lwip/cc13x2_26x2/arch/cc.h b/src/lwip/cc13xx_26xx/arch/cc.h similarity index 100% rename from src/lwip/cc13x2_26x2/arch/cc.h rename to src/lwip/cc13xx_26xx/arch/cc.h diff --git a/src/lwip/cc13x2_26x2/arch/perf.h b/src/lwip/cc13xx_26xx/arch/perf.h similarity index 100% rename from src/lwip/cc13x2_26x2/arch/perf.h rename to src/lwip/cc13xx_26xx/arch/perf.h diff --git a/src/lwip/cc13x2_26x2/lwipopts.h b/src/lwip/cc13xx_26xx/lwipopts.h similarity index 97% rename from src/lwip/cc13x2_26x2/lwipopts.h rename to src/lwip/cc13xx_26xx/lwipopts.h index 387232e369c3ec..925a06d2615bf8 100644 --- a/src/lwip/cc13x2_26x2/lwipopts.h +++ b/src/lwip/cc13xx_26xx/lwipopts.h @@ -77,8 +77,8 @@ #define LWIP_IPV6_ROUTER_SUPPORT 0 #define LWIP_ND6_LISTEN_RA 0 -#define LWIP_ND6_NUM_NEIGHBORS (0) -#define LWIP_ND6_NUM_DESTINATIONS (0) +#define LWIP_ND6_NUM_NEIGHBORS (1) +#define LWIP_ND6_NUM_DESTINATIONS (1) #define LWIP_ND6_NUM_PREFIXES (0) #define LWIP_ND6_NUM_ROUTERS (0) #define LWIP_ND6_MAX_MULTICAST_SOLICIT (0) @@ -110,7 +110,8 @@ #define LWIP_IPV6_NUM_ADDRESSES 5 -#define LWIP_IPV6_ND 0 +#define LWIP_IPV6_MLD 1 +#define LWIP_IPV6_ND 1 #define LWIP_ND6_QUEUEING 0 #define LWIP_MULTICAST_PING 0 diff --git a/src/lwip/cc13x2_26x2/lwippools.h b/src/lwip/cc13xx_26xx/lwippools.h similarity index 100% rename from src/lwip/cc13x2_26x2/lwippools.h rename to src/lwip/cc13xx_26xx/lwippools.h diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index b4876e13103364..8cd18955cc43d9 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -149,7 +149,12 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { if (chip_device_platform == "cc13x2_26x2") { defines += [ "CHIP_DEVICE_LAYER_TARGET_CC13X2_26X2=1", - "CHIP_DEVICE_LAYER_TARGET=cc13x2_26x2", + "CHIP_DEVICE_LAYER_TARGET=cc13xx_26xx/cc13x2_26x2", + ] + } else if (chip_device_platform == "cc13x4_26x4") { + defines += [ + "CHIP_DEVICE_LAYER_TARGET_CC13X4_26X4=1", + "CHIP_DEVICE_LAYER_TARGET=cc13xx_26xx/cc13x4_26x4", ] } else if (chip_device_platform == "cc32xx") { defines += [ @@ -416,7 +421,9 @@ if (chip_device_platform != "none") { ] if (chip_device_platform == "cc13x2_26x2") { - _platform_target = "cc13x2_26x2" + _platform_target = "cc13xx_26xx/cc13x2_26x2" + } else if (chip_device_platform == "cc13x4_26x4") { + _platform_target = "cc13xx_26xx/cc13x4_26x4" } else if (chip_device_platform == "cc32xx") { _platform_target = "cc32xx" } else if (chip_device_platform == "darwin") { diff --git a/src/platform/cc13x2_26x2/BLEManagerImpl.cpp b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp similarity index 99% rename from src/platform/cc13x2_26x2/BLEManagerImpl.cpp rename to src/platform/cc13xx_26xx/BLEManagerImpl.cpp index 1aa871a977b855..65c5cf0a2d9938 100644 --- a/src/platform/cc13x2_26x2/BLEManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp @@ -61,8 +61,8 @@ extern "C" { // BLE Manager Debug Logs extern "C" { #ifdef BLEMGR_DBG_LOGGING -extern void cc13x2_26x2Log(const char * aFormat, ...); -#define BLEMGR_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +extern void cc13xx_26xxLog(const char * aFormat, ...); +#define BLEMGR_LOG(...) cc13xx_26xxLog(__VA_ARGS__); #else #define BLEMGR_LOG(...) #endif diff --git a/src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp b/src/platform/cc13xx_26xx/CC13XX_26XXConfig.cpp similarity index 60% rename from src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp rename to src/platform/cc13xx_26xx/CC13XX_26XXConfig.cpp index 70abc0fc6f6812..c0475e0d015610 100644 --- a/src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp +++ b/src/platform/cc13xx_26xx/CC13XX_26XXConfig.cpp @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include @@ -44,94 +44,95 @@ namespace Internal { /* itemID and subID are limited to 10 bits, even though their types are uint16_t */ // Keys stored in the Chip-factory namespace -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SerialNum = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0001 } + +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_SerialNum = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0001 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceId = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0002 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_MfrDeviceId = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0002 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceCert = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0003 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_MfrDeviceCert = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0003 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceICACerts = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0004 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_MfrDeviceICACerts = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0004 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDevicePrivateKey = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0005 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_MfrDevicePrivateKey = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0005 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_HardwareVersion = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0006 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_HardwareVersion = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0006 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ManufacturingDate = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0007 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_ManufacturingDate = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0007 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SetupPinCode = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0008 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_SetupPinCode = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0008 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SetupDiscriminator = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0009 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_SetupDiscriminator = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0009 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pIterationCount = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x000a } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_Spake2pIterationCount = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x000a } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pSalt = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x000b } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_Spake2pSalt = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x000b } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pVerifier = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x000c } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_Spake2pVerifier = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x000c } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_LifeTimeCounter = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0010 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_LifeTimeCounter = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipFactory, .subID = 0x0010 } }; // Keys stored in the Chip-counters namespace -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_BootCount = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipCounters, .subID = 0x000d } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_BootCount = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipCounters, .subID = 0x000d } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_TotalOperationalHours = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipCounters, .subID = 0x000f } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_TotalOperationalHours = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipCounters, .subID = 0x000f } }; // Keys stored in the Chip-config namespace -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ServiceConfig = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0012 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_ServiceConfig = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x0012 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_PairedAccountId = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0013 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_PairedAccountId = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x0013 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ServiceId = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0014 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_ServiceId = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x0014 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_LastUsedEpochKeyId = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x00017 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_LastUsedEpochKeyId = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x00017 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_FailSafeArmed = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x00018 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_FailSafeArmed = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x00018 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_WiFiStationSecType = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x00019 } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_WiFiStationSecType = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x00019 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_RegulatoryLocation = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0001a } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_RegulatoryLocation = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x0001a } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_CountryCode = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0001b } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_CountryCode = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x0001b } }; // itemID 0x001c is unused (used to be breadcrumb). -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_UniqueId = { - { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0001d } +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_UniqueId = { + { .systemID = kCC13XX_26XXMatter_SysID, .itemID = kCC13XX_26XXMatter_ItemID_ChipConfig, .subID = 0x0001d } }; /* Internal for the KVS interface. */ -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_KVS_key = { { .systemID = kCC13X2_26X2Matter_SysID, - .itemID = kCC13X2_26X2Matter_ItemID_ChipKVS_key } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_KVS_value = { { .systemID = kCC13X2_26X2Matter_SysID, - .itemID = kCC13X2_26X2Matter_ItemID_ChipKVS_value } }; +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_KVS_key = { { .systemID = kCC13XX_26XXMatter_SysID, + .itemID = kCC13XX_26XXMatter_ItemID_ChipKVS_key } }; +const CC13XX_26XXConfig::Key CC13XX_26XXConfig::kConfigKey_KVS_value = { { .systemID = kCC13XX_26XXMatter_SysID, + .itemID = kCC13XX_26XXMatter_ItemID_ChipKVS_value } }; /* Static local variables */ static NVINTF_nvFuncts_t sNvoctpFps = { 0 }; -CHIP_ERROR CC13X2_26X2Config::Init() +CHIP_ERROR CC13XX_26XXConfig::Init() { CHIP_ERROR err = CHIP_NO_ERROR; @@ -144,7 +145,7 @@ CHIP_ERROR CC13X2_26X2Config::Init() return err; } -CHIP_ERROR CC13X2_26X2Config::ReadConfigValue(Key key, bool & val) +CHIP_ERROR CC13XX_26XXConfig::ReadConfigValue(Key key, bool & val) { CHIP_ERROR ret; size_t ignore; @@ -152,32 +153,32 @@ CHIP_ERROR CC13X2_26X2Config::ReadConfigValue(Key key, bool & val) ret = ReadConfigValueBin(key, &localVal, sizeof(localVal), ignore); - // reference CC13X2_26X2Config::WriteConfigValue(Key key, bool val) for storage of boolean values + // reference CC13XX_26XXConfig::WriteConfigValue(Key key, bool val) for storage of boolean values val = (localVal != 0); return ret; } -CHIP_ERROR CC13X2_26X2Config::ReadConfigValue(Key key, uint32_t & val) +CHIP_ERROR CC13XX_26XXConfig::ReadConfigValue(Key key, uint32_t & val) { size_t ignore; return ReadConfigValueBin(key, (uint8_t *) &val, sizeof(val), ignore); } -CHIP_ERROR CC13X2_26X2Config::ReadConfigValue(Key key, uint64_t & val) +CHIP_ERROR CC13XX_26XXConfig::ReadConfigValue(Key key, uint64_t & val) { size_t ignore; return ReadConfigValueBin(key, (uint8_t *) &val, sizeof(val), ignore); } -CHIP_ERROR CC13X2_26X2Config::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR CC13XX_26XXConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { return ReadConfigValueBin(key, (uint8_t *) buf, bufSize, outLen); } -CHIP_ERROR CC13X2_26X2Config::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR CC13XX_26XXConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { CHIP_ERROR err = CHIP_NO_ERROR; size_t len; @@ -195,15 +196,16 @@ CHIP_ERROR CC13X2_26X2Config::ReadConfigValueBin(Key key, uint8_t * buf, size_t return err; } -/* Iterate through the key range to find a key that matches. */ static uint8_t FindKVSSubID(const char * key, uint16_t & subID) { char key_scratch[PersistentStorageDelegate::kKeyLengthMax + 1]; NVINTF_nvProxy_t nvProxy = { 0 }; uint8_t status = NVINTF_SUCCESS; + // Store first valid sub ID that has already been found in NV to prevent re-scanning the same page + uint16_t firstSubID = 0xffff; - nvProxy.sysid = CC13X2_26X2Config::kConfigKey_KVS_key.nvID.systemID; - nvProxy.itemid = CC13X2_26X2Config::kConfigKey_KVS_key.nvID.itemID; + nvProxy.sysid = CC13XX_26XXConfig::kConfigKey_KVS_key.nvID.systemID; + nvProxy.itemid = CC13XX_26XXConfig::kConfigKey_KVS_key.nvID.itemID; nvProxy.buffer = key_scratch; nvProxy.len = sizeof(key_scratch); nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DOREAD; @@ -222,17 +224,28 @@ static uint8_t FindKVSSubID(const char * key, uint16_t & subID) subID = nvProxy.subid; break; } + if (firstSubID == 0xFFFF) + { + firstSubID = nvProxy.subid; + } + else if (firstSubID == nvProxy.subid) + { + // Scanned all of NV with no new subID found. + status = NVINTF_NOTFOUND; + break; + } + } while (NVINTF_SUCCESS == status); sNvoctpFps.unlockNV(lock_key); return status; } -CHIP_ERROR CC13X2_26X2Config::ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, +CHIP_ERROR CC13XX_26XXConfig::ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes) { CHIP_ERROR err = CHIP_NO_ERROR; - NVINTF_itemID_t val_item = CC13X2_26X2Config::kConfigKey_KVS_value.nvID; + NVINTF_itemID_t val_item = CC13XX_26XXConfig::kConfigKey_KVS_value.nvID; uint16_t subID; size_t len; uint16_t read_len; @@ -269,39 +282,39 @@ CHIP_ERROR CC13X2_26X2Config::ReadKVS(const char * key, void * value, size_t val return err; } -CHIP_ERROR CC13X2_26X2Config::WriteConfigValue(Key key, bool val) +CHIP_ERROR CC13XX_26XXConfig::WriteConfigValue(Key key, bool val) { uint8_t localVal = val ? 1 : 0; return WriteConfigValueBin(key, (const uint8_t *) &localVal, sizeof(localVal)); } -CHIP_ERROR CC13X2_26X2Config::WriteConfigValue(Key key, uint32_t val) +CHIP_ERROR CC13XX_26XXConfig::WriteConfigValue(Key key, uint32_t val) { return WriteConfigValueBin(key, (const uint8_t *) &val, sizeof(val)); } -CHIP_ERROR CC13X2_26X2Config::WriteConfigValue(Key key, uint64_t val) +CHIP_ERROR CC13XX_26XXConfig::WriteConfigValue(Key key, uint64_t val) { return WriteConfigValueBin(key, (const uint8_t *) &val, sizeof(val)); } -CHIP_ERROR CC13X2_26X2Config::WriteConfigValueStr(Key key, const char * str) +CHIP_ERROR CC13XX_26XXConfig::WriteConfigValueStr(Key key, const char * str) { size_t strLen = strlen(str); return WriteConfigValueBin(key, (const uint8_t *) str, strLen); } -CHIP_ERROR CC13X2_26X2Config::WriteConfigValueStr(Key key, const char * str, size_t strLen) +CHIP_ERROR CC13XX_26XXConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen) { return WriteConfigValueBin(key, (const uint8_t *) str, strLen); } -CHIP_ERROR CC13X2_26X2Config::WriteKVS(const char * key, const void * value, size_t value_size) +CHIP_ERROR CC13XX_26XXConfig::WriteKVS(const char * key, const void * value, size_t value_size) { CHIP_ERROR err = CHIP_NO_ERROR; uint16_t subID; - NVINTF_itemID_t key_item = CC13X2_26X2Config::kConfigKey_KVS_key.nvID; - NVINTF_itemID_t val_item = CC13X2_26X2Config::kConfigKey_KVS_value.nvID; + NVINTF_itemID_t key_item = CC13XX_26XXConfig::kConfigKey_KVS_key.nvID; + NVINTF_itemID_t val_item = CC13XX_26XXConfig::kConfigKey_KVS_value.nvID; if (FindKVSSubID(key, subID) != NVINTF_SUCCESS) { @@ -354,7 +367,7 @@ CHIP_ERROR CC13X2_26X2Config::WriteKVS(const char * key, const void * value, siz return err; } -CHIP_ERROR CC13X2_26X2Config::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) +CHIP_ERROR CC13XX_26XXConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -364,12 +377,12 @@ CHIP_ERROR CC13X2_26X2Config::WriteConfigValueBin(Key key, const uint8_t * data, return err; } -CHIP_ERROR CC13X2_26X2Config::ClearKVS(const char * key) +CHIP_ERROR CC13XX_26XXConfig::ClearKVS(const char * key) { CHIP_ERROR err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; uint16_t subID; - NVINTF_itemID_t key_item = CC13X2_26X2Config::kConfigKey_KVS_key.nvID; - NVINTF_itemID_t val_item = CC13X2_26X2Config::kConfigKey_KVS_value.nvID; + NVINTF_itemID_t key_item = CC13XX_26XXConfig::kConfigKey_KVS_key.nvID; + NVINTF_itemID_t val_item = CC13XX_26XXConfig::kConfigKey_KVS_value.nvID; if (FindKVSSubID(key, subID) == NVINTF_SUCCESS) { @@ -396,7 +409,7 @@ CHIP_ERROR CC13X2_26X2Config::ClearKVS(const char * key) return err; } -CHIP_ERROR CC13X2_26X2Config::ClearConfigValue(Key key) +CHIP_ERROR CC13XX_26XXConfig::ClearConfigValue(Key key) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -405,13 +418,13 @@ CHIP_ERROR CC13X2_26X2Config::ClearConfigValue(Key key) return err; } -bool CC13X2_26X2Config::ConfigValueExists(Key key) +bool CC13XX_26XXConfig::ConfigValueExists(Key key) { /* 0 is an invalid length for an item, getting a length of 0 means there is no item */ return (0 != sNvoctpFps.getItemLen(key.nvID)); } -CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) +CHIP_ERROR CC13XX_26XXConfig::FactoryResetConfig(void) { CHIP_ERROR err = CHIP_NO_ERROR; NVINTF_nvProxy_t nvProxy = { 0 }; @@ -423,8 +436,8 @@ CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) intptr_t key = sNvoctpFps.lockNV(); /* Setup doNext call */ - nvProxy.sysid = kCC13X2_26X2Matter_SysID; - nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipConfig; + nvProxy.sysid = kCC13XX_26XXMatter_SysID; + nvProxy.itemid = kCC13XX_26XXMatter_ItemID_ChipConfig; nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; /* Lock and wipe all items with config itemid */ @@ -436,8 +449,8 @@ CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); /* Setup doNext call */ - nvProxy.sysid = kCC13X2_26X2Matter_SysID; - nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipCounters; + nvProxy.sysid = kCC13XX_26XXMatter_SysID; + nvProxy.itemid = kCC13XX_26XXMatter_ItemID_ChipCounters; nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; /* Lock and wipe all items with counters itemid */ @@ -449,8 +462,8 @@ CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); /* Setup doNext call */ - nvProxy.sysid = kCC13X2_26X2Matter_SysID; - nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipKVS_key; + nvProxy.sysid = kCC13XX_26XXMatter_SysID; + nvProxy.itemid = kCC13XX_26XXMatter_ItemID_ChipKVS_key; nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; /* Lock and wipe all items with kvs_key itemid */ @@ -462,8 +475,8 @@ CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); /* Setup doNext call */ - nvProxy.sysid = kCC13X2_26X2Matter_SysID; - nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipKVS_value; + nvProxy.sysid = kCC13XX_26XXMatter_SysID; + nvProxy.itemid = kCC13XX_26XXMatter_ItemID_ChipKVS_value; nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; /* Lock and wipe all items with key_value itemid */ @@ -485,10 +498,10 @@ CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) return err; } -void CC13X2_26X2Config::RunConfigUnitTest() +void CC13XX_26XXConfig::RunConfigUnitTest() { // Run common unit test. - ::chip::DeviceLayer::Internal::RunConfigUnitTest(); + ::chip::DeviceLayer::Internal::RunConfigUnitTest(); } } // namespace Internal diff --git a/src/platform/cc13x2_26x2/CC13X2_26X2Config.h b/src/platform/cc13xx_26xx/CC13XX_26XXConfig.h similarity index 89% rename from src/platform/cc13x2_26x2/CC13X2_26X2Config.h rename to src/platform/cc13xx_26xx/CC13XX_26XXConfig.h index f3e8191aeca011..2450c0f8c50544 100644 --- a/src/platform/cc13x2_26x2/CC13X2_26X2Config.h +++ b/src/platform/cc13xx_26xx/CC13XX_26XXConfig.h @@ -19,7 +19,7 @@ /** * @file * Utilities for accessing persisted device configuration on - * Texas Instruments cc13x2_26x2 SoCs. + * Texas Instruments cc13xx_26xx SoCs. */ #pragma once @@ -32,7 +32,7 @@ namespace chip { namespace DeviceLayer { namespace Internal { -class CC13X2_26X2Config +class CC13XX_26XXConfig { public: struct Key; @@ -46,13 +46,13 @@ class CC13X2_26X2Config static constexpr uint16_t kNVinf_itemid_chipKVS_key = 4; static constexpr uint16_t kNVinf_itemid_chipKVS_value = 5; - static const uint16_t kCC13X2_26X2Matter_SysID = kNvinf_sysid_chip; + static const uint16_t kCC13XX_26XXMatter_SysID = kNvinf_sysid_chip; - static const uint16_t kCC13X2_26X2Matter_ItemID_ChipConfig = kNVinf_itemid_chipConfig; - static const uint16_t kCC13X2_26X2Matter_ItemID_ChipFactory = kNVinf_itemid_chipFactory; - static const uint16_t kCC13X2_26X2Matter_ItemID_ChipCounters = kNVinf_itemid_chipCounters; - static const uint16_t kCC13X2_26X2Matter_ItemID_ChipKVS_key = kNVinf_itemid_chipKVS_key; - static const uint16_t kCC13X2_26X2Matter_ItemID_ChipKVS_value = kNVinf_itemid_chipKVS_value; + static const uint16_t kCC13XX_26XXMatter_ItemID_ChipConfig = kNVinf_itemid_chipConfig; + static const uint16_t kCC13XX_26XXMatter_ItemID_ChipFactory = kNVinf_itemid_chipFactory; + static const uint16_t kCC13XX_26XXMatter_ItemID_ChipCounters = kNVinf_itemid_chipCounters; + static const uint16_t kCC13XX_26XXMatter_ItemID_ChipKVS_key = kNVinf_itemid_chipKVS_key; + static const uint16_t kCC13XX_26XXMatter_ItemID_ChipKVS_value = kNVinf_itemid_chipKVS_value; // Key definitions for well-known keys. static const Key kConfigKey_SerialNum; @@ -108,14 +108,14 @@ class CC13X2_26X2Config static CHIP_ERROR ClearKVS(const char * key); }; -struct CC13X2_26X2Config::Key +struct CC13XX_26XXConfig::Key { NVINTF_itemID_t nvID; bool operator==(const Key & other) const; }; -inline bool CC13X2_26X2Config::Key::operator==(const Key & other) const +inline bool CC13XX_26XXConfig::Key::operator==(const Key & other) const { return (nvID.systemID == other.nvID.systemID && nvID.itemID == other.nvID.itemID && nvID.subID == other.nvID.subID); } diff --git a/src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp b/src/platform/cc13xx_26xx/ConfigurationManagerImpl.cpp similarity index 79% rename from src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp rename to src/platform/cc13xx_26xx/ConfigurationManagerImpl.cpp index 7d420bab1c93e2..794b6fe169ff7f 100644 --- a/src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/ConfigurationManagerImpl.cpp @@ -30,7 +30,7 @@ #include #include -#include +#include #include #include @@ -65,7 +65,7 @@ CHIP_ERROR ConfigurationManagerImpl::Init() CHIP_ERROR err; // Initialize the generic implementation base class. - err = Internal::GenericConfigurationManagerImpl::Init(); + err = Internal::GenericConfigurationManagerImpl::Init(); SuccessOrExit(err); IncreaseBootCount(); @@ -86,7 +86,7 @@ void ConfigurationManagerImpl::InitiateFactoryReset() CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) { - return ReadConfigValue(CC13X2_26X2Config::kConfigKey_BootCount, rebootCount); + return ReadConfigValue(CC13XX_26XXConfig::kConfigKey_BootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::IncreaseBootCount(void) @@ -94,11 +94,11 @@ CHIP_ERROR ConfigurationManagerImpl::IncreaseBootCount(void) CHIP_ERROR ret; uint32_t bootCount = 0; - ret = ReadConfigValue(CC13X2_26X2Config::kConfigKey_BootCount, bootCount); + ret = ReadConfigValue(CC13XX_26XXConfig::kConfigKey_BootCount, bootCount); if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == ret || CHIP_NO_ERROR == ret) { - ret = WriteConfigValue(CC13X2_26X2Config::kConfigKey_BootCount, bootCount + 1); + ret = WriteConfigValue(CC13XX_26XXConfig::kConfigKey_BootCount, bootCount + 1); } return ret; @@ -108,7 +108,7 @@ CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOp { CHIP_ERROR ret; - ret = ReadConfigValue(CC13X2_26X2Config::kConfigKey_TotalOperationalHours, totalOperationalHours); + ret = ReadConfigValue(CC13XX_26XXConfig::kConfigKey_TotalOperationalHours, totalOperationalHours); if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == ret) { @@ -121,12 +121,12 @@ CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOp CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) { - return WriteConfigValue(CC13X2_26X2Config::kConfigKey_TotalOperationalHours, totalOperationalHours); + return WriteConfigValue(CC13XX_26XXConfig::kConfigKey_TotalOperationalHours, totalOperationalHours); } CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) { - CC13X2_26X2Config::Key configKey{ { CC13X2_26X2Config::kCC13X2_26X2Matter_SysID, key } }; + CC13XX_26XXConfig::Key configKey{ { CC13XX_26XXConfig::kCC13XX_26XXMatter_SysID, key } }; CHIP_ERROR err = ReadConfigValue(configKey, value); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) @@ -138,68 +138,68 @@ CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform: CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) { - CC13X2_26X2Config::Key configKey{ { CC13X2_26X2Config::kCC13X2_26X2Matter_SysID, key } }; + CC13XX_26XXConfig::Key configKey{ { CC13XX_26XXConfig::kCC13XX_26XXMatter_SysID, key } }; return WriteConfigValue(configKey, value); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) { - return CC13X2_26X2Config::ReadConfigValue(key, val); + return CC13XX_26XXConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) { - return CC13X2_26X2Config::ReadConfigValue(key, val); + return CC13XX_26XXConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) { - return CC13X2_26X2Config::ReadConfigValue(key, val); + return CC13XX_26XXConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { - return CC13X2_26X2Config::ReadConfigValueStr(key, buf, bufSize, outLen); + return CC13XX_26XXConfig::ReadConfigValueStr(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { - return CC13X2_26X2Config::ReadConfigValueBin(key, buf, bufSize, outLen); + return CC13XX_26XXConfig::ReadConfigValueBin(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) { - return CC13X2_26X2Config::WriteConfigValue(key, val); + return CC13XX_26XXConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) { - return CC13X2_26X2Config::WriteConfigValue(key, val); + return CC13XX_26XXConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) { - return CC13X2_26X2Config::WriteConfigValue(key, val); + return CC13XX_26XXConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) { - return CC13X2_26X2Config::WriteConfigValueStr(key, str); + return CC13XX_26XXConfig::WriteConfigValueStr(key, str); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) { - return CC13X2_26X2Config::WriteConfigValueStr(key, str, strLen); + return CC13XX_26XXConfig::WriteConfigValueStr(key, str, strLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { - return CC13X2_26X2Config::WriteConfigValueBin(key, data, dataLen); + return CC13XX_26XXConfig::WriteConfigValueBin(key, data, dataLen); } void ConfigurationManagerImpl::RunConfigUnitTest(void) { - CC13X2_26X2Config::RunConfigUnitTest(); + CC13XX_26XXConfig::RunConfigUnitTest(); } void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) @@ -208,7 +208,7 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) ChipLogProgress(DeviceLayer, "Performing factory reset"); - err = CC13X2_26X2Config::FactoryResetConfig(); + err = CC13XX_26XXConfig::FactoryResetConfig(); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "FactoryResetConfig() failed: %s", ErrorStr(err)); diff --git a/src/platform/cc13x2_26x2/ConnectivityManagerImpl.cpp b/src/platform/cc13xx_26xx/ConnectivityManagerImpl.cpp similarity index 100% rename from src/platform/cc13x2_26x2/ConnectivityManagerImpl.cpp rename to src/platform/cc13xx_26xx/ConnectivityManagerImpl.cpp diff --git a/src/platform/cc13x2_26x2/DiagnosticDataProviderImpl.cpp b/src/platform/cc13xx_26xx/DiagnosticDataProviderImpl.cpp similarity index 99% rename from src/platform/cc13x2_26x2/DiagnosticDataProviderImpl.cpp rename to src/platform/cc13xx_26xx/DiagnosticDataProviderImpl.cpp index 323ca605221ae4..07eefd23ca3b9a 100644 --- a/src/platform/cc13x2_26x2/DiagnosticDataProviderImpl.cpp +++ b/src/platform/cc13xx_26xx/DiagnosticDataProviderImpl.cpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include diff --git a/src/platform/cc13x2_26x2/DiagnosticDataProviderImpl.h b/src/platform/cc13xx_26xx/DiagnosticDataProviderImpl.h similarity index 100% rename from src/platform/cc13x2_26x2/DiagnosticDataProviderImpl.h rename to src/platform/cc13xx_26xx/DiagnosticDataProviderImpl.h diff --git a/src/platform/cc13x2_26x2/KeyValueStoreManagerImpl.cpp b/src/platform/cc13xx_26xx/KeyValueStoreManagerImpl.cpp similarity index 89% rename from src/platform/cc13x2_26x2/KeyValueStoreManagerImpl.cpp rename to src/platform/cc13xx_26xx/KeyValueStoreManagerImpl.cpp index 5227b55e5e65df..b92f80085da5aa 100644 --- a/src/platform/cc13x2_26x2/KeyValueStoreManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/KeyValueStoreManagerImpl.cpp @@ -28,7 +28,7 @@ #include -#include +#include namespace chip { namespace DeviceLayer { @@ -49,7 +49,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t VerifyOrReturnError(value, CHIP_ERROR_INVALID_ARGUMENT); } - err = CC13X2_26X2Config::ReadKVS(key, value, value_size, read_bytes_size, offset_bytes); + err = CC13XX_26XXConfig::ReadKVS(key, value, value_size, read_bytes_size, offset_bytes); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -62,12 +62,12 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { VerifyOrReturnError(key, CHIP_ERROR_INVALID_ARGUMENT); - return CC13X2_26X2Config::WriteKVS(key, value, value_size); + return CC13XX_26XXConfig::WriteKVS(key, value, value_size); } CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { - return CC13X2_26X2Config::ClearKVS(key); + return CC13XX_26XXConfig::ClearKVS(key); } } // namespace PersistedStorage diff --git a/src/platform/cc13x2_26x2/Logging.cpp b/src/platform/cc13xx_26xx/Logging.cpp similarity index 71% rename from src/platform/cc13x2_26x2/Logging.cpp rename to src/platform/cc13xx_26xx/Logging.cpp index 1fb240c2c10d44..b7ba49ba784dd8 100644 --- a/src/platform/cc13x2_26x2/Logging.cpp +++ b/src/platform/cc13xx_26xx/Logging.cpp @@ -11,31 +11,27 @@ #include "ti_drivers_config.h" -#include +#include #include -UART_Handle sDebugUartHandle; +UART2_Handle sDebugUartHandle; char sDebugUartBuffer[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; -#if MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED -extern "C" int cc13x2_26x2LogInit(void) +#if MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED +extern "C" int cc13xx_26xxLogInit(void) { - UART_Params uartParams; + UART2_Params uartParams; - UART_init(); - - UART_Params_init(&uartParams); + UART2_Params_init(&uartParams); // Most params can be default because we only send data, we don't receive uartParams.baudRate = 115200; - // unclear why the UART driver sticks in writing sometimes - uartParams.writeTimeout = 10000; // ticks - sDebugUartHandle = UART_open(CONFIG_UART_DEBUG, &uartParams); + sDebugUartHandle = UART2_open(CONFIG_UART_DEBUG, &uartParams); return 0; } -extern "C" void cc13x2_26x2VLog(const char * msg, va_list v) +extern "C" void cc13xx_26xxVLog(const char * msg, va_list v) { int ret; @@ -47,17 +43,17 @@ extern "C" void cc13x2_26x2VLog(const char * msg, va_list v) sDebugUartBuffer[len - 2] = '\r'; sDebugUartBuffer[len - 1] = '\n'; - UART_write(sDebugUartHandle, sDebugUartBuffer, len); + UART2_write(sDebugUartHandle, sDebugUartBuffer, len, NULL); } } #else /* log functins defined somewhere else */ -extern "C" int cc13x2_26x2LogInit(void); -extern "C" void cc13x2_26x2VLog(const char * msg, va_list v); +extern "C" int cc13xx_26xxLogInit(void); +extern "C" void cc13xx_26xxVLog(const char * msg, va_list v); -#endif // MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED +#endif // MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED namespace chip { namespace DeviceLayer { @@ -81,7 +77,7 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) (void) module; (void) category; - cc13x2_26x2VLog(msg, v); + cc13xx_26xxVLog(msg, v); chip::DeviceLayer::OnLogOutput(); } @@ -100,7 +96,7 @@ extern "C" void LwIPLog(const char * msg, ...) va_start(v, msg); - cc13x2_26x2VLog(msg, v); + cc13xx_26xxVLog(msg, v); chip::DeviceLayer::OnLogOutput(); va_end(v); @@ -110,13 +106,13 @@ extern "C" void LwIPLog(const char * msg, ...) /** * Platform log output function. */ -extern "C" void cc13x2_26x2Log(const char * msg, ...) +extern "C" void cc13xx_26xxLog(const char * msg, ...) { va_list v; va_start(v, msg); - cc13x2_26x2VLog(msg, v); + cc13xx_26xxVLog(msg, v); chip::DeviceLayer::OnLogOutput(); va_end(v); @@ -132,7 +128,7 @@ extern "C" void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const ch va_start(v, aFormat); - cc13x2_26x2VLog(aFormat, v); + cc13xx_26xxVLog(aFormat, v); chip::DeviceLayer::OnLogOutput(); va_end(v); diff --git a/src/platform/cc13x2_26x2/OTAImageProcessorImpl.cpp b/src/platform/cc13xx_26xx/OTAImageProcessorImpl.cpp similarity index 100% rename from src/platform/cc13x2_26x2/OTAImageProcessorImpl.cpp rename to src/platform/cc13xx_26xx/OTAImageProcessorImpl.cpp diff --git a/src/platform/cc13x2_26x2/OTAImageProcessorImpl.h b/src/platform/cc13xx_26xx/OTAImageProcessorImpl.h similarity index 100% rename from src/platform/cc13x2_26x2/OTAImageProcessorImpl.h rename to src/platform/cc13xx_26xx/OTAImageProcessorImpl.h diff --git a/src/platform/cc13x2_26x2/PlatformManagerImpl.cpp b/src/platform/cc13xx_26xx/PlatformManagerImpl.cpp similarity index 97% rename from src/platform/cc13x2_26x2/PlatformManagerImpl.cpp rename to src/platform/cc13xx_26xx/PlatformManagerImpl.cpp index be7a427b57c52a..2cd8c01ca47a0c 100644 --- a/src/platform/cc13x2_26x2/PlatformManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/PlatformManagerImpl.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include #include #include @@ -105,7 +105,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) CHIP_ERROR err; // Initialize the configuration system. - err = Internal::CC13X2_26X2Config::Init(); + err = Internal::CC13XX_26XXConfig::Init(); SuccessOrExit(err); // DMM Addition diff --git a/src/platform/cc13x2_26x2/Random.c b/src/platform/cc13xx_26xx/Random.c similarity index 100% rename from src/platform/cc13x2_26x2/Random.c rename to src/platform/cc13xx_26xx/Random.c diff --git a/src/platform/cc13x2_26x2/ThreadStackManagerImpl.cpp b/src/platform/cc13xx_26xx/ThreadStackManagerImpl.cpp similarity index 94% rename from src/platform/cc13x2_26x2/ThreadStackManagerImpl.cpp rename to src/platform/cc13xx_26xx/ThreadStackManagerImpl.cpp index c62fa61460f9fb..caffe8443b6bbd 100644 --- a/src/platform/cc13x2_26x2/ThreadStackManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/ThreadStackManagerImpl.cpp @@ -36,7 +36,7 @@ #include // platform folder in the TI SDK example application -#include +#include // DMM Includes #ifdef USE_DMM @@ -88,7 +88,10 @@ CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) #endif /* OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE != 0 */ // Initialize the OpenThread platform layer - otSysInit(0, NULL); + platformAlarmInit(); + platformAlarmMicroInit(); + platformRandomInit(); + platformRadioInit(); #ifdef USE_DMM // DMM Init @@ -119,6 +122,19 @@ void ThreadStackManagerImpl::_SendProcMessage(ThreadStackManagerImpl::procQueueM SignalThreadActivityPendingFromISR(); } +extern "C" void * otPlatCAlloc(size_t aNum, size_t aSize) +{ + return chip::Platform::MemoryCalloc(aNum, aSize); +} + +extern "C" void otPlatFree(void * aPtr) +{ + if (aPtr != nullptr) + { + chip::Platform::MemoryFree(aPtr); + } +} + void ThreadStackManagerImpl::_ProcMessage(otInstance * aInstance) { procQueueMsg procMsg; @@ -141,11 +157,6 @@ void ThreadStackManagerImpl::_ProcMessage(otInstance * aInstance) break; } - case procQueueCmd_random: { - platformRandomProcess(); - break; - } - case procQueueCmd_alarmu: { platformAlarmMicroProcess(aInstance); break; diff --git a/src/platform/cc13x2_26x2/BLEManagerImpl.h b/src/platform/cc13xx_26xx/cc13x2_26x2/BLEManagerImpl.h similarity index 99% rename from src/platform/cc13x2_26x2/BLEManagerImpl.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/BLEManagerImpl.h index d43ecddefba178..34c517ed1c166b 100644 --- a/src/platform/cc13x2_26x2/BLEManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/BLEManagerImpl.h @@ -19,7 +19,7 @@ /** * @file * Provides an implementation of the BLEManager object for the Texas - * Instruments cc13xx_cc26xx platform. + * Instruments CC13XX_26XX platform. */ #pragma once @@ -191,7 +191,7 @@ typedef struct } PasscodeData_t; /** - * Concrete implementation of the BLEManager singleton object for cc13x2_cc26x2. + * Concrete implementation of the BLEManager singleton object for CC13XX_26XX. */ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate @@ -349,7 +349,7 @@ inline BLEManager & BLEMgr(void) * Returns the platform-specific implementation of the BLEManager singleton object. * * Internal components can use this to gain access to features of the BLEManager - * that are specific to the cc13x2_cc26x2 platforms. + * that are specific to the CC13XX_26XX platforms. */ inline BLEManagerImpl & BLEMgrImpl(void) { diff --git a/src/platform/cc13x2_26x2/BUILD.gn b/src/platform/cc13xx_26xx/cc13x2_26x2/BUILD.gn similarity index 76% rename from src/platform/cc13x2_26x2/BUILD.gn rename to src/platform/cc13xx_26xx/cc13x2_26x2/BUILD.gn index 85d3fde0466553..133580e80169dc 100644 --- a/src/platform/cc13x2_26x2/BUILD.gn +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/BUILD.gn @@ -24,26 +24,25 @@ if (chip_enable_openthread) { static_library("cc13x2_26x2") { sources = [ - "../FreeRTOS/SystemTimeSupport.cpp", - "../SingletonConfigurationManager.cpp", + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../CC13XX_26XXConfig.cpp", + "../CC13XX_26XXConfig.h", + "../ConfigurationManagerImpl.cpp", + "../ConnectivityManagerImpl.cpp", + "../DiagnosticDataProviderImpl.cpp", + "../DiagnosticDataProviderImpl.h", + "../KeyValueStoreManagerImpl.cpp", + "../Logging.cpp", + "../PlatformManagerImpl.cpp", + "../Random.c", "BlePlatformConfig.h", - "CC13X2_26X2Config.cpp", - "CC13X2_26X2Config.h", - "CHIPDevicePlatformConfig.h", "CHIPDevicePlatformConfig.h", "CHIPDevicePlatformEvent.h", - "ConfigurationManagerImpl.cpp", - "ConnectivityManagerImpl.cpp", "ConnectivityManagerImpl.h", - "DiagnosticDataProviderImpl.cpp", - "DiagnosticDataProviderImpl.h", "InetPlatformConfig.h", - "KeyValueStoreManagerImpl.cpp", "KeyValueStoreManagerImpl.h", - "Logging.cpp", - "PlatformManagerImpl.cpp", "PlatformManagerImpl.h", - "Random.c", "SystemPlatformConfig.h", ] @@ -58,7 +57,7 @@ static_library("cc13x2_26x2") { if (chip_enable_ble) { sources += [ - "BLEManagerImpl.cpp", + "../BLEManagerImpl.cpp", "BLEManagerImpl.h", ] } @@ -68,8 +67,8 @@ static_library("cc13x2_26x2") { # this needs to be in the final link to place the data correctly # see ${chip_root}/third_party/ti_simplelink_sdk/ti_simplelink_executable.gni #"oad_image_header.c", - "OTAImageProcessorImpl.cpp", - "OTAImageProcessorImpl.h", + "../OTAImageProcessorImpl.cpp", + "../OTAImageProcessorImpl.h", ] } @@ -78,6 +77,7 @@ static_library("cc13x2_26x2") { import("//build_overrides/ti_simplelink_sdk.gni") import("${ti_simplelink_sdk_build_root}/ti_simplelink_board.gni") public_deps += [ + "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2", "${chip_root}/third_party/ti_simplelink_sdk:mbedtls", "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sdk", "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sysconfig", @@ -92,13 +92,13 @@ static_library("cc13x2_26x2") { } sources += [ - "../OpenThread/OpenThreadUtils.cpp", - "ThreadStackManagerImpl.cpp", + "../../OpenThread/OpenThreadUtils.cpp", + "../ThreadStackManagerImpl.cpp", "ThreadStackManagerImpl.h", ] if (chip_mdns == "platform") { - sources += [ "../OpenThread/DnssdImpl.cpp" ] + sources += [ "../../OpenThread/DnssdImpl.cpp" ] deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] } } diff --git a/src/platform/cc13x2_26x2/BlePlatformConfig.h b/src/platform/cc13xx_26xx/cc13x2_26x2/BlePlatformConfig.h similarity index 93% rename from src/platform/cc13x2_26x2/BlePlatformConfig.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/BlePlatformConfig.h index a4745eb8e95f3c..8924b62d9b33c6 100644 --- a/src/platform/cc13x2_26x2/BlePlatformConfig.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/BlePlatformConfig.h @@ -19,7 +19,7 @@ /** * @file * Platform-specific configuration overrides for the CHIP BLE - * Layer for the Texas Instruments CC1352 platform. + * Layer for the Texas Instruments CC13XX_26XX platform. * * NOTE: Empty because BLE is not enabled, but build defines this file * to be included by the build configuration. diff --git a/src/platform/cc13x2_26x2/CHIPDevicePlatformConfig.h b/src/platform/cc13xx_26xx/cc13x2_26x2/CHIPDevicePlatformConfig.h similarity index 96% rename from src/platform/cc13x2_26x2/CHIPDevicePlatformConfig.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/CHIPDevicePlatformConfig.h index cc2470e9c3a7b6..13a5e6900dbb1d 100644 --- a/src/platform/cc13x2_26x2/CHIPDevicePlatformConfig.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/CHIPDevicePlatformConfig.h @@ -19,7 +19,7 @@ /** * @file * Platform-specific configuration overrides for the chip Device Layer - * for the Texas Instruments CC2652R7 platform. + * for the Texas Instruments CC13XX_CC26XX platform. */ #pragma once diff --git a/src/platform/cc13x2_26x2/CHIPDevicePlatformEvent.h b/src/platform/cc13xx_26xx/cc13x2_26x2/CHIPDevicePlatformEvent.h similarity index 94% rename from src/platform/cc13x2_26x2/CHIPDevicePlatformEvent.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/CHIPDevicePlatformEvent.h index ea5b2f05b78324..f647b595d02990 100644 --- a/src/platform/cc13x2_26x2/CHIPDevicePlatformEvent.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/CHIPDevicePlatformEvent.h @@ -19,7 +19,7 @@ /** * @file * Defines platform-specific event types and data for the chip - * for the Texas Instruments CC1352 platform. + * for the Texas Instruments CC13XX_26XX platform. * * NOTE: currently a bare-bones implementation to allow for building. */ diff --git a/src/platform/cc13x2_26x2/CHIPPlatformConfig.h b/src/platform/cc13xx_26xx/cc13x2_26x2/CHIPPlatformConfig.h similarity index 100% rename from src/platform/cc13x2_26x2/CHIPPlatformConfig.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/CHIPPlatformConfig.h diff --git a/src/platform/cc13x2_26x2/ConfigurationManagerImpl.h b/src/platform/cc13xx_26xx/cc13x2_26x2/ConfigurationManagerImpl.h similarity index 97% rename from src/platform/cc13x2_26x2/ConfigurationManagerImpl.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/ConfigurationManagerImpl.h index 44cafee006ff55..17ec853af5e9e0 100644 --- a/src/platform/cc13x2_26x2/ConfigurationManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/ConfigurationManagerImpl.h @@ -24,7 +24,7 @@ #pragma once -#include +#include #include namespace chip { @@ -33,7 +33,7 @@ namespace DeviceLayer { /** * Concrete implementation of the ConfigurationManager singleton object for the CC13X2_26X2 platform. */ -class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl +class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl { public: // This returns an instance of this class. diff --git a/src/platform/cc13x2_26x2/ConnectivityManagerImpl.h b/src/platform/cc13xx_26xx/cc13x2_26x2/ConnectivityManagerImpl.h similarity index 97% rename from src/platform/cc13x2_26x2/ConnectivityManagerImpl.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/ConnectivityManagerImpl.h index 5abed2848f065f..44c0e764b391a7 100644 --- a/src/platform/cc13x2_26x2/ConnectivityManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/ConnectivityManagerImpl.h @@ -18,7 +18,7 @@ /** * @file * Platform-specific connectivity manager class for the Texas - * Instruments CC1352 platform. + * Instruments CC13XX_26XX platform. */ #pragma once @@ -45,7 +45,7 @@ namespace chip { namespace DeviceLayer { /** - * Concrete implementation of the ConnectivityManager singleton object for the CC13X2_26X2 platforms. + * Concrete implementation of the ConnectivityManager singleton object for the CC13XX_26XX platforms. */ class ConnectivityManagerImpl final : public ConnectivityManager, public Internal::GenericConnectivityManagerImpl, @@ -98,7 +98,7 @@ inline ConnectivityManager & ConnectivityMgr(void) * Returns the platform-specific implementation of the ConnectivityManager singleton object. * * chip applications can use this to gain access to features of the ConnectivityManager - * that are specific to the CC1352 platform + * that are specific to the platform */ inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) { diff --git a/src/platform/cc13x2_26x2/FreeRTOSConfig.h b/src/platform/cc13xx_26xx/cc13x2_26x2/FreeRTOSConfig.h similarity index 100% rename from src/platform/cc13x2_26x2/FreeRTOSConfig.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/FreeRTOSConfig.h diff --git a/src/platform/cc13x2_26x2/InetPlatformConfig.h b/src/platform/cc13xx_26xx/cc13x2_26x2/InetPlatformConfig.h similarity index 100% rename from src/platform/cc13x2_26x2/InetPlatformConfig.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/InetPlatformConfig.h diff --git a/src/platform/cc13x2_26x2/KeyValueStoreManagerImpl.h b/src/platform/cc13xx_26xx/cc13x2_26x2/KeyValueStoreManagerImpl.h similarity index 99% rename from src/platform/cc13x2_26x2/KeyValueStoreManagerImpl.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/KeyValueStoreManagerImpl.h index bd70c08df860b6..45396e4544b7aa 100644 --- a/src/platform/cc13x2_26x2/KeyValueStoreManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/KeyValueStoreManagerImpl.h @@ -18,7 +18,7 @@ /** * @file - * Platform-specific key value storage implementation for CC1352. + * Platform-specific key value storage implementation for CC13XX_26XX. */ #pragma once diff --git a/src/platform/cc13x2_26x2/PlatformManagerImpl.h b/src/platform/cc13xx_26xx/cc13x2_26x2/PlatformManagerImpl.h similarity index 97% rename from src/platform/cc13x2_26x2/PlatformManagerImpl.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/PlatformManagerImpl.h index 8275e861c4376e..0cf7ea893b6634 100644 --- a/src/platform/cc13x2_26x2/PlatformManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/PlatformManagerImpl.h @@ -30,7 +30,7 @@ namespace DeviceLayer { /** * Concrete implementation of the PlatformManager singleton object for the - * CC13X2_26X2 platform. + * CC13XX_26XX platform. */ class PlatformManagerImpl final : public PlatformManager, public Internal::GenericPlatformManagerImpl_FreeRTOS { @@ -84,7 +84,7 @@ inline PlatformManager & PlatformMgr(void) * singleton object. * * chip applications can use this to gain access to features of the - * PlatformManager that are specific to the CC1352 SoC. + * PlatformManager that are specific to the SoC. */ inline PlatformManagerImpl & PlatformMgrImpl(void) { diff --git a/src/platform/cc13x2_26x2/SystemPlatformConfig.h b/src/platform/cc13xx_26xx/cc13x2_26x2/SystemPlatformConfig.h similarity index 100% rename from src/platform/cc13x2_26x2/SystemPlatformConfig.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/SystemPlatformConfig.h diff --git a/src/platform/cc13x2_26x2/ThreadStackManagerImpl.h b/src/platform/cc13xx_26xx/cc13x2_26x2/ThreadStackManagerImpl.h similarity index 97% rename from src/platform/cc13x2_26x2/ThreadStackManagerImpl.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/ThreadStackManagerImpl.h index 80965d5c4469f7..c7377336a2f38f 100644 --- a/src/platform/cc13x2_26x2/ThreadStackManagerImpl.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/ThreadStackManagerImpl.h @@ -19,7 +19,7 @@ /** * @file * Provides an implementation of the ThreadStackManager object - * for the Texas Instruments CC1352 platform. + * for the Texas Instruments CC13XX_26XX platform. * * NOTE: currently a bare-bones implementation to allow for building. */ @@ -46,7 +46,7 @@ class ThreadStackManager; class ThreadStackManagerImpl; /** - * Concrete implementation of the ThreadStackManager singleton object for CC1352. + * Concrete implementation of the ThreadStackManager singleton object for CC13XX_26XX. */ class ThreadStackManagerImpl final : public ThreadStackManager, public Internal::GenericThreadStackManagerImpl_OpenThread_LwIP, @@ -78,7 +78,6 @@ class ThreadStackManagerImpl final : public ThreadStackManager, procQueueCmd_radio, procQueueCmd_tasklets, procQueueCmd_uart, - procQueueCmd_random, procQueueCmd_alarmu, }; @@ -132,7 +131,7 @@ inline ThreadStackManager & ThreadStackMgr(void) * Returns the platform-specific implementation of the ThreadStackManager singleton object. * * chip applications can use this to gain access to features of the ThreadStackManager - * that are specific to CC1352 SoC. + * that are specific to SoC. */ inline ThreadStackManagerImpl & ThreadStackMgrImpl(void) { diff --git a/src/platform/cc13x2_26x2/args.gni b/src/platform/cc13xx_26xx/cc13x2_26x2/args.gni similarity index 97% rename from src/platform/cc13x2_26x2/args.gni rename to src/platform/cc13xx_26xx/cc13x2_26x2/args.gni index 7963e911e3e648..4ff86939ff74a0 100644 --- a/src/platform/cc13x2_26x2/args.gni +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/args.gni @@ -26,7 +26,7 @@ openthread_external_mbedtls = mbedtls_target openthread_external_platform = "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk" -lwip_platform = "cc13x2_26x2" +lwip_platform = "cc13xx_26xx" chip_inet_config_enable_ipv4 = false diff --git a/src/platform/cc13x2_26x2/ble_user_config.c b/src/platform/cc13xx_26xx/cc13x2_26x2/ble_user_config.c similarity index 100% rename from src/platform/cc13x2_26x2/ble_user_config.c rename to src/platform/cc13xx_26xx/cc13x2_26x2/ble_user_config.c diff --git a/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos.lds b/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos.lds new file mode 100644 index 00000000000000..c5d4aa88e6f4bf --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos.lds @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2020, Texas Instruments Incorporated + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of Texas Instruments Incorporated nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * ======== CC26X2R1_LAUNCHXL_FREERTOS.lds ======== + * Default Linker script for the Texas Instruments CC26X2R1 + */ + + + FLASH_ROM_BUILD = 2; + FLASH_BASE = 0x00000000 ; + GPRAM_BASE = 0x11000000 ; + RAM_BASE = 0x20000000 ; + ROM_BASE = 0x10000000 ; + + FLASH_SIZE = 0x00058000 ; + GPRAM_SIZE = 0x00002000 ; + RAM_SIZE = 0x00014000 ; + ROM_SIZE = 0x00040000 ; + + RTOS_RAM_SIZE = 0x0000012C; + RESERVED_RAM_SIZE_ROM_1 = 0x00000B08; + RESERVED_RAM_SIZE_ROM_2 = 0x00000EB3; + + PAGE_SIZE = 0x2000; +RTOS_RAM_SIZE = 0x0000012C; +RESERVED_RAM_SIZE_ROM_2 = 0x00000EB3; + + + RESERVED_RAM_SIZE_AT_START = (RTOS_RAM_SIZE + RESERVED_RAM_SIZE_ROM_2); + RESERVED_RAM_SIZE_AT_END = 0; + + + RAM_START = (RAM_BASE + RESERVED_RAM_SIZE_AT_START); + + + RAM_END = (RAM_BASE + RAM_SIZE - RESERVED_RAM_SIZE_AT_END - 1); + + +/* For ROM 2 devices, the following section needs to be allocated and reserved */ + RTOS_RAM_START = RAM_BASE; + RTOS_RAM_END = (RAM_BASE + RTOS_RAM_SIZE - 1); + + FLASH_START = FLASH_BASE; + WORD_SIZE = 4; + + FLASH_MEM_ALIGN = WORD_SIZE; + + PAGE_MASK = 0xFFFFE000; + + NUM_RESERVED_FLASH_PAGES = 1; + RESERVED_FLASH_SIZE = (NUM_RESERVED_FLASH_PAGES * PAGE_SIZE); + + FLASH_END = (FLASH_BASE + FLASH_SIZE - RESERVED_FLASH_SIZE - 1); + + FLASH_LAST_PAGE_START = (FLASH_SIZE - PAGE_SIZE); + +/* +__STACK_TOP = __stack + __STACK_SIZE; + + +__UNUSED_SRAM_start__ = RAM_BASE; +__UNUSED_SRAM_end__ = RAM_BASE + RAM_SIZE; + +__UNUSED_FLASH_start__ = FLASH_BASE; +__UNUSED_FLASH_end__ = FLASH_BASE + FLASH_SIZE; +*/ + + +MEMORY +{ + FLASH (RX) : ORIGIN = FLASH_START, LENGTH = (FLASH_END - FLASH_START + 1) + /* + * Customer Configuration Area and Bootloader Backdoor configuration in + * flash, 40 bytes + */ + /* FLASH_CCFG (RX) : ORIGIN = FLASH_LAST_PAGE_START, LENGTH = PAGE_SIZE */ + FLASH_CCFG (RX) : ORIGIN = 0x00057fa8, LENGTH = 0x00000058 + + + RTOS_SRAM (RWX) : ORIGIN = RTOS_RAM_START, LENGTH = (RTOS_RAM_END - RTOS_RAM_START + 1) + SRAM (RWX) : ORIGIN = 0x20000000 + RESERVED_RAM_SIZE_ROM_2 + RTOS_RAM_SIZE, LENGTH = (RAM_END - RAM_START + 1) + /* GPRAM (RWX) : ORIGIN = 0x11000000, LENGTH = 0x00002000 */ +} + +REGION_ALIAS("REGION_TEXT", FLASH); +REGION_ALIAS("REGION_BSS", SRAM); +REGION_ALIAS("REGION_DATA", SRAM); +REGION_ALIAS("REGION_STACK", SRAM); +REGION_ALIAS("REGION_HEAP", SRAM); +REGION_ALIAS("REGION_ARM_EXIDX", FLASH); +REGION_ALIAS("REGION_ARM_EXTAB", FLASH); + +SECTIONS { + + PROVIDE (_intvecs_base_address = + DEFINED(_intvecs_base_address) ? _intvecs_base_address : 0x0); + + .resetVecs (_intvecs_base_address) : AT (_intvecs_base_address) { + KEEP (*(.resetVecs)) + } > REGION_TEXT + + PROVIDE (_vtable_base_address = + DEFINED(_vtable_base_address) ? _vtable_base_address : 0x20000000 + RESERVED_RAM_SIZE_ROM_2 + RTOS_RAM_SIZE); + + .ramVecs (_vtable_base_address) (NOLOAD) : { + KEEP (*(.ramVecs)) + } > REGION_DATA + + /* if a ROM-only symbol is present, then ROM is being used. + * Reserve memory for surgically placed module states. + */ + _rom_data_start = 0x20000100; + _rom_data_size = DEFINED(ROM_DATA_SIZE) ? 12 : DEFINED(ROM_DATA_SIZE_NO_OAD) ? 0x108 : 0; + + .rom_data_reserve (_rom_data_start): { + . += _rom_data_size; + } > REGION_DATA + + /* + * UDMACC26XX_CONFIG_BASE below must match UDMACC26XX_CONFIG_BASE defined + * by ti/drivers/dma/UDMACC26XX.h + * The user is allowed to change UDMACC26XX_CONFIG_BASE to move it away from + * the default address 0x2000_1800, but remember it must be 1024 bytes aligned. + */ + UDMACC26XX_CONFIG_BASE = 0x20001800; + + /* + * Define absolute addresses for the DMA channels. + * DMA channels must always be allocated at a fixed offset from the DMA base address. + * --------- DO NOT MODIFY ----------- + */ + DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x10); + DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x20); + DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x30); + DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x40); + DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x50); + DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x60); + DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x70); + DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x90); + DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x100); + DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x110); + + DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x210); + DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x220); + DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x230); + DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x240); + DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x250); + DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x260); + DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x270); + DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x290); + DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x300); + DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x310); + + /* + * Allocate UART0, UART1, SPI0, SPI1, ADC, and GPTimer0 DMA descriptors at absolute addresses. + * --------- DO NOT MODIFY ----------- + */ + UDMACC26XX_uart0RxControlTableEntry_is_placed = 0; + .dmaUart0RxControlTableEntry DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0TxControlTableEntry_is_placed = 0; + .dmaUart0TxControlTableEntry DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0RxControlTableEntry_is_placed = 0; + .dmaSpi0RxControlTableEntry DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0TxControlTableEntry_is_placed = 0; + .dmaSpi0TxControlTableEntry DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1RxControlTableEntry_is_placed = 0; + .dmaUart1RxControlTableEntry DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1TxControlTableEntry_is_placed = 0; + .dmaUart1TxControlTableEntry DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaADCPriControlTableEntry_is_placed = 0; + .dmaADCPriControlTableEntry DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaADCPriControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaGPT0APriControlTableEntry_is_placed = 0; + .dmaGPT0APriControlTableEntry DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaGPT0APriControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1RxControlTableEntry_is_placed = 0; + .dmaSpi1RxControlTableEntry DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1TxControlTableEntry_is_placed = 0; + .dmaSpi1TxControlTableEntry DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0RxAltControlTableEntry_is_placed = 0; + .dmaUart0RxAltControlTableEntry DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0TxAltControlTableEntry_is_placed = 0; + .dmaUart0TxAltControlTableEntry DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0RxAltControlTableEntry_is_placed = 0; + .dmaSpi0RxAltControlTableEntry DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0TxAltControlTableEntry_is_placed = 0; + .dmaSpi0TxAltControlTableEntry DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1RxAltControlTableEntry_is_placed = 0; + .dmaUart1RxAltControlTableEntry DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1TxAltControlTableEntry_is_placed = 0; + .dmaUart1TxAltControlTableEntry DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaADCAltControlTableEntry_is_placed = 0; + .dmaADCAltControlTableEntry DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaADCAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaGPT0AAltControlTableEntry_is_placed = 0; + .dmaGPT0AAltControlTableEntry DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaGPT0AAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1RxAltControlTableEntry_is_placed = 0; + .dmaSpi1RxAltControlTableEntry DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1TxAltControlTableEntry_is_placed = 0; + .dmaSpi1TxAltControlTableEntry DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1TxAltControlTableEntry)} > REGION_DATA + + + + /* if a ROM-only symbol is present, then ROM is being used. + * Reserve memory for surgically placed config constants. + */ + _rom_rodata_start = 0x2000; + _rom_rodata_size = DEFINED(ROM_RODATA_SIZE) ? 0 : DEFINED(ROM_RODATA_SIZE_NO_OAD) ? 0x330 : 0; + + .rom_rodata_reserve (_rom_rodata_start): { + . += _rom_rodata_size; + } > REGION_TEXT AT> REGION_TEXT + + .text : { + CREATE_OBJECT_SYMBOLS + *(.text) + *(.text.*) + . = ALIGN(0x4); + KEEP (*(.ctors)) + . = ALIGN(0x4); + KEEP (*(.dtors)) + . = ALIGN(0x4); + __init_array_start = .; + KEEP (*(.init_array*)) + __init_array_end = .; + *(.init) + *(.fini*) + } > REGION_TEXT AT> REGION_TEXT + + PROVIDE (__etext = .); + PROVIDE (_etext = .); + PROVIDE (etext = .); + + .rodata : { + *(.rodata) + *(.rodata.*) + *(.rodata_*) + } > REGION_TEXT AT> REGION_TEXT + + .data : ALIGN(4) { + __data_load__ = LOADADDR (.data); + __data_start__ = .; + *(.data) + *(.data.*) + . = ALIGN (4); + __data_end__ = .; + } > REGION_DATA AT> REGION_TEXT + + .ARM.exidx : { + __exidx_start = .; + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + __exidx_end = .; + } > REGION_ARM_EXIDX AT> REGION_ARM_EXIDX + + .ARM.extab : { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > REGION_ARM_EXTAB AT> REGION_ARM_EXTAB + + + + .nvs (0x52000) (NOLOAD) : AT (0x52000) ALIGN(0x2000) { + *(.nvs) + } > REGION_TEXT + + .ccfg : { + KEEP (*(.ccfg)) + } > FLASH_CCFG AT> FLASH_CCFG + + .bss : { + __bss_start__ = .; + *(.shbss) + *(.bss) + *(.bss.*) + *(COMMON) + . = ALIGN (4); + __bss_end__ = .; + } > REGION_BSS AT> REGION_BSS + + .heap : { + __heap_start__ = .; + end = __heap_start__; + _end = end; + __end = end; + KEEP(*(.heap)) + __heap_end__ = .; + __HeapLimit = __heap_end__; + } > REGION_HEAP AT> REGION_HEAP + + .stack (NOLOAD) : ALIGN(0x8) { + _stack = .; + __stack = .; + KEEP(*(.stack)). + += 0x800; + _stack_end = .; + __stack_end = .; + } > REGION_STACK AT> REGION_STACK + +} + +ENTRY(resetISR) diff --git a/src/platform/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds b/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds similarity index 97% rename from src/platform/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds rename to src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds index d470eea96a1888..7424c4c92c7f4c 100644 --- a/src/platform/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds @@ -22,6 +22,8 @@ */ STACKSIZE = 0x800; +RESERVED_RAM_SIZE_BLE_ROM = 0x00000FDF; + MEMORY { @@ -29,9 +31,9 @@ MEMORY /* FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x000affa8 */ /* FLASH_CCFG (RX) : ORIGIN = 0x000affa8, LENGTH = 0x00000058 */ FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x000ae000 - /* BLE ROM reserves RAM at the beginning of the ram image */ + /* BLE ROM reserves RAM at the beginning of the ram image, size RESERVED_RAM_SIZE_BLE_ROM */ /* SRAM (RWX) : ORIGIN = 0x20000000, LENGTH = 0x00024000 */ - SRAM (RWX) : ORIGIN = 0x20000fdf, LENGTH = 0x00023021 + SRAM (RWX) : ORIGIN = 0x20000FDF, LENGTH = 0x00023021 GPRAM (RWX) : ORIGIN = 0x11000000, LENGTH = 0x00002000 /* Explicitly placed off target for the storage of logging data. * The data placed here is NOT loaded onto the target device. @@ -69,9 +71,9 @@ SECTIONS { } > REGION_TEXT PROVIDE (_vtable_base_address = - DEFINED(_vtable_base_address) ? _vtable_base_address : 0x20000000); + DEFINED(_vtable_base_address) ? _vtable_base_address : 0x20000000 + RESERVED_RAM_SIZE_BLE_ROM); - .vtable (_vtable_base_address) (NOLOAD) : { + .ramVecs (_vtable_base_address) (NOLOAD) : { KEEP (*(.ramVecs)) } > REGION_DATA diff --git a/src/platform/cc13x2_26x2/crypto/aes_alt.c b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/aes_alt.c similarity index 100% rename from src/platform/cc13x2_26x2/crypto/aes_alt.c rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/aes_alt.c diff --git a/src/platform/cc13x2_26x2/crypto/aes_alt.h b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/aes_alt.h similarity index 100% rename from src/platform/cc13x2_26x2/crypto/aes_alt.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/aes_alt.h diff --git a/src/platform/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h similarity index 97% rename from src/platform/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h index af111ccb58a9d7..a005f6bf804905 100644 --- a/src/platform/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h +++ b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/cc13x2_26x2-mbedtls-config.h @@ -40,8 +40,8 @@ /* Enable Hardware Acceleration */ //#define MBEDTLS_AES_ALT -#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT -#define MBEDTLS_ECDH_GEN_PUBLIC_ALT +//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT +//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT #define MBEDTLS_ECDSA_SIGN_ALT #define MBEDTLS_ECDSA_VERIFY_ALT #define MBEDTLS_ENTROPY_HARDWARE_ALT diff --git a/src/platform/cc13x2_26x2/crypto/ecdh_alt.c b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecdh_alt.c similarity index 100% rename from src/platform/cc13x2_26x2/crypto/ecdh_alt.c rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecdh_alt.c diff --git a/src/platform/cc13x2_26x2/crypto/ecdsa_alt.c b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecdsa_alt.c old mode 100755 new mode 100644 similarity index 100% rename from src/platform/cc13x2_26x2/crypto/ecdsa_alt.c rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecdsa_alt.c diff --git a/src/platform/cc13x2_26x2/crypto/ecjpake_alt.c b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecjpake_alt.c similarity index 100% rename from src/platform/cc13x2_26x2/crypto/ecjpake_alt.c rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecjpake_alt.c diff --git a/src/platform/cc13x2_26x2/crypto/ecjpake_alt.h b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecjpake_alt.h similarity index 100% rename from src/platform/cc13x2_26x2/crypto/ecjpake_alt.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecjpake_alt.h diff --git a/src/platform/cc13x2_26x2/crypto/sha256_alt.c b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/sha256_alt.c similarity index 100% rename from src/platform/cc13x2_26x2/crypto/sha256_alt.c rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/sha256_alt.c diff --git a/src/platform/cc13x2_26x2/crypto/sha256_alt.h b/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/sha256_alt.h similarity index 100% rename from src/platform/cc13x2_26x2/crypto/sha256_alt.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/crypto/sha256_alt.h diff --git a/src/platform/cc13x2_26x2/openthread-core-cc13x2_26x2-config-check.h b/src/platform/cc13xx_26xx/cc13x2_26x2/openthread-core-cc13x2_26x2-config-check.h similarity index 100% rename from src/platform/cc13x2_26x2/openthread-core-cc13x2_26x2-config-check.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/openthread-core-cc13x2_26x2-config-check.h diff --git a/src/platform/cc13x2_26x2/openthread-core-cc13x2_26x2-config.h b/src/platform/cc13xx_26xx/cc13x2_26x2/openthread-core-cc13x2_26x2-config.h similarity index 100% rename from src/platform/cc13x2_26x2/openthread-core-cc13x2_26x2-config.h rename to src/platform/cc13xx_26xx/cc13x2_26x2/openthread-core-cc13x2_26x2-config.h diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h new file mode 100644 index 00000000000000..34c517ed1c166b --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/BLEManagerImpl.h @@ -0,0 +1,368 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * + * 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. + */ + +/** + * @file + * Provides an implementation of the BLEManager object for the Texas + * Instruments CC13XX_26XX platform. + */ + +#pragma once + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + +#include "FreeRTOS.h" +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif +#include +#include + +#include "hal_types.h" + +#include "ti_ble_config.h" +#include "ti_drivers_config.h" + +#ifdef __cplusplus +} +#endif + +#include "chipOBleProfile.h" + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +using namespace chip::Ble; + +// Internal Events for RTOS application +#define ICALL_EVT ICALL_MSG_EVENT_ID // Event_Id_31 +#define QUEUE_EVT UTIL_QUEUE_EVENT_ID // Event_Id_30 + +// Application events +#define BLEManagerIMPL_STATE_UPDATE_EVT (0) + +// 500ms interval +#define BLEMANAGERIMPL_ADV_INT_SLOW (800) +// 100ms interval (Default) +#define BLEMANAGERIMPL_ADV_INT_FAST (160) + +#define CHIPOBLE_ADV_SIZE_NO_DEVICE_ID_INFO (4) + +#define CHIPOBLE_SCANRES_SIZE_NO_NAME (6) + +#define CHIPOBLE_ADV_DATA_MAX_SIZE (GAP_DEVICE_NAME_LEN + CHIPOBLE_SCANRES_SIZE_NO_NAME) + +#define CHIPOBLE_DEVICE_DESC_LENGTH (4) + +// How often to read current current RPA (in ms) +#define READ_RPA_EVT_PERIOD 3000 + +// 15 Minute Advertisement CHIP Timeout period +#define ADV_TIMEOUT (900000) + +#define STATE_CHANGE_EVT 0 +#define CHAR_CHANGE_EVT 1 +#define CHIPOBLE_CHAR_CHANGE_EVT 2 +#define BLEManagerIMPL_CHIPOBLE_TX_IND_EVT 3 +#define ADV_EVT 4 +#define PAIR_STATE_EVT 5 +#define PASSCODE_EVT 6 +#define READ_RPA_EVT 7 +#define SEND_PARAM_UPDATE_EVT 8 +#define BLEManagerIMPL_CHIPOBLE_CLOSE_CONN_EVT 9 +#define CONN_EVT 10 + +// For storing the active connections +#define RSSI_TRACK_CHNLS 1 // Max possible channels can be GAP_BONDINGS_MAX +#define MAX_RSSI_STORE_DEPTH 5 +#define INVALID_HANDLE 0xFFFF +#define RSSI_2M_THRSHLD -30 +#define RSSI_1M_THRSHLD -40 +#define RSSI_S2_THRSHLD -50 +#define RSSI_S8_THRSHLD -60 +#define PHY_NONE LL_PHY_NONE // No PHY set +#define AUTO_PHY_UPDATE 0xFF +// Set initial values to maximum, RX is set to max. by default(251 octets, 2120us) +// Some brand smartphone is essentially needing 251/2120, so we set them here. +#define BLEMANAGER_SUGGESTED_PDU_SIZE 251 // default is 27 octets(TX) +#define BLEMANAGER_SUGGESTED_TX_TIME 2120 // default is 328us(TX) + +typedef struct +{ + uint8_t len; // data length + void * pData; // pointer to message +} CHIPoBLEIndEvt_t; + +typedef struct +{ + uint8_t paramId; // Parameter written + uint16_t len; // data length + uint16_t connHandle; // Active connection which received the write +} CHIPoBLEProfChgEvt_t; + +// App event passed from stack modules. This type is defined by the application +// since it can queue events to itself however it wants. +typedef struct +{ + uint8_t event; // event type + void * pData; // pointer to message +} QueuedEvt_t; + +// Container to store advertising event data when passing from advertising +// callback to app event. See the respective event in GapAdvScan_Event_IDs +// in gap_advertiser.h for the type that pBuf should be cast to. +typedef struct +{ + uint32_t event; + void * pBuf; +} GapAdvEventData_t; + +// Container to store information from clock expiration using a flexible array +// since data is not always needed +typedef struct +{ + uint8_t event; + uint8_t data[]; +} ClockEventData_t; + +// List element for parameter update and PHY command status lists +typedef struct +{ + List_Elem elem; + uint16_t connHandle; +} ConnHandleEntry_t; + +// Connected device information +typedef struct +{ + uint16_t connHandle; // Connection Handle + ClockP_Struct * pUpdateClock; // pointer to clock struct + int8_t rssiArr[MAX_RSSI_STORE_DEPTH]; + uint8_t rssiCntr; + int8_t rssiAvg; + bool phyCngRq; // Set to true if PHY change request is in progress + uint8_t currPhy; + uint8_t rqPhy; + uint8_t phyRqFailCnt; // PHY change request count + bool isAutoPHYEnable; // Flag to indicate auto phy change + uint16_t mtu; + ClockEventData_t * pParamUpdateEventData; +} ConnRec_t; + +// Container to store passcode data when passing from gapbondmgr callback +// to app event. See the pfnPairStateCB_t documentation from the gapbondmgr.h +// header file for more information on each parameter. +typedef struct +{ + uint8_t state; + uint16_t connHandle; + uint8_t status; +} PairStateData_t; + +// Container to store passcode data when passing from gapbondmgr callback +// to app event. See the pfnPasscodeCB_t documentation from the gapbondmgr.h +// header file for more information on each parameter. +typedef struct +{ + uint8_t deviceAddr[B_ADDR_LEN]; + uint16_t connHandle; + uint8_t uiInputs; + uint8_t uiOutputs; + uint32_t numComparison; +} PasscodeData_t; + +/** + * Concrete implementation of the BLEManager singleton object for CC13XX_26XX. + */ +class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate + +{ + // Allow the BLEManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend BLEManager; + +public: + // ===== Platform-specific members that may be accessed directly by the application. + +private: + // ===== Members that implement the BLEManager internal interface. + + CHIP_ERROR _Init(void); + void _Shutdown() {} + bool _IsAdvertisingEnabled(void); + CHIP_ERROR _SetAdvertisingEnabled(bool val); + bool _IsAdvertising(void); + CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode); + CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize); + CHIP_ERROR _SetDeviceName(const char * deviceName); + uint16_t _NumConnections(void); + void _OnPlatformEvent(const ChipDeviceEvent * event); + BleLayer * _GetBleLayer(void); + + // ===== Members that implement virtual methods on BlePlatformDelegate. + + bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + bool CloseConnection(BLE_CONNECTION_OBJECT conId) override; + uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override; + + bool SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + + // ===== Members that implement virtual methods on BleApplicationDelegate. + + void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; + + const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, + 0x9F, 0x9D, 0x11 } }; + const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, + 0x9F, 0x9D, 0x12 } }; + + friend BLEManager & BLEMgr(void); + friend BLEManagerImpl & BLEMgrImpl(void); + + static BLEManagerImpl sInstance; + + /* BLE stack task handle */ + static TaskHandle_t sBleTaskHndl; + // Entity ID globally used to check for source and/or destination of messages + static ICall_EntityID sSelfEntity; + + // Event globally used to post local events and pend on system and + // local events. + static ICall_SyncHandle sSyncEvent; + static QueueHandle_t sEventHandlerMsgQueueID; + static chipOBleProfileCBs_t CHIPoBLEProfile_CBs; + static gapBondCBs_t BLEMgr_BondMgrCBs; + + enum class Flags : uint16_t + { + kAdvertisingEnabled = 0x0001, /* App enabled CHIPoBLE advertising */ + kFastAdvertisingEnabled = 0x0002, /* App enabled Fash CHIPoBLE advertising */ + kAdvertising = 0x0004, /* TI BLE stack actively advertising */ + kBLEStackInitialized = 0x0008, /* TI BLE Stack GAP/GATT Intilization complete */ + kBLEStackAdvInitialized = 0x0010, /* TI BLE Stack Advertisement Intilization complete */ + kBLEStackGATTNameUpdate = 0x0020, /* Trigger TI BLE Stack name update, must be performed prior to adv start */ + kBLEStackGATTNameSet = 0x0040, /* Device name has been set externally*/ + kAdvertisingRefreshNeeded = 0x0080, /* Advertising settings changed and it should be restarted */ + + }; + + BitFlags mFlags; + CHIPoBLEServiceMode mServiceMode; + char mDeviceName[GAP_DEVICE_NAME_LEN]; + + ConnRec_t connList[MAX_NUM_BLE_CONNS]; + // List to store connection handles for queued param updates + List_List paramUpdateList; + + // Advertising handles + uint8_t advHandleLegacy; + // Address mode + GAP_Addr_Modes_t addrMode = DEFAULT_ADDRESS_MODE; + // Current Random Private Address + uint8_t rpa[B_ADDR_LEN] = { 0 }; + + uint8_t mAdvDatachipOBle[CHIPOBLE_ADV_DATA_MAX_SIZE]; + uint8_t mScanResDatachipOBle[CHIPOBLE_ADV_DATA_MAX_SIZE]; + + ClockP_Struct clkRpaRead; + ClockP_Struct clkAdvTimeout; + // Memory to pass RPA read event ID to clock handler + ClockEventData_t argRpaRead = { .event = READ_RPA_EVT }; + + // ===== Private BLE Stack Helper functions. + void ConfigureAdvertisements(void); + void EventHandler_init(void); + void InitPHYRSSIArray(void); + CHIP_ERROR CreateEventHandler(void); + uint8_t ProcessStackEvent(ICall_Hdr * pMsg); + void ProcessEvtHdrMsg(QueuedEvt_t * pMsg); + void ProcessGapMessage(gapEventHdr_t * pMsg); + uint8_t ProcessGATTMsg(gattMsgEvent_t * pMsg); + void ProcessAdvEvent(GapAdvEventData_t * pEventData); + CHIP_ERROR ProcessParamUpdate(uint16_t connHandle); + status_t EnqueueEvtHdrMsg(uint8_t event, void * pData); + uint8_t AddBLEConn(uint16_t connHandle); + uint8_t RemoveBLEConn(uint16_t connHandle); + uint8_t GetBLEConnIndex(uint16_t connHandle) const; + uint8_t ClearBLEConnListEntry(uint16_t connHandle); + void ClearPendingBLEParamUpdate(uint16_t connHandle); + void UpdateBLERPA(void); + + static void HandleIncomingBleConnection(Ble::BLEEndPoint * bleEP); + + /* Static helper function */ + static void EventHandler(void * arg); + static CHIP_ERROR DriveBLEState(void); + + /* Declared static to acquire function ptr */ + static void advCallback(uint32_t event, void * pBuf, uintptr_t arg); + static void ClockHandler(uintptr_t arg); + static void AdvTimeoutHandler(uintptr_t arg); + static void FastAdvTimeoutHandler(uintptr_t arg); + static void CHIPoBLEProfile_charValueChangeCB(uint8_t paramId, uint16_t len, uint16_t connHandle); + static void PasscodeCb(uint8_t * pDeviceAddr, uint16_t connHandle, uint8_t uiInputs, uint8_t uiOutputs, uint32_t numComparison); + static void PairStateCb(uint16_t connHandle, uint8_t state, uint8_t status); + static void AssertHandler(uint8 assertCause, uint8 assertSubcause); +}; + +/** + * Returns a reference to the public interface of the BLEManager singleton object. + * + * Internal components should use this to access features of the BLEManager object + * that are common to all platforms. + */ +inline BLEManager & BLEMgr(void) +{ + return BLEManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the BLEManager singleton object. + * + * Internal components can use this to gain access to features of the BLEManager + * that are specific to the CC13XX_26XX platforms. + */ +inline BLEManagerImpl & BLEMgrImpl(void) +{ + return BLEManagerImpl::sInstance; +} + +inline BleLayer * BLEManagerImpl::_GetBleLayer() +{ + return this; +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip + +#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/BUILD.gn b/src/platform/cc13xx_26xx/cc13x4_26x4/BUILD.gn new file mode 100644 index 00000000000000..8c2cac58e4abd0 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/BUILD.gn @@ -0,0 +1,105 @@ +# Copyright (c) 2021 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/chip.gni") + +import("${chip_root}/src/platform/device.gni") + +assert(chip_device_platform == "cc13x4_26x4") + +if (chip_enable_openthread) { + import("//build_overrides/openthread.gni") +} + +static_library("cc13x4_26x4") { + sources = [ + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../CC13XX_26XXConfig.cpp", + "../CC13XX_26XXConfig.h", + "../ConfigurationManagerImpl.cpp", + "../ConnectivityManagerImpl.cpp", + "../DiagnosticDataProviderImpl.cpp", + "../DiagnosticDataProviderImpl.h", + "../KeyValueStoreManagerImpl.cpp", + "../Logging.cpp", + "../PlatformManagerImpl.cpp", + "../Random.c", + "BlePlatformConfig.h", + "CHIPDevicePlatformConfig.h", + "CHIPDevicePlatformEvent.h", + "ConnectivityManagerImpl.h", + "InetPlatformConfig.h", + "KeyValueStoreManagerImpl.h", + "PlatformManagerImpl.h", + "SystemPlatformConfig.h", + ] + + deps = [] + + public_deps = [ + "${chip_root}/src/crypto", + "${chip_root}/src/platform:platform_base", + ] + public_configs = + [ "${chip_root}/src/lib/address_resolve:default_address_resolve_config" ] + + if (chip_enable_ble) { + sources += [ + "../BLEManagerImpl.cpp", + "BLEManagerImpl.h", + ] + } + + if (chip_enable_ota_requestor) { + sources += [ + # this needs to be in the final link to place the data correctly + # see ${chip_root}/third_party/ti_simplelink_sdk/ti_simplelink_executable.gni + #"oad_image_header.c", + "../OTAImageProcessorImpl.cpp", + "../OTAImageProcessorImpl.h", + ] + } + + if (chip_enable_openthread) { + # needed for MTD/FTD + import("//build_overrides/ti_simplelink_sdk.gni") + import("${ti_simplelink_sdk_build_root}/ti_simplelink_board.gni") + public_deps += [ + "${chip_root}/third_party/openthread/platforms/cc13x4_26x4:libopenthread-cc13x4_cc26x4", + "${chip_root}/third_party/ti_simplelink_sdk:mbedtls", + "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sdk", + "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sysconfig", + ] + + if (chip_openthread_ftd) { + public_deps += + [ "${chip_root}/third_party/openthread/repo:libopenthread-ftd" ] + } else { + public_deps += + [ "${chip_root}/third_party/openthread/repo:libopenthread-mtd" ] + } + + sources += [ + "../../OpenThread/OpenThreadUtils.cpp", + "../ThreadStackManagerImpl.cpp", + "ThreadStackManagerImpl.h", + ] + + if (chip_mdns == "platform") { + sources += [ "../../OpenThread/DnssdImpl.cpp" ] + deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] + } + } +} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/OpenThreadConfig.h b/src/platform/cc13xx_26xx/cc13x4_26x4/BlePlatformConfig.h similarity index 72% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/OpenThreadConfig.h rename to src/platform/cc13xx_26xx/cc13x4_26x4/BlePlatformConfig.h index 30f5633cc3bc7f..db305a7b4786ae 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/OpenThreadConfig.h +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/BlePlatformConfig.h @@ -1,8 +1,6 @@ /* * * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +17,11 @@ /** * @file - * Overrides to default OpenThread configuration. + * Platform-specific configuration overrides for the CHIP BLE + * Layer for the Texas Instruments CC13XX_26XX platform. * + * NOTE: Empty because BLE is not enabled, but build defines this file + * to be included by the build configuration. */ #pragma once - -// Use the TI-supplied default platform configuration for remainder -#include "openthread-core-cc13x2_26x2-config.h" diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformConfig.h b/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformConfig.h new file mode 100644 index 00000000000000..72cc68906026b5 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformConfig.h @@ -0,0 +1,55 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Platform-specific configuration overrides for the chip Device Layer + * for the Texas Instruments CC13XX_CC26XX platform. + */ + +#pragma once + +// ==================== Platform Adaptations ==================== + +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0 +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 + +// ========== Platform-specific Configuration ========= + +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 +#define CHIP_DEVICE_CONFIG_ENABLE_TUNNEL_TELEMETRY 0 + +// ========== CHIP Platform Configuration ========= + +#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (8192) + +#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (7168) + +#define BLEMANAGER_EVENT_HANDLER_STACK_SIZE (924) +#define BLEMANAGER_EVENT_HANDLER_PRIORITY (2) + +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 + +// Per 5.2.5.2. Commencement Section of CHIP spec, BLE advertisement is +// disabled for Locks and Barrier Access Devices. +#define CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART 0 +#define CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART 0 + +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 1 diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformEvent.h b/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformEvent.h new file mode 100644 index 00000000000000..0cb1aab8301984 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPDevicePlatformEvent.h @@ -0,0 +1,41 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Defines platform-specific event types and data for the chip + * for the Texas Instruments CC13XX_26XX platform. + * + * NOTE: currently a bare-bones implementation to allow for building. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Represents platform-specific event information + */ +struct ChipDevicePlatformEvent final +{ +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPPlatformConfig.h b/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPPlatformConfig.h new file mode 100644 index 00000000000000..70d524af217635 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/CHIPPlatformConfig.h @@ -0,0 +1,69 @@ +/* + * + * Copyright (c) 2020-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. + */ + +/** + * @file + * Platform-specific configuration overrides for CHIP on + * the Texas Instruments CC1352 platform. + * + * NOTE: currently a bare-bones implementation to allow for building. + */ + +#pragma once + +#include + +// ==================== General Platform Adaptations ==================== + +#define CHIP_CONFIG_ABORT() abort() + +#define CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE uint16_t +#define CHIP_CONFIG_PERSISTED_STORAGE_ENC_MSG_CNTR_ID 1 +#define CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH 2 + +#define CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY 0x01 + +// ==================== Security Adaptations ==================== + +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE (sizeof(unsigned int) * 76) + +// ==================== General Configuration Overrides ==================== + +#ifndef CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS +#define CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS 8 +#endif // CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS + +#ifndef CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS +#define CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS 8 +#endif // CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS + +#ifndef CHIP_LOG_FILTERING +#define CHIP_LOG_FILTERING 0 +#endif // CHIP_LOG_FILTERING + +#ifndef CHIP_CONFIG_MAX_INTERFACES +#define CHIP_CONFIG_MAX_INTERFACES 4 +#endif // CHIP_CONFIG_MAX_INTERFACES + +#ifndef CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS +#define CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS 4 +#endif // CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS + +// Limit the number of device admins to ensure enough ressources for handling them +#ifndef CHIP_CONFIG_MAX_FABRICS +#define CHIP_CONFIG_MAX_FABRICS 5 +#endif diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/ConfigurationManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/ConfigurationManagerImpl.h new file mode 100644 index 00000000000000..b16a6269818563 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/ConfigurationManagerImpl.h @@ -0,0 +1,91 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Provides an implementation of the ConfigurationManager object + * for the Texas Instruments CC1352 platform. + */ + +#pragma once + +#include +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Concrete implementation of the ConfigurationManager singleton object for the CC13X2_26X2 platform. + */ +class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl +{ +public: + // This returns an instance of this class. + static ConfigurationManagerImpl & GetDefaultInstance(); + + CHIP_ERROR GetRebootCount(uint32_t & rebootCount); + CHIP_ERROR IncreaseBootCount(void); + CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours); + CHIP_ERROR StoreTotalOperationalHours(uint32_t totalOperationalHours); + +private: + // ===== Members that implement the ConfigurationManager public interface. + + CHIP_ERROR Init(void) override; + CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override; + bool CanFactoryReset(void) override; + void InitiateFactoryReset(void) override; + CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) override; + CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) override; + + // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. + + // ===== Members that implement the GenericConfigurationManagerImpl protected interface. + CHIP_ERROR ReadConfigValue(Key key, bool & val) override; + CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override; + CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) override; + CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) override; + CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) override; + CHIP_ERROR WriteConfigValue(Key key, bool val) override; + CHIP_ERROR WriteConfigValue(Key key, uint32_t val) override; + CHIP_ERROR WriteConfigValue(Key key, uint64_t val) override; + CHIP_ERROR WriteConfigValueStr(Key key, const char * str) override; + CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen) override; + CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) override; + void RunConfigUnitTest(void) override; + + // ===== Private members reserved for use by this class only. + + static void DoFactoryReset(intptr_t arg); +}; + +inline CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +/** + * Returns the platform-specific implementation of the ConfigurationManager object. + * + * Applications can use this to gain access to features of the ConfigurationManager + * that are specific to the selected platform. + */ +ConfigurationManager & ConfigurationMgrImpl(); + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/ConnectivityManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/ConnectivityManagerImpl.h new file mode 100644 index 00000000000000..517b2552d90281 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/ConnectivityManagerImpl.h @@ -0,0 +1,108 @@ +/* + * + * Copyright (c) 2020 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. + */ +/** + * @file + * Platform-specific connectivity manager class for the Texas + * Instruments CC13XX_26XX platform. + */ + +#pragma once + +#include +#include +#include +#if INET_CONFIG_ENABLE_TCP_ENDPOINT +#include +#endif +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include +#else +#include +#endif +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#else +#include +#endif +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Concrete implementation of the ConnectivityManager singleton object for the CC13XX_26XX platforms. + */ +class ConnectivityManagerImpl final : public ConnectivityManager, + public Internal::GenericConnectivityManagerImpl, + public Internal::GenericConnectivityManagerImpl_UDP, +#if INET_CONFIG_ENABLE_TCP_ENDPOINT + public Internal::GenericConnectivityManagerImpl_TCP, +#endif +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + public Internal::GenericConnectivityManagerImpl_BLE, +#else + public Internal::GenericConnectivityManagerImpl_NoBLE, +#endif +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + public Internal::GenericConnectivityManagerImpl_Thread, +#else + public Internal::GenericConnectivityManagerImpl_NoThread, +#endif + public Internal::GenericConnectivityManagerImpl_NoWiFi +{ + // Allow the ConnectivityManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend class ConnectivityManager; + +private: + // ===== Members that implement the ConnectivityManager abstract interface. + + CHIP_ERROR _Init(void); + void _OnPlatformEvent(const ChipDeviceEvent * event); + + // ===== Members for internal use by the following friends. + + friend ConnectivityManager & ConnectivityMgr(void); + friend ConnectivityManagerImpl & ConnectivityMgrImpl(void); + + static ConnectivityManagerImpl sInstance; +}; + +/** + * Returns the public interface of the ConnectivityManager singleton object. + * + * chip applications should use this to access features of the ConnectivityManager object + * that are common to all platforms. + */ +inline ConnectivityManager & ConnectivityMgr(void) +{ + return ConnectivityManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the ConnectivityManager singleton object. + * + * chip applications can use this to gain access to features of the ConnectivityManager + * that are specific to the platform + */ +inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) +{ + return ConnectivityManagerImpl::sInstance; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/FreeRTOSConfig.h b/src/platform/cc13xx_26xx/cc13x4_26x4/FreeRTOSConfig.h new file mode 100644 index 00000000000000..a3e2ae6e1baf78 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/FreeRTOSConfig.h @@ -0,0 +1,249 @@ +/* + * FreeRTOS Kernel V10.0.0 + * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. If you wish to use our + * Amazon FreeRTOS name, please do so in a fair use way that does not cause + * confusion. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/****************************************************************************** + See http://www.freertos.org/a00110.html for an explanation of the + definitions contained in this file. +******************************************************************************/ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * http://www.freertos.org/a00110.html + *----------------------------------------------------------*/ + +/* These values are generated by SysConfig */ + +/* General options */ +#define configCPU_CLOCK_HZ ((unsigned long) (48000000)) +/* FreeRTOS heap size is 0 because currently "bget" heap is the + only heap available, for both FreeRTOS and application */ +#define configTOTAL_HEAP_SIZE ((size_t)(0)) +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 + +/* Stack sizes, all in words */ +#define configMINIMAL_STACK_SIZE ((unsigned short) (1024)) +#define configPOSIX_STACK_SIZE ((unsigned short) (1024)) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (6) +#define configTIMER_QUEUE_LENGTH (20) +#define configTIMER_TASK_STACK_DEPTH (configMINIMAL_STACK_SIZE * 2) +#define configIDLE_TASK_STACK_DEPTH (configMINIMAL_STACK_SIZE * 2) + +/* TrustZone/PSA settings */ +/* We do not set ENABLE_TRUSTZONE, as this is only for Secure Side function call support */ +#define configENABLE_TRUSTZONE 0 +#define configRUN_FREERTOS_SECURE_ONLY 1 + +/* + * The ISR stack will be initialized in the startup__.c file + * to 0xa5a5a5a5. The stack peak can then be displayed in Runtime Object View. + */ +#define configENABLE_ISR_STACK_INIT 1 +/* Enable debugging features in the UI to use the queue registry or ROV features */ +#define configQUEUE_REGISTRY_SIZE 0 + +#define configASSERT(x) \ + if ((x) == 0) \ + { \ + taskDISABLE_INTERRUPTS(); \ + for (;;) \ + ; \ + } + +/* Modifying the options below is not permitted or currently unsupported */ + +/* ARM-v8m specific settings: floating point unit is enabled, memory protection unit is disabled */ +#define configENABLE_FPU 1 +#define configENABLE_MPU 0 + +/* The CM33 port requires an additional stack size definition */ +#define configMINIMAL_SECURE_STACK_SIZE configMINIMAL_STACK_SIZE + +/* Constants related to the behaviour or the scheduler. */ +#define configTICK_RATE_HZ ((TickType_t) 100000) +#define configUSE_PREEMPTION 1 +#define configUSE_TIME_SLICING 0 +#define configMAX_PRIORITIES (10UL) +#define configIDLE_SHOULD_YIELD 0 +#define configUSE_16_BIT_TICKS 0 /* Only for 8 and 16-bit hardware. */ + +/* Constants that describe the hardware and memory usage. */ +#define configMAX_TASK_NAME_LEN (12) +#define configRECORD_STACK_HIGH_ADDRESS 1 + +/* Required by TI driver implementations */ +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configAPPLICATION_ALLOCATED_HEAP 1 + +/* Constants that build features in or out. */ +#define configUSE_MUTEXES 1 +#define configUSE_TICKLESS_IDLE 1 +#define configUSE_APPLICATION_TASK_TAG 1 /* Needed by POSIX/pthread */ +#define configUSE_CO_ROUTINES 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_QUEUE_SETS 0 +#define configUSE_TASK_NOTIFICATIONS 1 + +/* Constants that define which hook (callback) functions should be used. */ +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configUSE_MALLOC_FAILED_HOOK 0 + +/* Constants provided for debugging and optimisation assistance. */ +#define configENABLE_BACKWARD_COMPATIBILITY 1 + +#if defined(__TI_COMPILER_VERSION__) || defined(__ti_version__) +#include +#define traceTASK_DELETE(pxTCB) PTLS_taskDeleteHook(pxTCB) +#elif defined(__IAR_SYSTEMS_ICC__) +#ifndef __IAR_SYSTEMS_ASM__ +#include +#define traceTASK_DELETE(pxTCB) Mtx_taskDeleteHook(pxTCB) +#endif +#endif + +/* + * Enable thread local storage + * + * Assign TLS array index ownership here to avoid collisions. + * TLS storage is needed to implement thread-safe errno with + * TI and IAR compilers. With GNU compiler, we enable newlib. + */ +#if defined(__TI_COMPILER_VERSION__) || defined(__ti_version__) || defined(__IAR_SYSTEMS_ICC__) + +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 2 + +#if defined(__TI_COMPILER_VERSION__) || defined(__ti_version__) +#define PTLS_TLS_INDEX 0 /* ti.posix.freertos.PTLS */ +#elif defined(__IAR_SYSTEMS_ICC__) +#define MTX_TLS_INDEX 0 /* ti.posix.freertos.Mtx */ +#endif + +#define NDK_TLS_INDEX 1 /* Reserve an index for NDK TLS */ + +#elif defined(__GNUC__) + +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 1 + +#define NDK_TLS_INDEX 0 /* Reserve an index for NDK TLS */ + +/* note: system locks required by newlib are not implemented */ +#define configUSE_NEWLIB_REENTRANT 1 +#endif + +/* + * Set the following definitions to 1 to include the API function, or zero + * to exclude the API function. NOTE: Setting an INCLUDE_ parameter to 0 is + * only necessary if the linker does not automatically remove functions that + * are not referenced anyway. + */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 0 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 0 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTaskResumeFromISR 0 +#define INCLUDE_xTaskGetCurrentTaskHandle 1 +#define INCLUDE_xTaskGetSchedulerState 1 +#define INCLUDE_xSemaphoreGetMutexHolder 0 +#define INCLUDE_xTimerPendFunctionCall 0 + +/* Cortex-M3/4 interrupt priority configuration follows...................... */ + +/* Use the system definition, if there is one. */ +#ifdef __NVIC_PRIO_BITS +#define configPRIO_BITS __NVIC_PRIO_BITS +#else +#define configPRIO_BITS 3 /* 8 priority levels */ +#endif + +/* + * The lowest interrupt priority that can be used in a call to a "set priority" + * function. + */ +#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x07 + +/* + * The highest interrupt priority that can be used by any interrupt service + * routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT + * CALL INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A + * HIGHER PRIORITY THAN THIS! (higher priorities are lower numeric values. + */ +#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 1 + +/* + * Interrupt priorities used by the kernel port layer itself. These are generic + * to all Cortex-M ports, and do not rely on any particular library functions. + */ +#define configKERNEL_INTERRUPT_PRIORITY (configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) + +/* + * !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! + * See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. + * + * Priority 1 (shifted 5 since only the top 3 bits are implemented). + * Priority 1 is the second highest priority. + * Priority 0 is the highest priority. + */ +#define configMAX_SYSCALL_INTERRUPT_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) + +/* + * The trace facility is turned on to make some functions available for use in + * CLI commands. + */ +#define configUSE_TRACE_FACILITY 1 + +/* + * Runtime Object View is a Texas Instrument host tool that helps visualize + * the application. When enabled, the ISR stack will be initialized in the + * startup__.c file to 0xa5a5a5a5. The stack peak can then + * be displayed in Runtime Object View. + */ +#define configENABLE_ISR_STACK_INIT 1 +#endif /* FREERTOS_CONFIG_H */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/InetPlatformConfig.h b/src/platform/cc13xx_26xx/cc13x4_26x4/InetPlatformConfig.h new file mode 100644 index 00000000000000..a38d274ab1b62e --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/InetPlatformConfig.h @@ -0,0 +1,34 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#pragma once + +// ==================== Platform Adaptations ==================== + +#ifndef INET_CONFIG_ENABLE_IPV4 +#error Inet IPv4 configuration should be configured at build generation time +#endif + +// ========== Platform-specific Configuration Overrides ========= + +#ifndef INET_CONFIG_NUM_TCP_ENDPOINTS +#define INET_CONFIG_NUM_TCP_ENDPOINTS 4 +#endif // INET_CONFIG_NUM_TCP_ENDPOINTS + +#ifndef INET_CONFIG_NUM_UDP_ENDPOINTS +#define INET_CONFIG_NUM_UDP_ENDPOINTS 4 +#endif // INET_CONFIG_NUM_UDP_ENDPOINTS diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/KeyValueStoreManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/KeyValueStoreManagerImpl.h new file mode 100644 index 00000000000000..45396e4544b7aa --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/KeyValueStoreManagerImpl.h @@ -0,0 +1,75 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * 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. + */ + +/** + * @file + * Platform-specific key value storage implementation for CC13XX_26XX. + */ + +#pragma once + +namespace chip { +namespace DeviceLayer { +namespace PersistedStorage { + +class KeyValueStoreManagerImpl final : public KeyValueStoreManager +{ + // Allow the KeyValueStoreManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend class KeyValueStoreManager; + +public: + CHIP_ERROR _Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size = nullptr, size_t offset = 0) const; + + CHIP_ERROR _Delete(const char * key); + + CHIP_ERROR _Put(const char * key, const void * value, size_t value_size); + +private: + // ===== Members for internal use by the following friends. + friend KeyValueStoreManager & KeyValueStoreMgr(); + friend KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(); + + static KeyValueStoreManagerImpl sInstance; +}; + +/** + * Returns the public interface of the KeyValueStoreManager singleton object. + * + * Chip applications should use this to access features of the KeyValueStoreManager object + * that are common to all platforms. + */ +inline KeyValueStoreManager & KeyValueStoreMgr(void) +{ + return KeyValueStoreManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the KeyValueStoreManager singleton object. + * + * Chip applications can use this to gain access to features of the KeyValueStoreManager + * that are specific to the platform. + */ +inline KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(void) +{ + return KeyValueStoreManagerImpl::sInstance; +} + +} // namespace PersistedStorage +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/PlatformManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/PlatformManagerImpl.h new file mode 100644 index 00000000000000..3e6851ec24eeac --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/PlatformManagerImpl.h @@ -0,0 +1,94 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Provides an implementation of the PlatformManager object. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Concrete implementation of the PlatformManager singleton object for the + * CC13XX_26XX platform. + */ +class PlatformManagerImpl final : public PlatformManager, public Internal::GenericPlatformManagerImpl_FreeRTOS +{ + // Allow the PlatformManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend PlatformManager; + + // Allow the generic implementation base class to call helper methods on + // this class. +#ifndef DOXYGEN_SHOULD_SKIP_THIS + friend Internal::GenericPlatformManagerImpl_FreeRTOS; +#endif + +public: + // ===== Platform-specific members that may be accessed directly by the application. + + System::Clock::Timestamp GetStartTime() { return mStartTime; } + +private: + // ===== Methods that implement the PlatformManager abstract interface. + + CHIP_ERROR _InitChipStack(void); + void _Shutdown(void); + + // ===== Members for internal use by the following friends. + + friend PlatformManager & PlatformMgr(void); + friend PlatformManagerImpl & PlatformMgrImpl(void); + friend class Internal::BLEManagerImpl; + + System::Clock::Timestamp mStartTime = System::Clock::kZero; + + static PlatformManagerImpl sInstance; + + using Internal::GenericPlatformManagerImpl_FreeRTOS::PostEventFromISR; +}; + +/** + * Returns the public interface of the PlatformManager singleton object. + * + * chip applications should use this to access features of the PlatformManager + * object that are common to all platforms. + */ +inline PlatformManager & PlatformMgr(void) +{ + return PlatformManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the PlatformManager + * singleton object. + * + * chip applications can use this to gain access to features of the + * PlatformManager that are specific to the SoC. + */ +inline PlatformManagerImpl & PlatformMgrImpl(void) +{ + return PlatformManagerImpl::sInstance; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/SystemPlatformConfig.h b/src/platform/cc13xx_26xx/cc13x4_26x4/SystemPlatformConfig.h new file mode 100644 index 00000000000000..8a65078ca2e28d --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/SystemPlatformConfig.h @@ -0,0 +1,39 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Platform-specific configuration overrides for the CHIP System + * Layer + * + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { +struct ChipDeviceEvent; +} // namespace DeviceLayer +} // namespace chip + +// ==================== Platform Adaptations ==================== +#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 1 +#define CHIP_SYSTEM_CONFIG_EVENT_OBJECT_TYPE const struct ::chip::DeviceLayer::ChipDeviceEvent * + +// ========== Platform-specific Configuration Overrides ========= diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/ThreadStackManagerImpl.h b/src/platform/cc13xx_26xx/cc13x4_26x4/ThreadStackManagerImpl.h new file mode 100644 index 00000000000000..afabf6069cc38f --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/ThreadStackManagerImpl.h @@ -0,0 +1,141 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Provides an implementation of the ThreadStackManager object + * for the Texas Instruments CC13XX_26XX platform. + * + * NOTE: currently a bare-bones implementation to allow for building. + */ + +#pragma once + +#include +#include + +#include +#include + +#include + +extern "C" void platformAlarmSignal(); +extern "C" void platformAlarmMicroSignal(); +extern "C" void platformRadioSignal(uintptr_t arg); +extern "C" void platformUartSignal(uintptr_t arg); + +namespace chip { +namespace DeviceLayer { + +class ThreadStackManager; +class ThreadStackManagerImpl; + +/** + * Concrete implementation of the ThreadStackManager singleton object for CC13XX_26XX. + */ +class ThreadStackManagerImpl final : public ThreadStackManager, + public Internal::GenericThreadStackManagerImpl_OpenThread_LwIP, + public Internal::GenericThreadStackManagerImpl_FreeRTOS +{ + // Allow the ThreadStackManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend class ThreadStackManager; + + // Allow the generic implementation base classes to call helper methods on + // this class. +#ifndef DOXYGEN_SHOULD_SKIP_THIS + friend Internal::GenericThreadStackManagerImpl_OpenThread; + friend Internal::GenericThreadStackManagerImpl_OpenThread_LwIP; + friend Internal::GenericThreadStackManagerImpl_FreeRTOS; +#endif + + // Allow glue functions called by OpenThread to call helper methods on this + // class. + friend void ::platformAlarmSignal(); + friend void ::platformAlarmMicroSignal(); + friend void ::platformRadioSignal(uintptr_t arg); + friend void ::platformUartSignal(uintptr_t arg); + friend void ::otTaskletsSignalPending(otInstance * otInst); + + enum procQueueCmd + { + procQueueCmd_alarm, + procQueueCmd_radio, + procQueueCmd_tasklets, + procQueueCmd_uart, + procQueueCmd_alarmu, + }; + + struct procQueueMsg + { + enum procQueueCmd cmd; + uintptr_t arg; + }; + +public: + // ===== Platform-specific members that may be accessed directly by the application. + + using ThreadStackManager::InitThreadStack; + CHIP_ERROR InitThreadStack(otInstance * otInst); + void _SendProcMessage(procQueueMsg & procMsg); + void _ProcMessage(otInstance * aInstance); + void GetExtAddress(otExtAddress & aExtAddr); + +private: + // ===== Methods that implement the ThreadStackManager abstract interface. + + CHIP_ERROR _InitThreadStack(void); + + // ===== Members for internal use by the following friends. + + friend ThreadStackManager & ::chip::DeviceLayer::ThreadStackMgr(void); + friend ThreadStackManagerImpl & ::chip::DeviceLayer::ThreadStackMgrImpl(void); + + static ThreadStackManagerImpl sInstance; + + static bool IsInitialized(); + + // ===== Private members for use by this class only. + + ThreadStackManagerImpl() = default; + QueueHandle_t procQueue; +}; + +/** + * Returns the public interface of the ThreadStackManager singleton object. + * + * chip applications should use this to access features of the ThreadStackManager object + * that are common to all platforms. + */ +inline ThreadStackManager & ThreadStackMgr(void) +{ + return ThreadStackManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the ThreadStackManager singleton object. + * + * chip applications can use this to gain access to features of the ThreadStackManager + * that are specific to SoC. + */ +inline ThreadStackManagerImpl & ThreadStackMgrImpl(void) +{ + return ThreadStackManagerImpl::sInstance; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/args.gni b/src/platform/cc13xx_26xx/cc13x4_26x4/args.gni new file mode 100644 index 00000000000000..35c5499e2b02f1 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/args.gni @@ -0,0 +1,37 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/ti_simplelink_sdk.gni") + +# ARM architecture flags will be set based on Device Family +arm_platform_config = + "${ti_simplelink_sdk_build_root}/ti_simplelink_arm_platform_config.gni" + +chip_device_platform = "cc13x4_26x4" + +mbedtls_target = "${chip_root}/third_party/ti_simplelink_sdk:mbedtls" +openthread_external_mbedtls = mbedtls_target +openthread_external_platform = + "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk" + +lwip_platform = "cc13xx_26xx" + +chip_inet_config_enable_ipv4 = false + +chip_build_tests = false + +openthread_project_core_config_file = "openthread-core-cc13x4_26x4-config.h" +openthread_core_config_platform_check_file = + "openthread-core-cc13x4_26x4-config-check.h" diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/ble_user_config.c b/src/platform/cc13xx_26xx/cc13x4_26x4/ble_user_config.c new file mode 100644 index 00000000000000..7f51e3226e565a --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/ble_user_config.c @@ -0,0 +1,560 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * + * 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. + */ + +/** + * @file + * This file contains user configurable variables for the BLE Application. + * + */ + +/******************************************************************************* + * INCLUDES + */ + +#include "ble_user_config.h" +#include "hal_types.h" +#ifndef FREERTOS +#include +#endif +#ifdef SYSCFG +#include "ti_ble_config.h" +#else +#include +#endif + +#ifndef CC23X0 +#include "ble_overrides.h" +#include "ti_radio_config.h" + +#include "ecc/ECCROMCC26XX.h" +#include +#include +#include +#include +#else +#include +#include +#include +#endif + +#include +#include +#include + +#ifdef FREERTOS +#define Swi_restore SwiP_restore +#define Swi_disable SwiP_disable +#include +#else +#include +#endif +#include + +#ifndef CC23X0 +#if !defined(DeviceFamily_CC26X1) +#include +#if !defined(DeviceFamily_CC13X4) +#include +#endif +#else +#include +#endif +#endif + +/******************************************************************************* + * MACROS + */ + +/******************************************************************************* + * CONSTANTS + */ + +// Tx Power +#define NUM_TX_POWER_VALUES (RF_BLE_TX_POWER_TABLE_SIZE - 1) + +#ifndef SYSCFG +// Default Tx Power Index +#if defined(CC13X2P) +#define DEFAULT_TX_POWER HCI_EXT_TX_POWER_0_DBM +#else // !CC13X2 +#define DEFAULT_TX_POWER HCI_EXT_TX_POWER_0_DBM +#endif // CC13X2 +#endif // SYSCFG + +// Override NOP +#define OVERRIDE_NOP 0xC0000001 + +/******************************************************************************* + * TYPEDEFS + */ + +/******************************************************************************* + * LOCAL VARIABLES + */ + +/********************************************************************* + * LOCAL FUNCTIONS + */ + +void driverTable_fnSpinlock(void); + +/******************************************************************************* + * GLOBAL VARIABLES + */ + +#ifndef CC23X0 +// Tx Power Table +txPwrTbl_t appTxPwrTbl = { (txPwrVal_t *) RF_BLE_txPowerTable, + NUM_TX_POWER_VALUES, // max + DEFAULT_TX_POWER }; // default +#endif +#if defined(CC13X2P) && defined(CC13X2P_2_LAUNCHXL) + +// Tx Power Backoff Values (txPwrBackoff1MPhy,txPwrBackoff2MPhy ,txPwrBackoffCoded) +const txPwrBackoffVal_t TxPowerBackoffTable[] = { + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 0 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 1 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 2 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 3 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 4 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 5 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 6 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 7 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 8 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 9 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 10 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 11 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 12 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 13 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 14 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 15 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 16 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 17 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 18 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 19 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 20 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 21 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 22 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 23 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 24 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 25 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 26 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 27 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 28 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 29 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 30 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 31 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 32 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 33 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_17_DBM_P4_9_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 34 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_18_DBM_P4_10_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 35 + { HCI_EXT_TX_POWER_P2_19_DBM, HCI_EXT_TX_POWER_P2_18_DBM_P4_10_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 36 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 37 + { HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM }, // max tx power for channel 38 + { HCI_EXT_TX_POWER_P2_14_DBM_P4_6_DBM, HCI_EXT_TX_POWER_P2_20_DBM, HCI_EXT_TX_POWER_P2_20_DBM } +}; // max tx power for channel 39 + +txPwrBackoffTbl_t appTxPwrBackoffTbl = { TxPowerBackoffTable }; + +#endif // defined(CC13X2P) && defined(CC13X2P_2_LAUNCHXL) + +// Antenna board configurations (example for a 12-antenna board) +// Maximum number of antennas +#define ANTENNA_TABLE_SIZE 12 +// BitMask of all the relevant GPIOs which needed for the antennas +#define ANTENNA_IO_MASK BV(27) | BV(28) | BV(29) | BV(30) + +// Antenna GPIO configuration (should be adapted to the antenna board design) +antennaIOEntry_t antennaTbl[ANTENNA_TABLE_SIZE] = { + 0, // antenna 0 GPIO configuration (all GPIOs in ANTENNA_IO_MASK are LOW) + BV(28), // antenna 1 + BV(29), // antenna 2 + BV(28) | BV(29), // antenna 3 + BV(30), // antenna 4 + BV(28) | BV(30), // antenna 5 + BV(27), // antenna 6 + BV(27) | BV(28), // antenna 7 + BV(27) | BV(29), // antenna 8 + BV(27) | BV(28) | BV(29), // antenna 9 + BV(27) | BV(30), // antenna 10 + BV(27) | BV(28) | BV(30) // antenna 11 +}; + +#ifdef RTLS_CTE +// Antenna properties passes to the stack +cteAntProp_t appCTEAntProp = { ANTENNA_IO_MASK, ANTENNA_TABLE_SIZE, antennaTbl }; +#endif + +#ifdef CC23X0 +ECCParams_CurveParams eccParams_NISTP256 = { .curveType = ECCParams_CURVE_TYPE_SHORT_WEIERSTRASS_AN3, + .length = ECCParams_NISTP256_LENGTH, + .prime = ECC_NISTP256_prime.byte, + .order = ECC_NISTP256_order.byte, + .a = ECC_NISTP256_a.byte, + .b = ECC_NISTP256_b.byte, + .generatorX = ECC_NISTP256_generatorX.byte, + .generatorY = ECC_NISTP256_generatorY.byte, + .cofactor = 1 }; +#elif !defined(DeviceFamily_CC26X1) +ECCParams_CurveParams eccParams_NISTP256 = { .curveType = ECCParams_CURVE_TYPE_SHORT_WEIERSTRASS_AN3, + .length = NISTP256_PARAM_SIZE_BYTES, + .prime = NISTP256_prime.byte, + .order = NISTP256_order.byte, + .a = NISTP256_a.byte, + .b = NISTP256_b.byte, + .generatorX = NISTP256_generator.x.byte, + .generatorY = NISTP256_generator.y.byte, + .cofactor = 1 }; +#else +ECCParams_CurveParams eccParams_NISTP256 = { .curveType = ECCParams_CURVE_TYPE_SHORT_WEIERSTRASS_AN3, + .length = ECC_NISTP256_PARAM_LENGTH_BYTES, + .prime = ECC_NISTP256_prime.byte, + .order = ECC_NISTP256_order.byte, + .a = ECC_NISTP256_a.byte, + .b = ECC_NISTP256_b.byte, + .generatorX = ECC_NISTP256_generatorX.byte, + .generatorY = ECC_NISTP256_generatorY.byte, + .cofactor = 1 }; +#endif + +#if defined(USE_COEX) +// 2 structures generated by the sysconfig RF for coexistence configuration +extern rfCoreHal_bleCoExConfig_t coexConfig; +extern RF_CoexOverride_BLEUseCases coexConfigBle; +// from coexConfig struct we will get the coex enable and coex type (3 or 1 wire) +// from coexConfigBle struct we will get the priority and rx request per use case: +// initiator, connected, Broadcaster and Observer. +coexUseCaseConfig_t coexSysConfig = { &coexConfig, &coexConfigBle }; +#endif + +#ifdef ICALL_JT +#include + +#ifndef CC23X0 +// RF Driver API Table +rfDrvTblPtr_t rfDriverTableBLE[] = { + (uint32) RF_open, + (uint32) driverTable_fnSpinlock, // RF_close +#ifdef RF_SINGLEMODE + (uint32) RF_postCmd, +#else // !RF_SINGLEMODE + (uint32) driverTable_fnSpinlock, // RF_postCmd +#endif // RF_SINGLEMODE + (uint32) driverTable_fnSpinlock, // RF_pendCmd +#ifdef RF_SINGLEMODE + (uint32) RF_runCmd, +#else // !RF_SINGLEMODE + (uint32) driverTable_fnSpinlock, // RF_runCmd +#endif // RF_SINGLEMODE + (uint32) RF_cancelCmd, + (uint32) RF_flushCmd, + (uint32) driverTable_fnSpinlock, // RF_yield + (uint32) RF_Params_init, + (uint32) RF_runImmediateCmd, + (uint32) RF_runDirectCmd, + (uint32) RF_ratCompare, + (uint32) driverTable_fnSpinlock, // RF_ratCapture + (uint32) RF_ratDisableChannel, + (uint32) RF_getCurrentTime, + (uint32) RF_getRssi, + (uint32) RF_getInfo, + (uint32) RF_getCmdOp, + (uint32) RF_control, + (uint32) driverTable_fnSpinlock, // RF_getTxPower + (uint32) RF_setTxPower, // RF_setTxPower + (uint32) driverTable_fnSpinlock, // RF_TxPowerTable_findPowerLevel + (uint32) driverTable_fnSpinlock, // RF_TxPowerTable_findValue +#ifndef RF_SINGLEMODE + (uint32) RF_scheduleCmd, + (uint32) RF_runScheduleCmd, + (uint32) driverTable_fnSpinlock, // RF_requestAccess +#endif // !RF_SINGLEMODE +}; + +cryptoDrvTblPtr_t cryptoDriverTableBLE[] = { (uint32) AESCCM_init, + (uint32) AESCCM_open, + (uint32) AESCCM_close, + (uint32) AESCCM_Params_init, + (uint32) AESCCM_Operation_init, + (uint32) AESCCM_oneStepEncrypt, + (uint32) AESCCM_oneStepDecrypt, + (uint32) AESECB_init, + (uint32) AESECB_open, + (uint32) AESECB_close, + (uint32) AESECB_Params_init, + (uint32) AESECB_Operation_init, + (uint32) AESECB_oneStepEncrypt, + (uint32) AESECB_oneStepDecrypt, + (uint32) CryptoKeyPlaintext_initKey, + (uint32) CryptoKeyPlaintext_initBlankKey }; + +// Swi APIs needed by BLE controller +rtosApiTblPtr_t rtosApiTable[] = { (uint32_t) Swi_disable, (uint32_t) Swi_restore }; +#endif +// BLE Stack Configuration Structure +const stackSpecific_t bleStackConfig = { .maxNumConns = MAX_NUM_BLE_CONNS, + .maxNumPDUs = MAX_NUM_PDU, + .maxPduSize = 0, + .maxNumPSM = L2CAP_NUM_PSM, + .maxNumCoChannels = L2CAP_NUM_CO_CHANNELS, + .maxWhiteListElems = MAX_NUM_WL_ENTRIES, + .maxResolvListElems = CFG_MAX_NUM_RL_ENTRIES, + .pfnBMAlloc = &pfnBMAlloc, + .pfnBMFree = &pfnBMFree, +#ifndef CC23X0 + .rfDriverParams.powerUpDurationMargin = RF_POWER_UP_DURATION_MARGIN, + .rfDriverParams.inactivityTimeout = RF_INACTIVITY_TIMEOUT, + .rfDriverParams.powerUpDuration = RF_POWER_UP_DURATION, + .rfDriverParams.pErrCb = &(RF_ERR_CB), +#endif + .eccParams = &eccParams_NISTP256, + .fastStateUpdateCb = NULL, + .bleStackType = 0, +#ifdef CC2652RB_LAUNCHXL + .extStackSettings = EXTENDED_STACK_SETTINGS | CC2652RB_OVERRIDE_USED, +#else + .extStackSettings = EXTENDED_STACK_SETTINGS, +#endif +#ifndef CC23X0 + .maxNumCteBuffers = MAX_NUM_CTE_BUFS, + .advReportIncChannel = ADV_RPT_INC_CHANNEL +#endif +}; + +uint16_t bleUserCfg_maxPduSize = MAX_PDU_SIZE; + +#ifdef OSAL_SNV_EXTFLASH +const extflashDrvTblPtr_t extflashDriverTable[] = { (uint32) ExtFlash_open, (uint32) ExtFlash_close, (uint32) ExtFlash_read, + (uint32) ExtFlash_write, (uint32) ExtFlash_erase }; +#endif // OSAL_SNV_EXTFLASH + +#ifndef CC23X0 +// Table for Driver can be found in icall_user_config.c +// if a driver is not to be used, then the pointer shoul dbe set to NULL, +// for this example, this is done in ble_user_config.h +const drvTblPtr_t driverTable = { + .rfDrvTbl = rfDriverTableBLE, + .eccDrvTbl = eccDriverTable, + .cryptoDrvTbl = cryptoDriverTableBLE, + .trngDrvTbl = trngDriverTable, + .rtosApiTbl = rtosApiTable, + .nvintfStructPtr = &nvintfFncStruct, +#ifdef OSAL_SNV_EXTFLASH + .extflashDrvTbl = extflashDriverTable, +#endif // OSAL_SNV_EXTFLASH +}; +#endif + +const boardConfig_t boardConfig = { +#ifndef CC23X0 + .rfFeModeBias = RF_FE_MODE_AND_BIAS, + .rfRegTbl = (regOverride_t *) pOverrides_bleCommon, + .rfRegTbl1M = (regOverride_t *) pOverrides_ble1Mbps, + .rfRegTbl2M = (regOverride_t *) pOverrides_ble2Mbps, + .rfRegTblCoded = (regOverride_t *) pOverrides_bleCoded, + .txPwrTbl = &appTxPwrTbl, +#if defined(CC13X2P) || defined(EM_CC1354P10_1_LP) +#if defined(CC13X2P_2_LAUNCHXL) + .txPwrBackoffTbl = &appTxPwrBackoffTbl, +#else + .txPwrBackoffTbl = NULL, +#endif // defined(CC13X2P_2_LAUNCHXL) +#if defined(EM_CC1354P10_1_LP) + .rfRegOverrideTxStdTblptr = NULL, + .rfRegOverrideTx20TblPtr = NULL, +#else + .rfRegOverrideTxStdTblptr = (regOverride_t *) pOverrides_bleTxStd, // Default PA + .rfRegOverrideTx20TblPtr = (regOverride_t *) pOverrides_bleTx20, // High power PA +#endif // EM_CC1354P10_1_LP +#endif // CC13X2P +#if defined(RTLS_CTE) + .rfRegOverrideCtePtr = (regOverride_t *) (pOverrides_bleCommon + BLE_STACK_OVERRIDES_OFFSET + CTE_OVERRIDES_OFFSET), + .cteAntennaPropPtr = &appCTEAntProp, +#else + .rfRegOverrideCtePtr = NULL, + .cteAntennaPropPtr = NULL, +#endif + .privOverrideOffset = BLE_STACK_OVERRIDES_OFFSET + PRIVACY_OVERRIDE_OFFSET, +#if defined(USE_COEX) + .coexUseCaseConfigPtr = &coexSysConfig, +#else + .coexUseCaseConfigPtr = NULL, +#endif +#endif +}; + +#else /* !(ICALL_JT) */ + +#ifndef CC23X0 +// RF Driver API Table +rfDrvTblPtr_t rfDriverTable[] = { + (uint32) RF_open, + (uint32) driverTable_fnSpinlock, // RF_close +#ifdef RF_SINGLEMODE + (uint32) RF_postCmd, +#else // !RF_SINGLEMODE + (uint32) driverTable_fnSpinlock, // RF_postCmd +#endif // RF_SINGLEMODE + (uint32) driverTable_fnSpinlock, // RF_pendCmd +#ifdef RF_SINGLEMODE + (uint32) RF_runCmd, +#else // !RF_SINGLEMODE + (uint32) driverTable_fnSpinlock, // RF_runCmd +#endif // RF_SINGLEMODE + (uint32) RF_cancelCmd, + (uint32) RF_flushCmd, + (uint32) driverTable_fnSpinlock, // RF_yield + (uint32) RF_Params_init, + (uint32) RF_runImmediateCmd, + (uint32) RF_runDirectCmd, + (uint32) RF_ratCompare(uint32) driverTable_fnSpinlock, // RF_ratCapture + (uint32) driverTable_fnSpinlock, // RF_ratDisableChannel + (uint32) RF_getCurrentTime, + (uint32) RF_getRssi, + (uint32) RF_getInfo, + (uint32) RF_getCmdOp, + (uint32) RF_control, + (uint32) driverTable_fnSpinlock, // RF_getTxPower + (uint32) RF_setTxPower, // RF_setTxPower + (uint32) driverTable_fnSpinlock, // RF_TxPowerTable_findPowerLevel + (uint32) driverTable_fnSpinlock, // RF_TxPowerTable_findValue +#ifndef RF_SINGLEMODE + (uint32) RF_scheduleCmd, + (uint32) RF_runScheduleCmd, + (uint32) driverTable_fnSpinlock // RF_requestAccess +#endif // !RF_SINGLEMODE +}; + +// ECC Driver API Table +eccDrvTblPtr_t eccDriverTable[] = { (uint32) ECDH_init, + (uint32) ECDH_Params_init, + (uint32) ECDH_open, + (uint32) ECDH_close, + (uint32) ECDH_OperationGeneratePublicKey_init, + (uint32) ECDH_OperationComputeSharedSecret_init, + (uint32) ECDH_generatePublicKey, + (uint32) ECDH_computeSharedSecret }; + +// Crypto Driver API Table +cryptoDrvTblPtr_t cryptoDriverTable[] = { (uint32) AESCCM_init, + (uint32) AESCCM_open, + (uint32) AESCCM_close, + (uint32) AESCCM_Params_init, + (uint32) AESCCM_Operation_init, + (uint32) AESCCM_oneStepEncrypt, + (uint32) AESCCM_oneStepDecrypt, + (uint32) AESECB_init, + (uint32) AESECB_open, + (uint32) AESECB_close, + (uint32) AESECB_Params_init, + (uint32) AESECB_Operation_init, + (uint32) AESECB_oneStepEncrypt, + (uint32) AESECB_oneStepDecrypt, + (uint32) CryptoKeyPlaintext_initKey, + (uint32) CryptoKeyPlaintext_initBlankKey }; + +trngDrvTblPtr_t trngDriverTable[] = { (uint32) TRNG_init, (uint32) TRNG_open, (uint32) TRNG_generateEntropy, (uint32) TRNG_close }; +#endif + +#endif /* ICALL_JT */ + +/******************************************************************************* + * @fn RegisterAssertCback + * + * @brief This routine registers the Application's assert handler. + * + * input parameters + * + * @param appAssertHandler - Application's assert handler. + * + * output parameters + * + * @param None. + * + * @return None. + */ +void RegisterAssertCback(assertCback_t appAssertHandler) +{ + appAssertCback = appAssertHandler; + +#ifdef EXT_HAL_ASSERT + // also set the Assert callback pointer used by halAssertHandlerExt + // Note: Normally, this pointer will be intialized by the stack, but in the + // event HAL_ASSERT is used by the Application, we initialize it + // directly here. + halAssertCback = appAssertHandler; +#endif // EXT_HAL_ASSERT + + return; +} + +/******************************************************************************* + * @fn driverTable_fnSpinLock + * + * @brief This routine is used to trap calls to unpopulated indexes of + * driver function pointer tables. + * + * input parameters + * + * @param None. + * + * output parameters + * + * @param None. + * + * @return None. + */ +void driverTable_fnSpinlock(void) +{ + volatile uint8 i = 1; + + while (i) + ; +} + +/******************************************************************************* + * @fn DefaultAssertCback + * + * @brief This is the Application default assert callback, in the event + * none is registered. + * + * input parameters + * + * @param assertCause - Assert cause as defined in hal_assert.h. + * @param assertSubcause - Optional assert subcause (see hal_assert.h). + * + * output parameters + * + * @param None. + * + * @return None. + */ +void DefaultAssertCback(uint8 assertCause, uint8 assertSubcause) +{ +#ifdef HAL_ASSERT_SPIN + driverTable_fnSpinlock(); +#endif // HAL_ASSERT_SPIN + + return; +} + +// Application Assert Callback Function Pointer +assertCback_t appAssertCback = DefaultAssertCback; + +/******************************************************************************* + */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos.lds b/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos.lds new file mode 100644 index 00000000000000..52e08615592fed --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos.lds @@ -0,0 +1,259 @@ +/* + * + * 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. + */ + +/** + * @file + * Linkerscript for a non-OTA Matter executable. + */ + +STACKSIZE = 0x2000; + +MEMORY +{ + FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0x00100000 + /* + * Customer Configuration Area and Bootloader Backdoor configuration in + * flash + */ + FLASH_CCFG (RX) : ORIGIN = 0x50000000, LENGTH = 0x00000800 + SRAM (RWX) : ORIGIN = 0x20000000, LENGTH = 0x00040000 + GPRAM (RWX) : ORIGIN = 0x11000000, LENGTH = 0x00002000 + /* Explicitly placed off target for the storage of logging data. + * The data placed here is NOT loaded onto the target device. + * This is part of 1 GB of external memory from 0x60000000 - 0x9FFFFFFF. + * ARM memory map can be found here: + * https://developer.arm.com/documentation/ddi0337/e/memory-map/about-the-memory-map + */ + LOG_DATA (R) : ORIGIN = 0x90000000, LENGTH = 0x40000 +} + +REGION_ALIAS("REGION_TEXT", FLASH); +REGION_ALIAS("REGION_BSS", SRAM); +REGION_ALIAS("REGION_DATA", SRAM); +REGION_ALIAS("REGION_STACK", SRAM); +REGION_ALIAS("REGION_HEAP", SRAM); +REGION_ALIAS("REGION_LOG", LOG_DATA); +REGION_ALIAS("REGION_ARM_EXIDX", FLASH); +REGION_ALIAS("REGION_ARM_EXTAB", FLASH); + +SECTIONS { + PROVIDE (_intvecs_base_address = + DEFINED(_intvecs_base_address) ? _intvecs_base_address : 0x00); + + .resetVecs (_intvecs_base_address) : AT (_intvecs_base_address) { + KEEP (*(.resetVecs)) + } > REGION_TEXT + + PROVIDE (_vtable_base_address = + DEFINED(_vtable_base_address) ? _vtable_base_address : 0x20000000); + + .vtable (_vtable_base_address) (NOLOAD) : { + KEEP (*(.ramVecs)) + } > REGION_DATA + + /* + * UDMACC26XX_CONFIG_BASE below must match UDMACC26XX_CONFIG_BASE defined + * by ti/drivers/dma/UDMACC26XX.h + * The user is allowed to change UDMACC26XX_CONFIG_BASE to move it away from + * the default address 0x2000_0400, but remember it must be 1024 bytes aligned. + */ + UDMACC26XX_CONFIG_BASE = 0x20000400; + + /* + * Define absolute addresses for the DMA channels. + * DMA channels must always be allocated at a fixed offset from the DMA base address. + * --------- DO NOT MODIFY ----------- + */ + DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x10); + DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x20); + DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x30); + DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x40); + DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x50); + DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x60); + DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x70); + DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x90); + DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x100); + DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x110); + + DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x210); + DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x220); + DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x230); + DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x240); + DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x250); + DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x260); + DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x270); + DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x290); + DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x300); + DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x310); + + /* + * Allocate UART0, UART1, SPI0, SPI1, ADC, and GPTimer0 DMA descriptors at absolute addresses. + * --------- DO NOT MODIFY ----------- + */ + UDMACC26XX_uart0RxControlTableEntry_is_placed = 0; + .dmaUart0RxControlTableEntry DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0TxControlTableEntry_is_placed = 0; + .dmaUart0TxControlTableEntry DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0RxControlTableEntry_is_placed = 0; + .dmaSpi0RxControlTableEntry DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0TxControlTableEntry_is_placed = 0; + .dmaSpi0TxControlTableEntry DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1RxControlTableEntry_is_placed = 0; + .dmaUart1RxControlTableEntry DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1TxControlTableEntry_is_placed = 0; + .dmaUart1TxControlTableEntry DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaADCPriControlTableEntry_is_placed = 0; + .dmaADCPriControlTableEntry DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaADCPriControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaGPT0APriControlTableEntry_is_placed = 0; + .dmaGPT0APriControlTableEntry DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaGPT0APriControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1RxControlTableEntry_is_placed = 0; + .dmaSpi1RxControlTableEntry DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1TxControlTableEntry_is_placed = 0; + .dmaSpi1TxControlTableEntry DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0RxAltControlTableEntry_is_placed = 0; + .dmaUart0RxAltControlTableEntry DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0TxAltControlTableEntry_is_placed = 0; + .dmaUart0TxAltControlTableEntry DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0RxAltControlTableEntry_is_placed = 0; + .dmaSpi0RxAltControlTableEntry DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0TxAltControlTableEntry_is_placed = 0; + .dmaSpi0TxAltControlTableEntry DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1RxAltControlTableEntry_is_placed = 0; + .dmaUart1RxAltControlTableEntry DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1TxAltControlTableEntry_is_placed = 0; + .dmaUart1TxAltControlTableEntry DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaADCAltControlTableEntry_is_placed = 0; + .dmaADCAltControlTableEntry DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaADCAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaGPT0AAltControlTableEntry_is_placed = 0; + .dmaGPT0AAltControlTableEntry DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaGPT0AAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1RxAltControlTableEntry_is_placed = 0; + .dmaSpi1RxAltControlTableEntry DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1TxAltControlTableEntry_is_placed = 0; + .dmaSpi1TxAltControlTableEntry DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1TxAltControlTableEntry)} > REGION_DATA + + .text : { + CREATE_OBJECT_SYMBOLS + *(.text) + *(.text.*) + . = ALIGN(0x4); + KEEP (*(.ctors)) + . = ALIGN(0x4); + KEEP (*(.dtors)) + . = ALIGN(0x4); + __init_array_start = .; + KEEP (*(.init_array*)) + __init_array_end = .; + *(.init) + *(.fini*) + } > REGION_TEXT AT> REGION_TEXT + + PROVIDE (__etext = .); + PROVIDE (_etext = .); + PROVIDE (etext = .); + + .rodata : { + *(.rodata) + *(.rodata.*) + *(.rodata_*) + } > REGION_TEXT AT> REGION_TEXT + + .data : ALIGN(4) { + __data_load__ = LOADADDR (.data); + __data_start__ = .; + *(.data) + *(.data.*) + . = ALIGN (4); + __data_end__ = .; + } > REGION_DATA AT> REGION_TEXT + + .ARM.exidx : { + __exidx_start = .; + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + __exidx_end = .; + } > REGION_ARM_EXIDX AT> REGION_ARM_EXIDX + + .ARM.extab : { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > REGION_ARM_EXTAB AT> REGION_ARM_EXTAB + + /* End of executable code/data, NVS is not part of the OTA image */ + PROVIDE (_flash_end_address = .); + + /* 5 pages of NV Memory (0x800 each) offset by 1 page for BIM/CCFG */ + /*.nvs (NOLOAD) : ALIGN(0x2000) { */ + .nvs (0xFB800) (NOLOAD) : AT (0xFB800) ALIGN(0x800) { + *(.nvs) + } > REGION_TEXT + + .ccfg : { + KEEP (*(.ccfg)) + } > FLASH_CCFG AT> FLASH_CCFG + + .bss : { + __bss_start__ = .; + *(.shbss) + *(.bss) + *(.bss.*) + *(COMMON) + . = ALIGN (4); + __bss_end__ = .; + } > REGION_BSS AT> REGION_BSS + + .heap : { + __heap_start__ = .; + end = __heap_start__; + _end = end; + __end = end; + KEEP(*(.heap)) + __heap_end__ = .; + __HeapLimit = __heap_end__; + } > REGION_HEAP AT> REGION_HEAP + + .stack (NOLOAD) : ALIGN(0x8) { + _stack = .; + __stack = .; + KEEP(*(.stack)) + . += STACKSIZE; + _stack_end = .; + __stack_end = .; + } > REGION_STACK AT> REGION_STACK + + .log_data (COPY) : { + KEEP (*(.log_data)) + } > REGION_LOG +} + +ENTRY(resetISR) diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos_ota.lds b/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos_ota.lds new file mode 100644 index 00000000000000..83b05fb2716c79 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos_ota.lds @@ -0,0 +1,270 @@ +/* + * + * 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. + */ + +/** + * @file + * Linkerscript for Matter executable with space reserved for the TI BIM. + */ + +STACKSIZE = 0x800; + +MEMORY +{ + FLASH (RX) : ORIGIN = 0x00000000, LENGTH = 0xFF800 + /* + * Customer Configuration Area and Bootloader Backdoor configuration in + * flash + */ + /* FLASH_CCFG (RX) : ORIGIN = 0x50000000, LENGTH = 0x00000800 */ + SRAM (RWX) : ORIGIN = 0x20000000, LENGTH = 0x00040000 + GPRAM (RWX) : ORIGIN = 0x11000000, LENGTH = 0x00002000 + /* Explicitly placed off target for the storage of logging data. + * The data placed here is NOT loaded onto the target device. + * This is part of 1 GB of external memory from 0x60000000 - 0x9FFFFFFF. + * ARM memory map can be found here: + * https://developer.arm.com/documentation/ddi0337/e/memory-map/about-the-memory-map + */ + LOG_DATA (R) : ORIGIN = 0x90000000, LENGTH = 0x40000 +} + +REGION_ALIAS("REGION_TEXT", FLASH); +REGION_ALIAS("REGION_BSS", SRAM); +REGION_ALIAS("REGION_DATA", SRAM); +REGION_ALIAS("REGION_STACK", SRAM); +REGION_ALIAS("REGION_HEAP", SRAM); +REGION_ALIAS("REGION_LOG", LOG_DATA); +REGION_ALIAS("REGION_ARM_EXIDX", FLASH); +REGION_ALIAS("REGION_ARM_EXTAB", FLASH); + +SECTIONS { + /* BIM header placed at the base of flash by default */ + PROVIDE (_img_header_base_address = + DEFINED(_img_header_base_address) ? _img_header_base_address : 0x0); + + .oad_image_header (_img_header_base_address) : AT (_img_header_base_address) { + KEEP (*(.oad_image_header)) + } > REGION_TEXT + + /* interrupt vectors shifted to accommodate BIM header */ + PROVIDE (_intvecs_base_address = + DEFINED(_intvecs_base_address) ? _intvecs_base_address : 0x100); + + .resetVecs (_intvecs_base_address) : AT (_intvecs_base_address) { + KEEP (*(.resetVecs)) + } > REGION_TEXT + + PROVIDE (_vtable_base_address = + DEFINED(_vtable_base_address) ? _vtable_base_address : 0x20000000); + + .vtable (_vtable_base_address) (NOLOAD) : { + KEEP (*(.ramVecs)) + } > REGION_DATA + + /* + * UDMACC26XX_CONFIG_BASE below must match UDMACC26XX_CONFIG_BASE defined + * by ti/drivers/dma/UDMACC26XX.h + * The user is allowed to change UDMACC26XX_CONFIG_BASE to move it away from + * the default address 0x2000_0400, but remember it must be 1024 bytes aligned. + */ + UDMACC26XX_CONFIG_BASE = 0x20000400; + + /* + * Define absolute addresses for the DMA channels. + * DMA channels must always be allocated at a fixed offset from the DMA base address. + * --------- DO NOT MODIFY ----------- + */ + DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x10); + DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x20); + DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x30); + DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x40); + DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x50); + DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x60); + DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x70); + DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x90); + DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x100); + DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x110); + + DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x210); + DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x220); + DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x230); + DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x240); + DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x250); + DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x260); + DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x270); + DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x290); + DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x300); + DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS = (UDMACC26XX_CONFIG_BASE + 0x310); + + /* + * Allocate UART0, UART1, SPI0, SPI1, ADC, and GPTimer0 DMA descriptors at absolute addresses. + * --------- DO NOT MODIFY ----------- + */ + UDMACC26XX_uart0RxControlTableEntry_is_placed = 0; + .dmaUart0RxControlTableEntry DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0TxControlTableEntry_is_placed = 0; + .dmaUart0TxControlTableEntry DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0RxControlTableEntry_is_placed = 0; + .dmaSpi0RxControlTableEntry DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0TxControlTableEntry_is_placed = 0; + .dmaSpi0TxControlTableEntry DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1RxControlTableEntry_is_placed = 0; + .dmaUart1RxControlTableEntry DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1TxControlTableEntry_is_placed = 0; + .dmaUart1TxControlTableEntry DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaADCPriControlTableEntry_is_placed = 0; + .dmaADCPriControlTableEntry DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_ADC_PRI_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaADCPriControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaGPT0APriControlTableEntry_is_placed = 0; + .dmaGPT0APriControlTableEntry DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_GPT0A_PRI_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaGPT0APriControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1RxControlTableEntry_is_placed = 0; + .dmaSpi1RxControlTableEntry DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_RX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1RxControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1TxControlTableEntry_is_placed = 0; + .dmaSpi1TxControlTableEntry DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_TX_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1TxControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0RxAltControlTableEntry_is_placed = 0; + .dmaUart0RxAltControlTableEntry DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart0TxAltControlTableEntry_is_placed = 0; + .dmaUart0TxAltControlTableEntry DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart0TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0RxAltControlTableEntry_is_placed = 0; + .dmaSpi0RxAltControlTableEntry DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi0TxAltControlTableEntry_is_placed = 0; + .dmaSpi0TxAltControlTableEntry DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI0_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi0TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1RxAltControlTableEntry_is_placed = 0; + .dmaUart1RxAltControlTableEntry DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_uart1TxAltControlTableEntry_is_placed = 0; + .dmaUart1TxAltControlTableEntry DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_UART1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaUart1TxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaADCAltControlTableEntry_is_placed = 0; + .dmaADCAltControlTableEntry DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_ADC_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaADCAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaGPT0AAltControlTableEntry_is_placed = 0; + .dmaGPT0AAltControlTableEntry DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_GPT0A_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaGPT0AAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1RxAltControlTableEntry_is_placed = 0; + .dmaSpi1RxAltControlTableEntry DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_RX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1RxAltControlTableEntry)} > REGION_DATA + + UDMACC26XX_dmaSpi1TxAltControlTableEntry_is_placed = 0; + .dmaSpi1TxAltControlTableEntry DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS (NOLOAD) : AT (DMA_SPI1_TX_ALT_CONTROL_TABLE_ENTRY_ADDRESS) {*(.dmaSpi1TxAltControlTableEntry)} > REGION_DATA + + .text : { + CREATE_OBJECT_SYMBOLS + *(.text) + *(.text.*) + . = ALIGN(0x4); + KEEP (*(.ctors)) + . = ALIGN(0x4); + KEEP (*(.dtors)) + . = ALIGN(0x4); + __init_array_start = .; + KEEP (*(.init_array*)) + __init_array_end = .; + *(.init) + *(.fini*) + } > REGION_TEXT AT> REGION_TEXT + + PROVIDE (__etext = .); + PROVIDE (_etext = .); + PROVIDE (etext = .); + + .rodata : { + *(.rodata) + *(.rodata.*) + *(.rodata_*) + } > REGION_TEXT AT> REGION_TEXT + + .data : ALIGN(4) { + __data_load__ = LOADADDR (.data); + __data_start__ = .; + *(.data) + *(.data.*) + . = ALIGN (4); + __data_end__ = .; + } > REGION_DATA AT> REGION_TEXT + + .ARM.exidx : { + __exidx_start = .; + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + __exidx_end = .; + } > REGION_ARM_EXIDX AT> REGION_ARM_EXIDX + + .ARM.extab : { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > REGION_ARM_EXTAB AT> REGION_ARM_EXTAB + + /* End of executable code/data, NVS is not part of the OTA image */ + PROVIDE (_flash_end_address = .); + + /* Two pages of NV Memory (0x800 each) offset by 1 page for BIM/CCFG */ + .nvs (0xFE800) (NOLOAD) : AT (0xFE800) ALIGN(0x2000) { + *(.nvs) + } > REGION_TEXT + + /* CCFG is supplied by the BIM project */ + /* + .ccfg : { + KEEP (*(.ccfg)) + } > FLASH_CCFG AT> FLASH_CCFG + */ + + .bss : { + __bss_start__ = .; + *(.shbss) + *(.bss) + *(.bss.*) + *(COMMON) + . = ALIGN (4); + __bss_end__ = .; + } > REGION_BSS AT> REGION_BSS + + .heap : { + __heap_start__ = .; + end = __heap_start__; + _end = end; + __end = end; + KEEP(*(.heap)) + __heap_end__ = .; + __HeapLimit = __heap_end__; + } > REGION_HEAP AT> REGION_HEAP + + .stack (NOLOAD) : ALIGN(0x8) { + _stack = .; + __stack = .; + KEEP(*(.stack)) + . += STACKSIZE; + _stack_end = .; + __stack_end = .; + } > REGION_STACK AT> REGION_STACK + + .log_data (COPY) : { + KEEP (*(.log_data)) + } > REGION_LOG +} + +ENTRY(resetISR) diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.c b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.c new file mode 100644 index 00000000000000..b6b790489a9916 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.c @@ -0,0 +1,133 @@ +/* + * + * Copyright (c) 2020 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 "aes_alt.h" +#include "mbedtls/aes.h" + +#if defined(MBEDTLS_AES_ALT) + +#include + +#include "ti_drivers_config.h" + +#include +#include + +/* + * number of active contexts, used for power on/off of the crypto core + */ +static unsigned int ref_num = 0; + +static AESECB_Handle AESECB_handle = NULL; + +void mbedtls_aes_init(mbedtls_aes_context * ctx) +{ + AESECB_Params AESECBParams; + + if (ref_num == 0) + { + AESECB_Params_init(&AESECBParams); + AESECBParams.returnBehavior = AESECB_RETURN_BEHAVIOR_POLLING; + AESECB_handle = AESECB_open(CONFIG_AESECB_1, &AESECBParams); + + // handle will be NULL if open failed, subsequent calls will fail with a generic HW error + } + ref_num++; +} + +void mbedtls_aes_free(mbedtls_aes_context * ctx) +{ + if (ref_num > 0) + { + ref_num--; + if (ref_num == 0) + { + AESECB_close(AESECB_handle); + + AESECB_handle = NULL; + } + } + + memset((void *) ctx, 0x00, sizeof(ctx)); +} + +int mbedtls_aes_setkey_enc(mbedtls_aes_context * ctx, const unsigned char * key, unsigned int keybits) +{ + int_fast16_t statusCrypto; + size_t keylen = keybits / 8U; // 8 bits in a byte + + if (keylen > sizeof(ctx->keyMaterial)) + { + return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; + } + + /* Initialize AES key */ + memcpy(ctx->keyMaterial, key, keylen); + statusCrypto = CryptoKeyPlaintext_initKey(&ctx->cryptoKey, (uint8_t *) ctx->keyMaterial, keylen); + + if (CryptoKey_STATUS_SUCCESS != statusCrypto) + { + return MBEDTLS_ERR_AES_HW_ACCEL_FAILED; + } + + return 0; +} + +int mbedtls_aes_setkey_dec(mbedtls_aes_context * ctx, const unsigned char * key, unsigned int keybits) +{ + int_fast16_t statusCrypto; + size_t keylen = keybits / 8U; // 8 bits in a byte + + if (keylen > sizeof(ctx->keyMaterial)) + { + return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; + } + + /* Initialize AES key */ + statusCrypto = CryptoKeyPlaintext_initKey(&ctx->cryptoKey, (uint8_t *) key, keylen); + + if (CryptoKey_STATUS_SUCCESS != statusCrypto) + { + return MBEDTLS_ERR_AES_HW_ACCEL_FAILED; + } + + return 0; +} + +int mbedtls_aes_crypt_ecb(mbedtls_aes_context * ctx, int mode, const unsigned char input[16], unsigned char output[16]) +{ + int statusCrypto; + AESECB_Operation operationOneStepEncrypt; + + /* run it through the authentication + encryption, pass the ccmLVal = 2 */ + AESECB_Operation_init(&operationOneStepEncrypt); + + operationOneStepEncrypt.key = &ctx->cryptoKey; + operationOneStepEncrypt.inputLength = 16; + operationOneStepEncrypt.input = (uint8_t *) input; + operationOneStepEncrypt.output = (uint8_t *) output; + + statusCrypto = AESECB_oneStepEncrypt(AESECB_handle, &operationOneStepEncrypt); + + if (CryptoKey_STATUS_SUCCESS != statusCrypto) + { + return MBEDTLS_ERR_AES_HW_ACCEL_FAILED; + } + + return 0; +} +#endif diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.h b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.h new file mode 100644 index 00000000000000..9f5ecedec39e88 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/aes_alt.h @@ -0,0 +1,45 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#pragma once + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls-config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_AES_ALT) + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + CryptoKey cryptoKey; /*!< structure for the AES driver */ + uint32_t keyMaterial[16]; /*!< memory for the key bytes used by cryptoKey */ +} mbedtls_aes_context; + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_AES_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/cc13x4_26x4-mbedtls-config.h b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/cc13x4_26x4-mbedtls-config.h new file mode 100644 index 00000000000000..f1bb207c945dc0 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/cc13x4_26x4-mbedtls-config.h @@ -0,0 +1,134 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/* + * + * @file cc13x4_26x4-mbedtls-config.h.h + * + * @brief MbedTLS configuration header for CHIP + * + */ + +#ifndef CC13X4_26X4_MBEDTLS_CONFIG_H +#define CC13X4_26X4_MBEDTLS_CONFIG_H + +#include +#include + +/** + * Enable FreeRTOS threading support + */ +//#define MBEDTLS_FREERTOS +//#define MBEDTLS_THREADING_C +//#define MBEDTLS_THREADING_ALT + +/* Enable Hardware Acceleration */ + +//#define MBEDTLS_AES_ALT +//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT +//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT +//#define MBEDTLS_ECDSA_SIGN_ALT +//#define MBEDTLS_ECDSA_VERIFY_ALT +//#define MBEDTLS_ENTROPY_HARDWARE_ALT +//#define MBEDTLS_SHA256_ALT + +// Thread Joining disabled +//#define MBEDTLS_ECJPAKE_ALT +//#define MBEDTLS_ECJPAKE_C +//#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED +//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 + +/** + * Enable Crypto and Entropy modules + */ + +#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf + +#define MBEDTLS_AES_C +#define MBEDTLS_AES_ROM_TABLES +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C + +#define MBEDTLS_BIGNUM_C +#define MBEDTLS_CCM_C +#define MBEDTLS_CIPHER_C +#define MBEDTLS_CMAC_C +#define MBEDTLS_CTR_DRBG_C +#define MBEDTLS_ECP_C +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define MBEDTLS_ECP_NIST_OPTIM +#define MBEDTLS_ENTROPY_C +#define MBEDTLS_HAVE_ASM +#define MBEDTLS_HMAC_DRBG_C +#define MBEDTLS_MD_C +#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES +#define MBEDTLS_NO_PLATFORM_ENTROPY +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#define MBEDTLS_PK_WRITE_C +#define MBEDTLS_PLATFORM_C +#define MBEDTLS_PLATFORM_MEMORY +#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#define MBEDTLS_SHA256_C +#define MBEDTLS_SHA256_SMALLER +#define MBEDTLS_SSL_CLI_C +#define MBEDTLS_SSL_DTLS_ANTI_REPLAY +#define MBEDTLS_SSL_DTLS_HELLO_VERIFY +#define MBEDTLS_SSL_EXPORT_KEYS +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH +#define MBEDTLS_SSL_PROTO_TLS1_2 +#define MBEDTLS_SSL_PROTO_DTLS +#define MBEDTLS_SSL_TLS_C +#define MBEDTLS_ERROR_STRERROR_DUMMY +#define MBEDTLS_HKDF_C +#define MBEDTLS_X509_CREATE_C +#define MBEDTLS_X509_CSR_WRITE_C +#define MBEDTLS_BASE64_C +#define MBEDTLS_PEM_WRITE_C + +#define MBEDTLS_SSL_COOKIE_C +#define MBEDTLS_SSL_SRV_C + +#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + +#define MBEDTLS_BASE64_C +#define MBEDTLS_ECDH_C +#define MBEDTLS_ECDSA_C +#define MBEDTLS_ECDSA_DETERMINISTIC +#define MBEDTLS_OID_C +#define MBEDTLS_PEM_PARSE_C +#define MBEDTLS_X509_USE_C +#define MBEDTLS_X509_CRT_PARSE_C +#define MBEDTLS_PKCS5_C + +#define MBEDTLS_MPI_WINDOW_SIZE 1 /**< Maximum windows size used. */ +#define MBEDTLS_MPI_MAX_SIZE 32 /**< Maximum number of bytes for usable MPIs. */ +#define MBEDTLS_ECP_MAX_BITS 256 /**< Maximum bit size of groups */ +#define MBEDTLS_ECP_WINDOW_SIZE 2 /**< Maximum window size used */ +#define MBEDTLS_ECP_FIXED_POINT_OPTIM 0 /**< Enable fixed-point speed-up */ +#define MBEDTLS_ENTROPY_MAX_SOURCES 1 /**< Maximum number of sources supported */ + +#define MBEDTLS_MEMORY_BUFFER_ALLOC_C + +#define MBEDTLS_SSL_MAX_CONTENT_LEN 900 /**< Maxium fragment length in bytes */ + +#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 + +#include "mbedtls/check_config.h" + +#endif // CC13X4_26X4_MBEDTLS_CONFIG_H diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdh_alt.c b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdh_alt.c new file mode 100644 index 00000000000000..e14c277a7194ff --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdh_alt.c @@ -0,0 +1,313 @@ +/* + * + * Copyright (c) 2021 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. + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined MBEDTLS_ECDH_COMPUTE_SHARED_ALT || defined MBEDTLS_ECDH_GEN_PUBLIC_ALT + +#include + +#include +#include +#include +#include + +#include "ti_drivers_config.h" + +#include +#include +#include + +/* Parameter validation macros based on platform_util.h */ +#define ECDH_VALIDATE_RET(cond) MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA) +#define ECDH_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE(cond) + +#if defined MBEDTLS_ECDH_GEN_PUBLIC_ALT +/* + * Generate public key (restartable version) + */ +static int ecdh_gen_public_restartable(mbedtls_ecp_group * grp, mbedtls_mpi * d, mbedtls_ecp_point * Q, + int (*f_rng)(void *, unsigned char *, size_t), void * p_rng, + mbedtls_ecp_restart_ctx * rs_ctx) +{ + int ret = 0; + size_t plen = grp->nbits / 8U; + uint8_t * q_buf = (uint8_t *) mbedtls_calloc(1, (plen * 2U) + 1); + uint8_t * d_buf = (uint8_t *) mbedtls_calloc(1, plen); + CryptoKey myPrivateKey; + CryptoKey myPublicKey; + ECDH_Config config = { 0 }; + ECDH_Handle handle = NULL; + ECDH_OperationGeneratePublicKey operationGeneratePublicKey; + ECDHCC26X2_HWAttrs hwAttrs = { 0 }; + ECDHCC26X2_Object object = { 0 }; + + if (NULL == q_buf || NULL == d_buf) + { + ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; + goto cleanup; + } + + hwAttrs.intPriority = (1 << 5); + + config.object = (void *) &object; + config.hwAttrs = (void *) &hwAttrs; + + handle = ECDH_construct(&config, NULL); + + if (NULL == handle) + { + ret = MBEDTLS_ERR_ECP_HW_ACCEL_FAILED; + goto cleanup; + } + + CryptoKeyPlaintext_initKey(&myPrivateKey, d_buf, plen); + CryptoKeyPlaintext_initKey(&myPublicKey, q_buf, (plen * 2U) + 1); + + if (0 != f_rng(p_rng, d_buf, plen)) + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } + + ECDH_OperationGeneratePublicKey_init(&operationGeneratePublicKey); + operationGeneratePublicKey.myPrivateKey = &myPrivateKey; + operationGeneratePublicKey.myPublicKey = &myPublicKey; + + /* Load the ROM curve params */ + switch (grp->id) + { + case MBEDTLS_ECP_DP_SECP224R1: + operationGeneratePublicKey.curve = &ECCParams_NISTP224; + break; + + case MBEDTLS_ECP_DP_SECP256R1: + operationGeneratePublicKey.curve = &ECCParams_NISTP256; + break; + + case MBEDTLS_ECP_DP_SECP384R1: + operationGeneratePublicKey.curve = &ECCParams_NISTP384; + break; + + case MBEDTLS_ECP_DP_SECP521R1: + operationGeneratePublicKey.curve = &ECCParams_NISTP521; + break; + + case MBEDTLS_ECP_DP_BP256R1: + operationGeneratePublicKey.curve = &ECCParams_BrainpoolP256R1; + break; + + case MBEDTLS_ECP_DP_BP384R1: + operationGeneratePublicKey.curve = &ECCParams_BrainpoolP384R1; + break; + + case MBEDTLS_ECP_DP_BP512R1: + operationGeneratePublicKey.curve = &ECCParams_BrainpoolP512R1; + break; + + case MBEDTLS_ECP_DP_CURVE25519: + operationGeneratePublicKey.curve = &ECCParams_Curve25519; + break; + + default: + /* Possible extension to load an arbitrary curve */ + ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + goto cleanup; + } + + if (ECDH_STATUS_SUCCESS == ECDH_generatePublicKey(handle, &operationGeneratePublicKey)) + { + ret = 0; + } + else + { + ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; + } + + MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(d, d_buf, plen)); + MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&(Q->X), q_buf + 1, plen)); + MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&(Q->Y), q_buf + 1 + plen, plen)); + +cleanup: + mbedtls_free(q_buf); + mbedtls_free(d_buf); + + if (NULL != handle) + { + ECDH_close(handle); + } + + return (ret); +} + +/* + * Generate public key + */ +int mbedtls_ecdh_gen_public(mbedtls_ecp_group * grp, mbedtls_mpi * d, mbedtls_ecp_point * Q, + int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + ECDH_VALIDATE_RET(grp != NULL); + ECDH_VALIDATE_RET(d != NULL); + ECDH_VALIDATE_RET(Q != NULL); + ECDH_VALIDATE_RET(f_rng != NULL); + return (ecdh_gen_public_restartable(grp, d, Q, f_rng, p_rng, NULL)); +} +#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */ + +#if defined MBEDTLS_ECDH_COMPUTE_SHARED_ALT +/* + * Compute shared secret (SEC1 3.3.1) + */ +static int ecdh_compute_shared_restartable(mbedtls_ecp_group * grp, mbedtls_mpi * z, const mbedtls_ecp_point * Q, + const mbedtls_mpi * d, int (*f_rng)(void *, unsigned char *, size_t), void * p_rng, + mbedtls_ecp_restart_ctx * rs_ctx) +{ + int ret = 0; + size_t plen = grp->nbits / 8U; + uint8_t * q_buf = (uint8_t *) mbedtls_calloc(1, (plen * 2U) + 1); + uint8_t * s_buf = (uint8_t *) mbedtls_calloc(1, (plen * 2U) + 1); + uint8_t * d_buf = (uint8_t *) mbedtls_calloc(1, plen); + CryptoKey myPrivateKey; + CryptoKey theirPublicKey; + CryptoKey sharedSecret; + ECDH_Config config = { 0 }; + ECDH_Handle handle = NULL; + ECDH_OperationComputeSharedSecret operationComputeSharedSecret; + ECDHCC26X2_HWAttrs hwAttrs = { 0 }; + ECDHCC26X2_Object object = { 0 }; + + if (NULL == q_buf || NULL == s_buf || NULL == d_buf) + { + ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; + goto cleanup; + } + + hwAttrs.intPriority = (1 << 5); + + config.object = (void *) &object; + config.hwAttrs = (void *) &hwAttrs; + + handle = ECDH_construct(&config, NULL); + + if (NULL == handle) + { + ret = MBEDTLS_ERR_ECP_HW_ACCEL_FAILED; + goto cleanup; + } + + CryptoKeyPlaintext_initKey(&sharedSecret, s_buf, (2U * plen) + 1); + + /* The driver consumes network byte order. Copy this number and reverse them again. */ + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(d, d_buf, plen)); + CryptoKeyPlaintext_initKey(&myPrivateKey, d_buf, plen); + + /* The driver consumes an octet string in network byte order. Copy this + * point and reverse them again. */ + q_buf[0] = 0x04; + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&(Q->X), q_buf + 1, plen)); + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&(Q->Y), q_buf + 1 + plen, plen)); + CryptoKeyPlaintext_initKey(&theirPublicKey, q_buf, (2U * plen) + 1); + + ECDH_OperationComputeSharedSecret_init(&operationComputeSharedSecret); + operationComputeSharedSecret.myPrivateKey = &myPrivateKey; + operationComputeSharedSecret.theirPublicKey = &theirPublicKey; + operationComputeSharedSecret.sharedSecret = &sharedSecret; + + /* Load the ROM curve params */ + switch (grp->id) + { + case MBEDTLS_ECP_DP_SECP224R1: + operationComputeSharedSecret.curve = &ECCParams_NISTP224; + break; + + case MBEDTLS_ECP_DP_SECP256R1: + operationComputeSharedSecret.curve = &ECCParams_NISTP256; + break; + + case MBEDTLS_ECP_DP_SECP384R1: + operationComputeSharedSecret.curve = &ECCParams_NISTP384; + break; + + case MBEDTLS_ECP_DP_SECP521R1: + operationComputeSharedSecret.curve = &ECCParams_NISTP521; + break; + + case MBEDTLS_ECP_DP_BP256R1: + operationComputeSharedSecret.curve = &ECCParams_BrainpoolP256R1; + break; + + case MBEDTLS_ECP_DP_BP384R1: + operationComputeSharedSecret.curve = &ECCParams_BrainpoolP384R1; + break; + + case MBEDTLS_ECP_DP_BP512R1: + operationComputeSharedSecret.curve = &ECCParams_BrainpoolP512R1; + break; + + case MBEDTLS_ECP_DP_CURVE25519: + operationComputeSharedSecret.curve = &ECCParams_Curve25519; + break; + + default: + /* Possible extension to load an arbitrary curve */ + ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + goto cleanup; + } + + if (ECDH_STATUS_SUCCESS == ECDH_computeSharedSecret(handle, &operationComputeSharedSecret)) + { + ret = 0; + } + else + { + ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; + } + + MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(z, s_buf + 1, plen)); + +cleanup: + mbedtls_free(q_buf); + mbedtls_free(d_buf); + mbedtls_free(s_buf); + + if (NULL != handle) + { + ECDH_close(handle); + } + + return (ret); +} + +/* + * Compute shared secret (SEC1 3.3.1) + */ +int mbedtls_ecdh_compute_shared(mbedtls_ecp_group * grp, mbedtls_mpi * z, const mbedtls_ecp_point * Q, const mbedtls_mpi * d, + int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + ECDH_VALIDATE_RET(grp != NULL); + ECDH_VALIDATE_RET(Q != NULL); + ECDH_VALIDATE_RET(d != NULL); + ECDH_VALIDATE_RET(z != NULL); + return (ecdh_compute_shared_restartable(grp, z, Q, d, f_rng, p_rng, NULL)); +} +#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */ + +#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT || MBEDTLS_ECDH_GEN_PUBLIC_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdsa_alt.c b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdsa_alt.c new file mode 100644 index 00000000000000..e6ab92c6b0d483 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecdsa_alt.c @@ -0,0 +1,288 @@ +/* + * + * Copyright (c) 2021 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. + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined MBEDTLS_ECDSA_VERIFY_ALT || defined MBEDTLS_ECDSA_SIGN_ALT + +/* NOTE: The TI drivers consume these points and big numbers in network byte + * order. This is in contrast to the mbedtls_mpi structures which story + * these numbers and points in little endian byte order. This file uses + * the mpi functions to re-write the buffers into network byte order. + */ + +#include + +#include +#include +#include +#include + +#include "ti_drivers_config.h" + +#include +#include +#include + +#ifdef MBEDTLS_ECDSA_VERIFY_ALT + +/* + * Verify ECDSA signature of hashed message + */ +int mbedtls_ecdsa_verify(mbedtls_ecp_group * grp, const unsigned char * buf, size_t blen, const mbedtls_ecp_point * Q, + const mbedtls_mpi * r, const mbedtls_mpi * s) +{ + int ret = 0; + size_t plen = grp->nbits / 8U; + uint8_t * r_buf = (uint8_t *) mbedtls_calloc(1, plen); + uint8_t * s_buf = (uint8_t *) mbedtls_calloc(1, plen); + uint8_t * q_buf = (uint8_t *) mbedtls_calloc(1, (plen * 2U) + 1); + CryptoKey theirPublicKey; + ECDSA_Config config = { 0 }; + ECDSA_Handle handle = NULL; + ECDSA_OperationVerify operationVerify; + ECDSACC26X2_HWAttrs hwAttrs = { 0 }; + ECDSACC26X2_Object object = { 0 }; + + if (NULL == r_buf || NULL == s_buf || NULL == q_buf) + { + ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; + goto cleanup; + } + + hwAttrs.intPriority = (1 << 5); + hwAttrs.trngIntPriority = (1 << 5); + + config.object = (void *) &object; + config.hwAttrs = (void *) &hwAttrs; + + handle = ECDSA_construct(&config, NULL); + + if (NULL == handle) + { + ret = MBEDTLS_ERR_ECP_HW_ACCEL_FAILED; + goto cleanup; + } + + /* The driver consumes an octet string in network byte order. Copy this + * point and reverse them again. */ + q_buf[0] = 0x04; + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&(Q->X), q_buf + 1, plen)); + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&(Q->Y), q_buf + 1 + plen, plen)); + CryptoKeyPlaintext_initKey(&theirPublicKey, q_buf, (2U * plen) + 1); + + /* The driver also consumes the r and s in network byte order. Copy these + * buffers and them reverse them again */ + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(r, r_buf, plen)); + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(s, s_buf, plen)); + + /* prepare the operation */ + ECDSA_OperationVerify_init(&operationVerify); + operationVerify.theirPublicKey = &theirPublicKey; + operationVerify.hash = buf; + operationVerify.r = r_buf; + operationVerify.s = s_buf; + + /* Load the ROM curve params */ + switch (grp->id) + { + case MBEDTLS_ECP_DP_SECP224R1: + operationVerify.curve = &ECCParams_NISTP224; + break; + + case MBEDTLS_ECP_DP_SECP256R1: + operationVerify.curve = &ECCParams_NISTP256; + break; + + case MBEDTLS_ECP_DP_SECP384R1: + operationVerify.curve = &ECCParams_NISTP384; + break; + + case MBEDTLS_ECP_DP_SECP521R1: + operationVerify.curve = &ECCParams_NISTP521; + break; + + case MBEDTLS_ECP_DP_BP256R1: + operationVerify.curve = &ECCParams_BrainpoolP256R1; + break; + + case MBEDTLS_ECP_DP_BP384R1: + operationVerify.curve = &ECCParams_BrainpoolP384R1; + break; + + case MBEDTLS_ECP_DP_BP512R1: + operationVerify.curve = &ECCParams_BrainpoolP512R1; + break; + + case MBEDTLS_ECP_DP_CURVE25519: + operationVerify.curve = &ECCParams_Curve25519; + break; + + default: + /* Possible extension to load an arbitrary curve */ + ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + goto cleanup; + } + + if (ECDSA_STATUS_SUCCESS == ECDSA_verify(handle, &operationVerify)) + { + ret = 0; + } + else + { + ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; + } + +cleanup: + mbedtls_free(r_buf); + mbedtls_free(s_buf); + mbedtls_free(q_buf); + + if (NULL != handle) + { + ECDSA_close(handle); + } + + return ret; +} + +#endif /* MBEDTLS_ECDSA_VERIFY_ALT */ + +#ifdef MBEDTLS_ECDSA_SIGN_ALT + +/* + * Compute ECDSA signature of a hashed message + */ +int mbedtls_ecdsa_sign(mbedtls_ecp_group * grp, mbedtls_mpi * r, mbedtls_mpi * s, const mbedtls_mpi * d, const unsigned char * buf, + size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + int ret = 0; + size_t plen = grp->nbits / 8U; + uint8_t * r_buf = (uint8_t *) mbedtls_calloc(1, plen); + uint8_t * s_buf = (uint8_t *) mbedtls_calloc(1, plen); + uint8_t * d_buf = (uint8_t *) mbedtls_calloc(1, plen); + CryptoKey myPrivateKey; + ECDSA_Config config = { 0 }; + ECDSA_Handle handle = NULL; + ECDSA_OperationSign operationSign; + ECDSACC26X2_HWAttrs hwAttrs = { 0 }; + ECDSACC26X2_Object object = { 0 }; + + if (NULL == r_buf || NULL == s_buf || NULL == d_buf) + { + ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; + goto cleanup; + } + + hwAttrs.intPriority = (1 << 5); + hwAttrs.trngIntPriority = (1 << 5); + + config.object = (void *) &object; + config.hwAttrs = (void *) &hwAttrs; + + handle = ECDSA_construct(&config, NULL); + + if (NULL == handle) + { + ret = MBEDTLS_ERR_ECP_HW_ACCEL_FAILED; + goto cleanup; + } + + /* The driver consumes numbers in network byte order */ + MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(d, d_buf, plen)); + + CryptoKeyPlaintext_initKey(&myPrivateKey, d_buf, plen); + ECDSA_OperationSign_init(&operationSign); + operationSign.myPrivateKey = &myPrivateKey; + operationSign.hash = buf; + operationSign.r = r_buf; + operationSign.s = s_buf; + + /* Load the ROM curve params */ + switch (grp->id) + { + case MBEDTLS_ECP_DP_SECP224R1: + operationSign.curve = &ECCParams_NISTP224; + break; + + case MBEDTLS_ECP_DP_SECP256R1: + operationSign.curve = &ECCParams_NISTP256; + break; + + case MBEDTLS_ECP_DP_SECP384R1: + operationSign.curve = &ECCParams_NISTP384; + break; + + case MBEDTLS_ECP_DP_SECP521R1: + operationSign.curve = &ECCParams_NISTP521; + break; + + case MBEDTLS_ECP_DP_BP256R1: + operationSign.curve = &ECCParams_BrainpoolP256R1; + break; + + case MBEDTLS_ECP_DP_BP384R1: + operationSign.curve = &ECCParams_BrainpoolP384R1; + break; + + case MBEDTLS_ECP_DP_BP512R1: + operationSign.curve = &ECCParams_BrainpoolP512R1; + break; + + case MBEDTLS_ECP_DP_CURVE25519: + operationSign.curve = &ECCParams_Curve25519; + break; + + default: + /* Possible extension to load an arbitrary curve */ + ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + goto cleanup; + } + + if (ECDSA_STATUS_SUCCESS == ECDSA_sign(handle, &operationSign)) + { + ret = 0; + } + else + { + ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; + } + + /* The driver produces r and s in network byte order. copy into mbedtls mpi + * format. This incurs an extra byte reversal when written to ASN1. */ + MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(r, r_buf, plen)); + MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(s, s_buf, plen)); + +cleanup: + mbedtls_free(r_buf); + mbedtls_free(s_buf); + mbedtls_free(d_buf); + + if (NULL != handle) + { + ECDSA_close(handle); + } + + return ret; +} +#endif /* MBEDTLS_ECDSA_SIGN_ALT */ + +#endif /* defined MBEDTLS_ECDSA_VERIFY_ALT || defined MBEDTLS_ECDSA_SIGN_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.c b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.c new file mode 100644 index 00000000000000..84b60b0f92c347 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.c @@ -0,0 +1,900 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * + * 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. + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "mbedtls/ecjpake.h" + +#if defined(MBEDTLS_ECJPAKE_ALT) +#include "ecjpake_alt.h" + +#include + +#include "ti_drivers_config.h" + +#include +#include + +/* + * NOTE: On calling convention in this file. + * + * Many of the helper functions in this file take a pointer to a `uint8_t*`, + * usually called `p`. This is the current working pointer for the input or + * output buffer. They will also take a pointer to a `uint8_t`, usually called + * `end`. This is the pointer to the end of the current working buffer. The + * difference between these two pointers is calculated and used as the current + * available length of the working buffer. This is checked before anything is + * written to or read from the buffer. While values are read or written to the + * data at the pointer pointed at by `p`, the pointer pointed at by `p` is + * updated to point to the next available value. The callee updates the value + * of `p` for the caller, almost in the same fashion as strtok. + * + * Here is an example: + * ``` + * static int read_be_uint16(const uint8_t **p, + * const uint8_t *end, + * uint16_t *value) + * { + * if ((end < *p) || (end - *p < sizeof(uint16_t))) + * { + * return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL); + * } + * *value = ((uint16_t)(*p)[0] << 8) | (*p)[1]); + * return (0); + * } + * + * void sample_func(void) + * { + * uint8_t buffer[4] = {0x01, 0x02, 0x03, 0x04}; + * uint8_t* p = buffer + sizeof(buffer); + * uint8_t* end = buffer + sizeof(buffer); + * uint16_t value; + * + * read_be_uint16(&p, end, &value); + * // value is now 0x0102 + * // p points to buffer[2] + * read_be_uint16(&p, end, &value); + * // value is now 0x0304 + * // p points to buffer[4] (invalid) + * } + */ + +/* + * Convert a mbedtls_ecjpake_role to identifier string. + * + * depends on the value of the enumeration of mbedtls_ecjpake_role. + */ +static const char * const ecjpake_id[] = { "client", "server" }; + +#define ID_MINE (ecjpake_id[ctx->role]) +#define ID_PEER (ecjpake_id[1 - ctx->role]) + +/* + * Size of the temporary buffer for ecjpake_hash: + * 3 EC points plus their length, plus ID and its length (4 + 6 bytes) + */ +#define ECJPAKE_HASH_BUF_LEN (3 * (4 + MBEDTLS_ECP_MAX_PT_LEN) + 4 + 6) + +/** + * \breif execute the contents of this macro, save the return in + * `ret` and goto `cleanup` if it is not `0` + * + * The internal functions of this file driver are designed to return `0` on + * success. The caller is expected to have an `int ret` in the translation unit + * of the call-site, and a target `cleanup`. It is common practice to return + * `ret` in the caller. + * + * ``` + * int example_func(void) + * { + * int ret; + * ECJPAKE_ALT_CHK(some_func()); + * + * some_other_func(); + * + * cleanup: + * return ret; + * } + * ``` + * + * \param f code to execute + */ +#define ECJPAKE_ALT_CHK(f) \ + do \ + { \ + if ((ret = f) != 0) \ + goto cleanup; \ + } while (0) + +/** + * \brief writes a buffer prepended with a length byte + * + * \param p pointer to output buffer, will be changed by a successful + * call + * \param end pointer to the end of the output buffer + * \param key the CryptoKey to write + * \param bin the source to copy + * \param len the length to copy and write + * + * \return 0 if successful, + * a negative error code otherwise + * + * \retval MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * the input buffer is too small + */ +static int tls_write_binary(uint8_t ** p, const uint8_t * end, const uint8_t * bin, size_t len) +{ + if ((end < *p) || ((size_t)(end - *p) < 1 + len)) + { + return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL); + } + + /* write the length to the buffer */ + (*p)[0] = len; + *p += 1; + + /* write the binary data as is */ + memcpy(*p, bin, len); + *p += len; + + return (0); +} + +/** + * \brief read a binary value prepended by a length bit + * + * \param p pointer to input buffer, will be changed by a successful + * call + * \param end pointer to the end of the input buffer + * \param bin the array to fill + * \param len the size of \p bin + * + * \return 0 if successful, + * a negative error code otherwise + * + * \retval MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * the input buffer is too small + */ +static int tls_read_binary(const uint8_t ** p, const uint8_t * end, uint8_t * bin, size_t len) +{ + uint8_t data_len; + + /* length byte plus the length of the crypto key */ + if ((end < *p) || ((size_t)(end - *p) < 1 + len)) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + + /* read the length byte */ + data_len = (*p)[0]; + *p += 1; + /* check the length matches */ + if (data_len != len) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + + memcpy(bin, *p, len); + + *p += len; + + return (0); +} + +/** + * \brief writes a tls point into a CryptoKey + * + * \param p pointer to output buffer, will be changed by a successful + * call + * \param end pointer to the end of the output buffer + * \param key the CryptoKey to write + * + * \return 0 if successful, + * a negative error code otherwise + */ +static int tls_write_crypto_key(uint8_t ** p, const uint8_t * end, CryptoKey * key) +{ + return tls_write_binary(p, end, key->u.plaintext.keyMaterial, key->u.plaintext.keyLength); +} + +/** + * \brief read a tls point into a CryptoKey + * + * \param p pointer to input buffer, will be changed by a successful + * call + * \param end pointer to the end of the input buffer + * \param key the CryptoKey to fill + * + * \return 0 if successful, + * a negative error code otherwise + * + * \retval MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * the input buffer is too small + * \retval MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE + * the point is not in uncompressed form + */ +static int tls_read_crypto_key(const uint8_t ** p, const uint8_t * end, CryptoKey * key) +{ + /* check that the point is uncompressed */ + if ((end < *p) || (end - *p < 2)) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + if ((*p)[1] != 0x04) + { + return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE); + } + + return tls_read_binary(p, end, key->u.plaintext.keyMaterial, key->u.plaintext.keyLength); +} + +/** + * \brief write the curve info into the buffer + * + * \param p pointer to output buffer, will be changed by a successful + * call + * \param end pointer to the end of the output buffer + * \param group_id the mbedtls group id write + * + * \return 0 if successful, + * a negative error code otherwise + * + * \retval MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * the input buffer is too small + * \retval MBEDTLS_ERR_ECP_BAD_INPUT_DATA + * the group id did not name a valid curve + */ +static int tls_write_curve_info(uint8_t ** p, const uint8_t * end, mbedtls_ecp_group_id group_id) +{ + const mbedtls_ecp_curve_info * curve_info; + + if ((end < *p) || (end - *p < 3)) + { + return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL); + } + + curve_info = mbedtls_ecp_curve_info_from_grp_id(group_id); + + if (NULL == curve_info) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + + /* write that we use named curves */ + (*p)[0] = MBEDTLS_ECP_TLS_NAMED_CURVE; + (*p)[1] = curve_info->tls_id >> 8; + (*p)[2] = curve_info->tls_id & 0xFF; + *p += 3; + + return (0); +} + +/** + * \brief read and verify the curve info from the buffer + * + * \param p pointer to input buffer, will be changed by a successful + * call + * \param end pointer to the end of the input buffer + * \param group_id the mbedtls group id to load to check a match + * + * \return 0 if successful, + * a negative error code otherwise + * + * \retval MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL + * the input buffer is too small + * \retval MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE + * the tls curve identifiers do not match + * \retval MBEDTLS_ERR_ECP_BAD_INPUT_DATA + * the curve info was not for a named curve or we do not have + * that named curve + */ +static int tls_verify_curve_info(const uint8_t ** p, const uint8_t * end, mbedtls_ecp_group_id group_id) +{ + uint16_t curve_name_id; + const mbedtls_ecp_curve_info * curve_info; + + if ((end < *p) || (end - *p < 3)) + { + return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL); + } + + if ((*p)[0] != MBEDTLS_ECP_TLS_NAMED_CURVE) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + curve_name_id = (((uint16_t)(*p)[1] << 8)) | (((uint16_t)(*p)[2])); + *p += 3; + + curve_info = mbedtls_ecp_curve_info_from_grp_id(group_id); + + if (NULL == curve_info) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + + if (curve_name_id != curve_info->tls_id) + { + return (MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE); + } + + return (0); +} + +/** + * \brief Fill the a point with a random function + * + * \param private_key + * key to fill with random data + * \param f_rng random number function + * \param p_rng context for the random function + * + * \return 0 if successful, + * a negative error code otherwise + */ +static int gen_private_key(unsigned char * private_key, int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + unsigned int i; + unsigned int j = 0; + unsigned int sum = 0U; + + do + { + unsigned int * pkey = (unsigned int *) private_key; + f_rng(p_rng, private_key, NISTP256_CURVE_LENGTH_BYTES); + + /* check if private_key is equal to zero */ + for (i = 0; i < (NISTP256_CURVE_LENGTH_BYTES / sizeof(unsigned int)); i++) + { + sum |= pkey[i]; + } + j++; + } while (0U == sum && (j < 3)); + + return (0U != sum ? 0 : -1); +} + +/** + * \brief Generate the second round of keys for this node and peer + * + * \param ctx Context to use + * + * \return 0 if successful, + * a negative error code otherwise + */ +static int ecjpake_alt_generate_round2_keys(mbedtls_ecjpake_context * ctx) +{ + ECJPAKE_OperationRoundTwoGenerateKeys roundTwoGenerateKeys; + int ret; + + if (ctx->roundTwoGenerated) + { + return (0); + } + + ECJPAKE_OperationRoundTwoGenerateKeys_init(&roundTwoGenerateKeys); + roundTwoGenerateKeys.curve = &ECCParams_NISTP256; + roundTwoGenerateKeys.myPrivateKey2 = &ctx->myPrivateCryptoKey2; + roundTwoGenerateKeys.myPublicKey1 = &ctx->myPublicCryptoKey1; + roundTwoGenerateKeys.myPublicKey2 = &ctx->myPublicCryptoKey2; + roundTwoGenerateKeys.theirPublicKey1 = &ctx->theirPublicCryptoKey1; + roundTwoGenerateKeys.theirPublicKey2 = &ctx->theirPublicCryptoKey2; + roundTwoGenerateKeys.preSharedSecret = &ctx->preSharedSecretCryptoKey; + roundTwoGenerateKeys.theirNewGenerator = &ctx->theirGeneratorKey; + roundTwoGenerateKeys.myNewGenerator = &ctx->myGeneratorKey; + roundTwoGenerateKeys.myCombinedPrivateKey = &ctx->myCombinedPrivateKey; + roundTwoGenerateKeys.myCombinedPublicKey = &ctx->myCombinedPublicKey; + roundTwoGenerateKeys.myPrivateV = &ctx->myPrivateCryptoV3; + roundTwoGenerateKeys.myPublicV = &ctx->myPublicCryptoV3; + + ECJPAKE_ALT_CHK(ECJPAKE_roundTwoGenerateKeys(ctx->handle, &roundTwoGenerateKeys)); + + ctx->roundTwoGenerated = true; + +cleanup: + return (ret); +} + +void mbedtls_ecjpake_init(mbedtls_ecjpake_context * ctx) +{ + ECJPAKE_Params params; + + if (ctx == NULL) + { + return; + } + + ctx->md_info = NULL; + ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED; + + ECJPAKE_Params_init(¶ms); + + ctx->handle = ECJPAKE_open(0, ¶ms); +} + +void mbedtls_ecjpake_free(mbedtls_ecjpake_context * ctx) +{ + if (ctx == NULL) + { + return; + } + + ctx->md_info = NULL; + + ECJPAKE_close(ctx->handle); + ctx->handle = NULL; +} + +static void big_num_reverse(uint8_t * arr, size_t len) +{ + unsigned int left = 0; + unsigned int right = len - 1; + uint8_t temp; + + while (left < right) + { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + + ++left; + --right; + } +} + +/** + * \brief write a 4 byte length and binary output + * + * \param p pointer to output buffer, will be changed by a successful + * call + * \param end pointer to the end of the output buffer + * \param bin value to write + * \param len length to write + * + * \return 0 if successful, + * a negative error code otherwise + */ +static int ecjpake_write_len_binary(uint8_t ** p, const uint8_t * end, const uint8_t * bin, size_t len) +{ + if ((end < *p) || ((size_t)(end - *p) < 4 + len)) + { + return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL); + } + + memcpy(*p + 4, bin, len); + + (*p)[0] = (unsigned char) ((len >> 24) & 0xFF); + (*p)[1] = (unsigned char) ((len >> 16) & 0xFF); + (*p)[2] = (unsigned char) ((len >> 8) & 0xFF); + (*p)[3] = (unsigned char) ((len) &0xFF); + + *p += 4 + len; + + return (0); +} + +/** + * \brief Create the EC-JPAKE hash for each round + * + * \param md_info message digest info to use + * \param G 1st point to digest + * \param V 2nd point to digest + * \param X 3rd point to digest + * \param id string id to digest + * \param hash output buffer for digest + * + * \return 0 if successful, + * a negative error code otherwise + */ +static int ecjpake_hash(const mbedtls_md_info_t * md_info, CryptoKey * G, CryptoKey * V, CryptoKey * X, const char * id, + uint8_t * hash) +{ + int ret; + uint8_t buf[ECJPAKE_HASH_BUF_LEN]; + uint8_t * p = buf; + const uint8_t * end = buf + sizeof(buf); + const size_t id_len = strlen(id); + + /* + * Write 'lenG || G || lenV || V || lenX || X || lenID || ID' to the + * temporary buffer + */ + ECJPAKE_ALT_CHK(ecjpake_write_len_binary(&p, end, G->u.plaintext.keyMaterial, G->u.plaintext.keyLength)); + ECJPAKE_ALT_CHK(ecjpake_write_len_binary(&p, end, V->u.plaintext.keyMaterial, V->u.plaintext.keyLength)); + ECJPAKE_ALT_CHK(ecjpake_write_len_binary(&p, end, X->u.plaintext.keyMaterial, X->u.plaintext.keyLength)); + ECJPAKE_ALT_CHK(ecjpake_write_len_binary(&p, end, (uint8_t *) id, id_len)); + + /* + * Compute hash + * + * XXX: possible speedup by digesting the buffers directly instead of + * creating a temp buffer + */ + ECJPAKE_ALT_CHK(mbedtls_md(md_info, buf, p - buf, hash)); + +cleanup: + return (ret); +} + +/** + * \brief Read and validate the ZKP based on this public key. + * + * \param ctx Context to use + * \param generator_key + * Generator point to use + * \param public_key + * Public key use + * \param p Pointer to current place in buffer, will point to the next + * character after a successful call + * \param end Pointer to the end of the buffer + * + * \return 0 if successful, + * a negative error code otherwise + */ +static int ecjpake_zkp_read(mbedtls_ecjpake_context * ctx, CryptoKey * generator_key, CryptoKey * public_key, const uint8_t ** p, + const uint8_t * end) +{ + int ret; + CryptoKey v; + uint8_t v_material[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + uint8_t r[NISTP256_CURVE_LENGTH_BYTES]; + uint8_t hash[NISTP256_CURVE_LENGTH_BYTES]; + + ECJPAKE_OperationVerifyZKP operation_verify_zkp; + + CryptoKeyPlaintext_initKey(&v, v_material, sizeof(v_material)); + + /* read the Ephemeral public key V */ + ECJPAKE_ALT_CHK(tls_read_crypto_key(p, end, &v)); + + /* read the Schnorr signature r */ + ECJPAKE_ALT_CHK(tls_read_binary(p, end, r, sizeof(r))); + + /* calculate the hash */ + ECJPAKE_ALT_CHK(ecjpake_hash(ctx->md_info, generator_key, &v, public_key, ID_PEER, hash)); + + /* verify the r and hash based on V */ + ECJPAKE_OperationVerifyZKP_init(&operation_verify_zkp); + operation_verify_zkp.curve = &ECCParams_NISTP256; + operation_verify_zkp.theirGenerator = generator_key; + operation_verify_zkp.theirPublicKey = public_key; + operation_verify_zkp.theirPublicV = &v; + operation_verify_zkp.hash = hash; + operation_verify_zkp.r = r; + + ECJPAKE_ALT_CHK(ECJPAKE_verifyZKP(ctx->handle, &operation_verify_zkp)); + +cleanup: + return (ret); +} + +/** + * \brief Check if a CryptoKey is zero + * + * \param G CryptoKey to use + * + * \return 0 CryptoKey is not zero + * MBEDTLS_ERR_ECP_INVALID_KEY if CryptoKey is zero + */ +static int check_CryptoKey_is_zero(CryptoKey * G) +{ + unsigned int i; + /* skip beginning 0x04 byte */ + for (i = 1; i < G->u.plaintext.keyLength; i++) + { + if (G->u.plaintext.keyMaterial[i] != 0U) + { + /* the point is not all zero */ + return (0); + } + } + /* the for loop completed, they were all zero */ + return (MBEDTLS_ERR_ECP_INVALID_KEY); +} + +int mbedtls_ecjpake_setup(mbedtls_ecjpake_context * ctx, mbedtls_ecjpake_role role, mbedtls_md_type_t hash, + mbedtls_ecp_group_id curve, const uint8_t * secret, size_t len) +{ + int ret = 0; + + ctx->roundTwoGenerated = false; + ctx->role = role; + + if ((ctx->md_info = mbedtls_md_info_from_type(hash)) == NULL) + { + return (MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE); + } + + ctx->curve = curve; + + /* copy NISTP256 generator for hash functions */ + ctx->nistP256Generator[0] = 0x04; + memcpy(&(ctx->nistP256Generator[1]), ECCParams_NISTP256.generatorX, (NISTP256_CURVE_LENGTH_BYTES * 2)); + big_num_reverse(&(ctx->nistP256Generator[1]), NISTP256_CURVE_LENGTH_BYTES); + big_num_reverse(&(ctx->nistP256Generator[NISTP256_CURVE_LENGTH_BYTES + 1]), NISTP256_CURVE_LENGTH_BYTES); + CryptoKeyPlaintext_initKey(&ctx->nistP256GeneratorCryptoKey, ctx->nistP256Generator, sizeof(ctx->nistP256Generator)); + + /* Pre-shared secret */ + memcpy(ctx->preSharedSecretKeyingMaterial, secret, len); + + CryptoKeyPlaintext_initKey(&ctx->preSharedSecretCryptoKey, ctx->preSharedSecretKeyingMaterial, len); + + CryptoKeyPlaintext_initKey(&ctx->myPrivateCryptoKey1, ctx->myPrivateKeyMaterial1, sizeof(ctx->myPrivateKeyMaterial1)); + CryptoKeyPlaintext_initKey(&ctx->myPrivateCryptoKey2, ctx->myPrivateKeyMaterial2, sizeof(ctx->myPrivateKeyMaterial2)); + CryptoKeyPlaintext_initKey(&ctx->myPrivateCryptoV1, ctx->myPrivateVMaterial1, sizeof(ctx->myPrivateVMaterial1)); + CryptoKeyPlaintext_initKey(&ctx->myPrivateCryptoV2, ctx->myPrivateVMaterial2, sizeof(ctx->myPrivateVMaterial2)); + CryptoKeyPlaintext_initKey(&ctx->myPrivateCryptoV3, ctx->myPrivateVMaterial3, sizeof(ctx->myPrivateVMaterial3)); + + CryptoKeyPlaintext_initBlankKey(&ctx->myPublicCryptoKey1, ctx->myPublicKeyMaterial1, sizeof(ctx->myPublicKeyMaterial1)); + CryptoKeyPlaintext_initBlankKey(&ctx->myPublicCryptoKey2, ctx->myPublicKeyMaterial2, sizeof(ctx->myPublicKeyMaterial2)); + CryptoKeyPlaintext_initBlankKey(&ctx->myPublicCryptoV1, ctx->myPublicVMaterial1, sizeof(ctx->myPublicVMaterial1)); + CryptoKeyPlaintext_initBlankKey(&ctx->myPublicCryptoV2, ctx->myPublicVMaterial2, sizeof(ctx->myPublicVMaterial2)); + CryptoKeyPlaintext_initBlankKey(&ctx->myPublicCryptoV3, ctx->myPublicVMaterial3, sizeof(ctx->myPublicVMaterial3)); + CryptoKeyPlaintext_initBlankKey(&ctx->myCombinedPrivateKey, ctx->myCombinedPrivateKeyMaterial1, + sizeof(ctx->myCombinedPrivateKeyMaterial1)); + CryptoKeyPlaintext_initBlankKey(&ctx->myCombinedPublicKey, ctx->myCombinedPublicKeyMaterial1, + sizeof(ctx->myCombinedPublicKeyMaterial1)); + CryptoKeyPlaintext_initBlankKey(&ctx->myGeneratorKey, ctx->myGenerator, sizeof(ctx->myGenerator)); + + CryptoKeyPlaintext_initBlankKey(&ctx->theirPublicCryptoKey1, ctx->theirPublicKeyMaterial1, + sizeof(ctx->theirPublicKeyMaterial1)); + CryptoKeyPlaintext_initBlankKey(&ctx->theirPublicCryptoKey2, ctx->theirPublicKeyMaterial2, + sizeof(ctx->theirPublicKeyMaterial2)); + CryptoKeyPlaintext_initBlankKey(&ctx->theirCombinedPublicKey, ctx->theirCombinedPublicKeyMaterial1, + sizeof(ctx->theirCombinedPublicKeyMaterial1)); + CryptoKeyPlaintext_initBlankKey(&ctx->theirGeneratorKey, ctx->theirGenerator, sizeof(ctx->theirGenerator)); + + return (ret); +} + +int mbedtls_ecjpake_check(const mbedtls_ecjpake_context * ctx) +{ + if (ctx->md_info == NULL || ctx->curve == MBEDTLS_ECP_DP_NONE || ctx->handle == NULL) + { + return (MBEDTLS_ERR_ECP_BAD_INPUT_DATA); + } + + return (0); +} + +int mbedtls_ecjpake_read_round_one(mbedtls_ecjpake_context * ctx, const unsigned char * buf, size_t len) +{ + int ret; + const unsigned char * p = buf; + const unsigned char * end = buf + len; + + /* read their combined key material (Xc or Xs) */ + ECJPAKE_ALT_CHK(tls_read_crypto_key(&p, end, &ctx->theirPublicCryptoKey1)); + + /* verify that the point is not zero */ + ECJPAKE_ALT_CHK(check_CryptoKey_is_zero(&ctx->theirPublicCryptoKey1)); + + /* verify the proof (ZKP(Xc) or ZKP(Xs)) */ + ECJPAKE_ALT_CHK(ecjpake_zkp_read(ctx, &ctx->nistP256GeneratorCryptoKey, &ctx->theirPublicCryptoKey1, &p, end)); + + /* read their combined key material (Xc or Xs) */ + ECJPAKE_ALT_CHK(tls_read_crypto_key(&p, end, &ctx->theirPublicCryptoKey2)); + + /* verify that the point is not zero */ + ECJPAKE_ALT_CHK(check_CryptoKey_is_zero(&ctx->theirPublicCryptoKey2)); + + /* verify the proof (ZKP(Xc) or ZKP(Xs)) */ + ECJPAKE_ALT_CHK(ecjpake_zkp_read(ctx, &ctx->nistP256GeneratorCryptoKey, &ctx->theirPublicCryptoKey2, &p, end)); + +cleanup: + return (ret); +} + +int mbedtls_ecjpake_write_round_one(mbedtls_ecjpake_context * ctx, uint8_t * buf, size_t len, size_t * olen, + int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + int ret; + uint8_t * p = buf; + const uint8_t * end = buf + len; + uint8_t hash[NISTP256_CURVE_LENGTH_BYTES]; + uint8_t r[NISTP256_CURVE_LENGTH_BYTES]; + + /* Generate round one keys */ + ECJPAKE_OperationRoundOneGenerateKeys roundOneGenerateKeys; + ECJPAKE_OperationGenerateZKP operationGenerateZKP; + + /* Generate private keys */ + ECJPAKE_ALT_CHK(gen_private_key(ctx->myPrivateKeyMaterial1, f_rng, p_rng)); + ECJPAKE_ALT_CHK(gen_private_key(ctx->myPrivateKeyMaterial2, f_rng, p_rng)); + ECJPAKE_ALT_CHK(gen_private_key(ctx->myPrivateVMaterial1, f_rng, p_rng)); + ECJPAKE_ALT_CHK(gen_private_key(ctx->myPrivateVMaterial2, f_rng, p_rng)); + ECJPAKE_ALT_CHK(gen_private_key(ctx->myPrivateVMaterial3, f_rng, p_rng)); + + ECJPAKE_OperationRoundOneGenerateKeys_init(&roundOneGenerateKeys); + roundOneGenerateKeys.curve = &ECCParams_NISTP256; + roundOneGenerateKeys.myPrivateKey1 = &ctx->myPrivateCryptoKey1; + roundOneGenerateKeys.myPrivateKey2 = &ctx->myPrivateCryptoKey2; + roundOneGenerateKeys.myPublicKey1 = &ctx->myPublicCryptoKey1; + roundOneGenerateKeys.myPublicKey2 = &ctx->myPublicCryptoKey2; + roundOneGenerateKeys.myPrivateV1 = &ctx->myPrivateCryptoV1; + roundOneGenerateKeys.myPrivateV2 = &ctx->myPrivateCryptoV2; + roundOneGenerateKeys.myPublicV1 = &ctx->myPublicCryptoV1; + roundOneGenerateKeys.myPublicV2 = &ctx->myPublicCryptoV2; + + ECJPAKE_ALT_CHK(ECJPAKE_roundOneGenerateKeys(ctx->handle, &roundOneGenerateKeys)); + + /* write X1 */ + ECJPAKE_ALT_CHK(tls_write_crypto_key(&p, end, &ctx->myPublicCryptoKey1)); + + ECJPAKE_ALT_CHK(ecjpake_hash(ctx->md_info, &ctx->nistP256GeneratorCryptoKey, &ctx->myPublicCryptoV1, &ctx->myPublicCryptoKey1, + ID_MINE, hash)); + + /* generate round one ZKPs */ + ECJPAKE_OperationGenerateZKP_init(&operationGenerateZKP); + operationGenerateZKP.curve = &ECCParams_NISTP256; + operationGenerateZKP.myPrivateKey = &ctx->myPrivateCryptoKey1; + operationGenerateZKP.myPrivateV = &ctx->myPrivateCryptoV1; + operationGenerateZKP.hash = hash; + operationGenerateZKP.r = r; + + ECJPAKE_ALT_CHK(ECJPAKE_generateZKP(ctx->handle, &operationGenerateZKP)); + + /* write ZKP for X1 (V1 and r1) */ + ECJPAKE_ALT_CHK(tls_write_crypto_key(&p, end, &ctx->myPublicCryptoV1)); + + /* write r */ + ECJPAKE_ALT_CHK(tls_write_binary(&p, end, r, NISTP256_CURVE_LENGTH_BYTES)); + + ECJPAKE_ALT_CHK(ecjpake_hash(ctx->md_info, &ctx->nistP256GeneratorCryptoKey, &ctx->myPublicCryptoV2, &ctx->myPublicCryptoKey2, + ID_MINE, hash)); + + ECJPAKE_OperationGenerateZKP_init(&operationGenerateZKP); + operationGenerateZKP.curve = &ECCParams_NISTP256; + operationGenerateZKP.myPrivateKey = &ctx->myPrivateCryptoKey2; + operationGenerateZKP.myPrivateV = &ctx->myPrivateCryptoV2; + operationGenerateZKP.hash = hash; + operationGenerateZKP.r = r; + + ECJPAKE_ALT_CHK(ECJPAKE_generateZKP(ctx->handle, &operationGenerateZKP)); + + /* write X2 */ + ECJPAKE_ALT_CHK(tls_write_crypto_key(&p, end, &ctx->myPublicCryptoKey2)); + + /* write ZKP for X2 */ + ECJPAKE_ALT_CHK(tls_write_crypto_key(&p, end, &ctx->myPublicCryptoV2)); + + /* write r */ + ECJPAKE_ALT_CHK(tls_write_binary(&p, end, r, NISTP256_CURVE_LENGTH_BYTES)); + + *olen = p - buf; + +cleanup: + return (ret); +} + +int mbedtls_ecjpake_read_round_two(mbedtls_ecjpake_context * ctx, const unsigned char * buf, size_t len) +{ + int ret; + const uint8_t * p = buf; + const uint8_t * end = buf + len; + + ECJPAKE_ALT_CHK(ecjpake_alt_generate_round2_keys(ctx)); + + if (ctx->role == MBEDTLS_ECJPAKE_CLIENT) + { + ECJPAKE_ALT_CHK(tls_verify_curve_info(&p, end, ctx->curve)); + } + + /* read their combined key material (Xc or Xs) */ + ECJPAKE_ALT_CHK(tls_read_crypto_key(&p, end, &ctx->theirCombinedPublicKey)); + + /* verify that the point is not zero */ + ECJPAKE_ALT_CHK(check_CryptoKey_is_zero(&ctx->theirCombinedPublicKey)); + + /* verify the proof (ZKP(Xc) or ZKP(Xs)) */ + ECJPAKE_ALT_CHK(ecjpake_zkp_read(ctx, &ctx->theirGeneratorKey, &ctx->theirCombinedPublicKey, &p, end)); + +cleanup: + return (ret); +} + +int mbedtls_ecjpake_write_round_two(mbedtls_ecjpake_context * ctx, unsigned char * buf, size_t len, size_t * olen, + int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + int ret; + uint8_t hash[NISTP256_CURVE_LENGTH_BYTES]; + uint8_t r[NISTP256_CURVE_LENGTH_BYTES]; + uint8_t * p = buf; + const uint8_t * end = buf + len; + + ECJPAKE_OperationGenerateZKP operationGenerateZKP; + + ECJPAKE_ALT_CHK(ecjpake_alt_generate_round2_keys(ctx)); + + ECJPAKE_ALT_CHK( + ecjpake_hash(ctx->md_info, &ctx->myGeneratorKey, &ctx->myPublicCryptoV3, &ctx->myCombinedPublicKey, ID_MINE, hash)); + + ECJPAKE_OperationGenerateZKP_init(&operationGenerateZKP); + operationGenerateZKP.curve = &ECCParams_NISTP256; + operationGenerateZKP.myPrivateKey = &ctx->myCombinedPrivateKey; + operationGenerateZKP.myPrivateV = &ctx->myPrivateCryptoV3; + operationGenerateZKP.hash = hash; + operationGenerateZKP.r = r; + + ECJPAKE_ALT_CHK(ECJPAKE_generateZKP(ctx->handle, &operationGenerateZKP)); + + if (ctx->role == MBEDTLS_ECJPAKE_SERVER) + { + /* write curve info */ + ECJPAKE_ALT_CHK(tls_write_curve_info(&p, end, ctx->curve)); + } + + /* write public key X */ + ECJPAKE_ALT_CHK(tls_write_crypto_key(&p, end, &ctx->myCombinedPublicKey)); + + /* write ZKP for X (V and r) */ + ECJPAKE_ALT_CHK(tls_write_crypto_key(&p, end, &ctx->myPublicCryptoV3)); + + /* write r */ + ECJPAKE_ALT_CHK(tls_write_binary(&p, end, r, NISTP256_CURVE_LENGTH_BYTES)); + + *olen = p - buf; + +cleanup: + return (ret); +} + +int mbedtls_ecjpake_derive_secret(mbedtls_ecjpake_context * ctx, unsigned char * buf, size_t len, size_t * olen, + int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) +{ + int ret; + unsigned char md_len; + CryptoKey sharedSecretCryptoKey; + uint8_t sharedSecretKeyingMaterial1[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + + ECJPAKE_OperationComputeSharedSecret computeSharedSecret; + + md_len = mbedtls_md_get_size(ctx->md_info); + if (len < md_len) + { + return (MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL); + } + + CryptoKeyPlaintext_initKey(&sharedSecretCryptoKey, sharedSecretKeyingMaterial1, sizeof(sharedSecretKeyingMaterial1)); + + /* Generate shared secret */ + ECJPAKE_OperationComputeSharedSecret_init(&computeSharedSecret); + computeSharedSecret.curve = &ECCParams_NISTP256; + computeSharedSecret.myCombinedPrivateKey = &ctx->myCombinedPrivateKey; + computeSharedSecret.theirCombinedPublicKey = &ctx->theirCombinedPublicKey; + computeSharedSecret.theirPublicKey2 = &ctx->theirPublicCryptoKey2; + computeSharedSecret.myPrivateKey2 = &ctx->myPrivateCryptoKey2; + computeSharedSecret.sharedSecret = &sharedSecretCryptoKey; + + ECJPAKE_ALT_CHK(ECJPAKE_computeSharedSecret(ctx->handle, &computeSharedSecret)); + + ECJPAKE_ALT_CHK(mbedtls_md(ctx->md_info, sharedSecretKeyingMaterial1 + 1, NISTP256_CURVE_LENGTH_BYTES, buf)); + + *olen = md_len; + +cleanup: + return (ret); +} + +#undef ID_MINE +#undef ID_PEER + +#endif /* MBEDTLS_ECJPAKE_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.h b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.h new file mode 100644 index 00000000000000..9104b1a47e0489 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/ecjpake_alt.h @@ -0,0 +1,119 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#pragma once + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls-config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_ECJPAKE_ALT) + +#include "mbedtls/ecp.h" +#include "mbedtls/md.h" + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Length of parameters for the NIST p256r1. + * + * ECJ-PAKE is only defined for p256r1 + */ +#define NISTP256_CURVE_LENGTH_BYTES (32) + +/** + * Size in bytes of the identifier at the beginning of the point format + */ +#define OCTET_STRING_OFFSET 1 + +/** + * Size in bytes of a point expressed in the TLS point format + * + * id_byte || X coord || Y coord + */ +#define NISTP256_PUBLIC_KEY_LENGTH_BYTES (OCTET_STRING_OFFSET + (NISTP256_CURVE_LENGTH_BYTES * 2)) + +/** + * EC J-PAKE context structure. + */ +typedef struct +{ + const mbedtls_md_info_t * md_info; + mbedtls_ecp_group_id curve; + mbedtls_ecjpake_role role; + int point_format; + + bool roundTwoGenerated; + /* + * XXX: possible size reduction by moving ephemeral material to round + * calculations. + */ + unsigned char myPrivateKeyMaterial1[NISTP256_CURVE_LENGTH_BYTES]; + unsigned char myPrivateKeyMaterial2[NISTP256_CURVE_LENGTH_BYTES]; + unsigned char myPrivateVMaterial1[NISTP256_CURVE_LENGTH_BYTES]; + unsigned char myPrivateVMaterial2[NISTP256_CURVE_LENGTH_BYTES]; + unsigned char myPrivateVMaterial3[NISTP256_CURVE_LENGTH_BYTES]; + unsigned char myPublicKeyMaterial1[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myPublicKeyMaterial2[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myPublicVMaterial1[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myPublicVMaterial2[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myPublicVMaterial3[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myCombinedPublicKeyMaterial1[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myCombinedPrivateKeyMaterial1[NISTP256_CURVE_LENGTH_BYTES]; + unsigned char nistP256Generator[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char myGenerator[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char theirPublicKeyMaterial1[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char theirPublicKeyMaterial2[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char theirCombinedPublicKeyMaterial1[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char theirGenerator[NISTP256_PUBLIC_KEY_LENGTH_BYTES]; + unsigned char preSharedSecretKeyingMaterial[NISTP256_CURVE_LENGTH_BYTES]; + + CryptoKey nistP256GeneratorCryptoKey; + CryptoKey preSharedSecretCryptoKey; + CryptoKey myPrivateCryptoKey1; + CryptoKey myPrivateCryptoKey2; + CryptoKey myPrivateCryptoV1; + CryptoKey myPrivateCryptoV2; + CryptoKey myPrivateCryptoV3; + CryptoKey myCombinedPrivateKey; + CryptoKey myPublicCryptoKey1; + CryptoKey myPublicCryptoKey2; + CryptoKey myPublicCryptoV1; + CryptoKey myPublicCryptoV2; + CryptoKey myPublicCryptoV3; + CryptoKey myCombinedPublicKey; + CryptoKey myGeneratorKey; + CryptoKey theirPublicCryptoKey1; + CryptoKey theirPublicCryptoKey2; + CryptoKey theirCombinedPublicKey; + CryptoKey theirGeneratorKey; + + ECJPAKE_Handle handle; +} mbedtls_ecjpake_context; + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_ECJPAKE_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.c b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.c new file mode 100644 index 00000000000000..5adc0c8f3da9fa --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.c @@ -0,0 +1,192 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#if defined(MBEDTLS_SHA256_ALT) + +#include + +#include +#include + +/*! + * Hardware-specific configuration attributes, may be replaced with SysConfig + * ti_drivers.h structure. + */ +const SHA2CC26X2_HWAttrs sha2CC26X2HWAttrs_sha = { + .intPriority = ~0, +}; + +void mbedtls_sha256_init(mbedtls_sha256_context * ctx) +{ + SHA2_Params sha2Params; + + memset(ctx, 0, sizeof(mbedtls_sha256_context)); + SHA2_Params_init(&sha2Params); + + sha2Params.returnBehavior = SHA2_RETURN_BEHAVIOR_POLLING; + + ctx->config.object = &ctx->object; + ctx->config.hwAttrs = &sha2CC26X2HWAttrs_sha; + + ctx->hndl = SHA2_construct(&ctx->config, &sha2Params); +} + +void mbedtls_sha256_free(mbedtls_sha256_context * ctx) +{ + if (NULL == ctx) + { + return; + } + + if (ctx->hndl != NULL) + { + SHA2_close(ctx->hndl); + + memset(ctx, 0, sizeof(mbedtls_sha256_context)); + } +} + +/* + * Deviation from documentation in sha256.h. + * + * It has been noticed that some code using mbedtls does not call `init` before + * starting a SHA operation. Rather these implementations assume the `ctx` + * structure may be zero'ed out as initialization. To support this usage the + * driver instance is assumed to be uninitialized if the context's `hndl` is a + * NULL pointer. Start will initialize the driver and assign the handle to the + * context in this case. + */ +int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) +{ + SHA2_HashType type; + + // open the driver here because no-one called init + if (ctx->hndl == NULL) + { + SHA2_Params sha2Params; + + SHA2_Params_init(&sha2Params); + + sha2Params.returnBehavior = SHA2_RETURN_BEHAVIOR_POLLING; + + ctx->config.object = &ctx->object; + ctx->config.hwAttrs = &sha2CC26X2HWAttrs_sha; + + ctx->hndl = SHA2_construct(&ctx->config, &sha2Params); + + if (NULL == ctx->hndl) + { + return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; + } + } + else + { + SHA2_reset(ctx->hndl); + } + + if (is224) + { + type = SHA2_HASH_TYPE_224; + } + else + { + type = SHA2_HASH_TYPE_256; + } + + SHA2_setHashType(ctx->hndl, type); + + return 0; +} + +/** + * Deviation from documentation in sha256.h. + * + * It has been noticed that some code using mbedtls does not call `init` on the + * contexts being passed into this function. This seems to be done to avoid + * allocating hardware to cloned context instances. To support this use-case, + * only internal buffers to the SHA2 structure are copied without checking the + * driver handles. + */ +void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) +{ + dst->object.hashType = src->object.hashType; + dst->object.bytesInBuffer = src->object.bytesInBuffer; + dst->object.bytesProcessed = src->object.bytesProcessed; + memcpy(dst->object.buffer, src->object.buffer, sizeof(dst->object.buffer)); + // copy the digest to support cloning after finalization has happened + memcpy(dst->object.digest, src->object.digest, sizeof(dst->object.digest)); +} + +int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) +{ + int_fast16_t result; + + result = SHA2_finalize(ctx->hndl, output); + + if (SHA2_STATUS_SUCCESS != result) + { + return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; + } + else + { + return 0; + } +} + +int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) +{ + int_fast16_t result; + + // Process data in chunks. The driver buffers incomplete blocks internally. + result = SHA2_addData(ctx->hndl, input, ilen); + + if (SHA2_STATUS_SUCCESS != result) + { + return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; + } + else + { + return 0; + } +} + +int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) +{ + int_fast16_t result; + + // Process data in chunks. The driver buffers incomplete blocks internally. + result = SHA2_addData(ctx->hndl, data, SHA2_BLOCK_SIZE_BYTES_256); + + if (SHA2_STATUS_SUCCESS != result) + { + return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; + } + else + { + return 0; + } +} + +#endif /* MBEDTLS_SHA256_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.h b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.h new file mode 100644 index 00000000000000..75bb300398905c --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/crypto/sha256_alt.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#pragma once + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls-config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_SHA256_ALT) +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +typedef struct +{ + SHA2_Handle hndl; /*!< A handle that is returned by the SHA driver */ + SHA2_Config config; /*!< structure containing SHA2 driver specific implementation */ + SHA2CC26X2_Object object; /*!< Pointer to a driver specific data object */ +} mbedtls_sha256_context; + +#ifdef __cplusplus +} +#endif +#endif /* MBEDTLS_SHA256_ALT */ diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config-check.h b/src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config-check.h new file mode 100644 index 00000000000000..a5fcac9459b6c4 --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config-check.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2019, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT +#error "Platform cc1352 doesn't support configuration option: OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT" +#endif diff --git a/src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config.h b/src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config.h new file mode 100644 index 00000000000000..5857675e1a309d --- /dev/null +++ b/src/platform/cc13xx_26xx/cc13x4_26x4/openthread-core-cc13x4_26x4-config.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#ifdef DeviceFamily_CC13X4 + +/* Number of message buffers reduced to fit into CC26x2x3 RAM */ +#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 22 + +#endif // DeviceFamily_CC13X4 + +#define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_APP + +// When operating in a less than ideal RF environment, having a more forgiving configuration +// of OpenThread makes thread a great deal more reliable. +#define OPENTHREAD_CONFIG_TMF_ADDRESS_QUERY_MAX_RETRY_DELAY 120 // default is 28800 +#define OPENTHREAD_CONFIG_MAC_DEFAULT_MAX_FRAME_RETRIES_DIRECT 15 // default is 3 +#define OPENTHREAD_CONFIG_MAC_DEFAULT_MAX_FRAME_RETRIES_INDIRECT 1 // default is 0 +#define OPENTHREAD_CONFIG_MAC_MAX_TX_ATTEMPTS_INDIRECT_POLLS 16 // default is 4 + +// Enable periodic parent search to speed up finding a better parent. +#define OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE 1 // default is 0 +#define OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD -45 // default is -65 +#define OPENTHREAD_CONFIG_MLE_INFORM_PREVIOUS_PARENT_ON_REATTACH 1 // default is 0 + +// Use smaller maximum interval to speed up reattaching. +#define OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_MAXIMUM_INTERVAL (60 * 10 * 1000) // default 1200000 ms + +#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 1 +//#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 0 +#define UART_AS_SERIAL_TRANSPORT 1 +#define OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1 +#define OPENTHREAD_CONFIG_ECDSA_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_SERVICE_DISCOVERY_ENABLE 1 + +#define OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE 0 +#define OPENTHREAD_CONFIG_BORDER_AGENT_ENABLE 0 +#define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 0 +#define OPENTHREAD_CONFIG_JOINER_ENABLE 0 + +#define OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS 0 +// TCP disabled until OpenThread has a GN/Ninja build for the tcplp library +#define OPENTHREAD_CONFIG_TCP_ENABLE 0 diff --git a/src/platform/cc13x2_26x2/chipOBleProfile.c b/src/platform/cc13xx_26xx/chipOBleProfile.c similarity index 100% rename from src/platform/cc13x2_26x2/chipOBleProfile.c rename to src/platform/cc13xx_26xx/chipOBleProfile.c diff --git a/src/platform/cc13x2_26x2/chipOBleProfile.h b/src/platform/cc13xx_26xx/chipOBleProfile.h similarity index 100% rename from src/platform/cc13x2_26x2/chipOBleProfile.h rename to src/platform/cc13xx_26xx/chipOBleProfile.h diff --git a/src/platform/cc13x2_26x2/oad_image_header.c b/src/platform/cc13xx_26xx/oad_image_header.c similarity index 100% rename from src/platform/cc13x2_26x2/oad_image_header.c rename to src/platform/cc13xx_26xx/oad_image_header.c diff --git a/src/platform/device.gni b/src/platform/device.gni index 77ca207ebbe768..8b6d9787f2a051 100755 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -16,7 +16,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/ble/ble.gni") declare_args() { - # Device platform layer: cc13x2_26x2, cc32xx, darwin, efr32, esp32, external, freertos, linux, nrfconnect, k32w0, qpg, tizen, cyw30739, bl602, mw320, zephyr, beken, openiotsdk, none. + # Device platform layer: cc13x2_26x2, cc13x4_26x4, cc32xx, darwin, efr32, esp32, external, freertos, linux, nrfconnect, k32w0, qpg, tizen, cyw30739, bl602, mw320, zephyr, beken, openiotsdk, none. chip_device_platform = "auto" chip_platform_target = "" @@ -50,6 +50,7 @@ declare_args() { chip_enable_openthread = chip_device_platform == "linux" || chip_device_platform == "qpg" || chip_device_platform == "cc13x2_26x2" || + chip_device_platform == "cc13x4_26x4" || chip_device_platform == "k32w0" || chip_device_platform == "tizen" || chip_device_platform == "webos" } @@ -90,7 +91,8 @@ declare_args() { chip_device_platform == "openiotsdk") { chip_mdns = "minimal" } else if (chip_device_platform == "darwin" || - chip_device_platform == "cc13x2_26x2" || current_os == "android" || + chip_device_platform == "cc13x2_26x2" || + chip_device_platform == "cc13x4_26x4" || current_os == "android" || chip_device_platform == "fake" || chip_device_platform == "tizen") { chip_mdns = "platform" @@ -115,7 +117,9 @@ if (chip_device_platform == "bl702" && chip_enable_openthread) { _chip_device_layer = "none" if (chip_device_platform == "cc13x2_26x2") { - _chip_device_layer = "cc13x2_26x2" + _chip_device_layer = "cc13xx_26xx/cc13x2_26x2" +} else if (chip_device_platform == "cc13x4_26x4") { + _chip_device_layer = "cc13xx_26xx/cc13x4_26x4" } else if (chip_device_platform == "cc32xx") { _chip_device_layer = "cc32xx" } else if (chip_device_platform == "darwin") { @@ -218,6 +222,7 @@ assert( (current_os != "freertos" && chip_device_platform == "none") || chip_device_platform == "fake" || chip_device_platform == "cc13x2_26x2" || + chip_device_platform == "cc13x4_26x4" || chip_device_platform == "cc32xx" || chip_device_platform == "darwin" || chip_device_platform == "efr32" || chip_device_platform == "esp32" || chip_device_platform == "external" || chip_device_platform == "linux" || diff --git a/third_party/openthread/ot-ti b/third_party/openthread/ot-ti new file mode 160000 index 00000000000000..8bec26bf2a882d --- /dev/null +++ b/third_party/openthread/ot-ti @@ -0,0 +1 @@ +Subproject commit 8bec26bf2a882d252a83ce4154a5c8e0031e56c0 diff --git a/third_party/openthread/platforms/cc13x2_26x2/BUILD.gn b/third_party/openthread/platforms/cc13x2_26x2/BUILD.gn new file mode 100644 index 00000000000000..476d0232fdf358 --- /dev/null +++ b/third_party/openthread/platforms/cc13x2_26x2/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/openthread.gni") +import("//build_overrides/ti_simplelink_sdk.gni") + +import("${ti_simplelink_sdk_build_root}/ti_simplelink_board.gni") +import("${ti_simplelink_sdk_build_root}/ti_simplelink_sdk.gni") + +openthread_ti_root = "${chip_root}/third_party/openthread/ot-ti" + +config("openthread_cc13x2_cc26x2_config") { + include_dirs = [ + "${openthread_root}/examples/platforms", + "${openthread_root}/src/core", + "${openthread_ti_root}/src", + ] +} + +source_set("libopenthread-cc13x2_cc26x2") { + cflags = [ + "-Wno-address-of-packed-member", + "-Wno-implicit-fallthrough", + "-Wno-unused-label", + ] + public_deps = [ + "${openthread_root}/src/core:libopenthread_core_headers", + "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk", + "${ti_simplelink_sdk_build_root}:ti_simplelink_sysconfig", + ] + + configs -= [ "${build_root}/config/compiler:std_default" ] + configs += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_posix_config" ] + + #configs += [ ":${sdk_target_name}_posix_config" ] + #configs += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk_posix_config" ] + sources = [ + #"${openthread_ti_root}/src/system.c", + "${openthread_root}/examples/platforms/utils/code_utils.h", + "${openthread_root}/examples/platforms/utils/link_metrics.cpp", + "${openthread_root}/examples/platforms/utils/link_metrics.h", + "${openthread_root}/examples/platforms/utils/mac_frame.cpp", + "${openthread_root}/examples/platforms/utils/mac_frame.h", + "${openthread_ti_root}/src/alarm.c", + "${openthread_ti_root}/src/alarm_micro.c", + "${openthread_ti_root}/src/diag.c", + "${openthread_ti_root}/src/entropy.c", + "${openthread_ti_root}/src/misc.c", + "${openthread_ti_root}/src/radio.c", + "${openthread_ti_root}/src/settings.c", + ] + + public_configs = [ + ":openthread_cc13x2_cc26x2_config", + "${openthread_root}:openthread_config", + ] + if (chip_openthread_ftd) { + public_configs += [ "${openthread_root}:openthread_ftd_config" ] + } else { + public_configs += [ "${openthread_root}:openthread_mtd_config" ] + } +} diff --git a/third_party/openthread/platforms/cc13x4_26x4/BUILD.gn b/third_party/openthread/platforms/cc13x4_26x4/BUILD.gn new file mode 100644 index 00000000000000..64b0a813935f0e --- /dev/null +++ b/third_party/openthread/platforms/cc13x4_26x4/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/openthread.gni") +import("//build_overrides/ti_simplelink_sdk.gni") + +import("${ti_simplelink_sdk_build_root}/ti_simplelink_board.gni") +import("${ti_simplelink_sdk_build_root}/ti_simplelink_sdk.gni") + +openthread_ti_root = "${chip_root}/third_party/openthread/ot-ti" + +config("openthread_cc13x4_cc26x4_config") { + include_dirs = [ + "${openthread_root}/examples/platforms", + "${openthread_root}/src/core", + "${openthread_ti_root}/src", + ] +} + +source_set("libopenthread-cc13x4_cc26x4") { + cflags = [ + "-Wno-address-of-packed-member", + "-Wno-implicit-fallthrough", + "-Wno-unused-label", + ] + public_deps = [ + "${openthread_root}/src/core:libopenthread_core_headers", + "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk", + "${ti_simplelink_sdk_build_root}:ti_simplelink_sysconfig", + ] + + configs -= [ "${build_root}/config/compiler:std_default" ] + configs += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_posix_config" ] + + #configs += [ ":${sdk_target_name}_posix_config" ] + #configs += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk_posix_config" ] + sources = [ + #"${openthread_ti_root}/src/system.c", + "${openthread_root}/examples/platforms/utils/code_utils.h", + "${openthread_root}/examples/platforms/utils/link_metrics.cpp", + "${openthread_root}/examples/platforms/utils/link_metrics.h", + "${openthread_root}/examples/platforms/utils/mac_frame.cpp", + "${openthread_root}/examples/platforms/utils/mac_frame.h", + "${openthread_ti_root}/src/alarm.c", + "${openthread_ti_root}/src/alarm_micro.c", + "${openthread_ti_root}/src/diag.c", + "${openthread_ti_root}/src/entropy.c", + "${openthread_ti_root}/src/misc.c", + "${openthread_ti_root}/src/radio.c", + "${openthread_ti_root}/src/settings.c", + ] + + public_configs = [ + ":openthread_cc13x4_cc26x4_config", + "${openthread_root}:openthread_config", + ] + if (chip_openthread_ftd) { + public_configs += [ "${openthread_root}:openthread_ftd_config" ] + } else { + public_configs += [ "${openthread_root}:openthread_mtd_config" ] + } +} diff --git a/third_party/ti_simplelink_sdk/BUILD.gn b/third_party/ti_simplelink_sdk/BUILD.gn index d0b8d79372ea31..8f6c4806d2182a 100644 --- a/third_party/ti_simplelink_sdk/BUILD.gn +++ b/third_party/ti_simplelink_sdk/BUILD.gn @@ -44,8 +44,17 @@ config("ti_simplelink_mbedtls_config") { defines = [ "MBEDTLS_CONFIG_FILE=\"cc13x2_26x2-mbedtls-config.h\"" ] include_dirs = [ - "${chip_root}/src/platform/cc13x2_26x2", - "${chip_root}/src/platform/cc13x2_26x2/crypto", + "${chip_root}/src/platform/cc13xx_26xx/", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/crypto", + "${ti_simplelink_sdk_root}/source", + ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + defines = [ "MBEDTLS_CONFIG_FILE=\"cc13x4_26x4-mbedtls-config.h\"" ] + include_dirs = [ + "${chip_root}/src/platform/cc13xx_26xx/", + "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4", + "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4/crypto", "${ti_simplelink_sdk_root}/source", ] } else if (ti_simplelink_device_family == "cc32xx") { @@ -60,11 +69,11 @@ mbedtls_target("mbedtls") { if (ti_simplelink_device_family == "cc13x2_26x2" || ti_simplelink_device_family == "cc13x2x7_26x2x7") { sources = [ - "${chip_root}/src/platform/cc13x2_26x2/crypto/aes_alt.c", - "${chip_root}/src/platform/cc13x2_26x2/crypto/ecdh_alt.c", - "${chip_root}/src/platform/cc13x2_26x2/crypto/ecdsa_alt.c", - "${chip_root}/src/platform/cc13x2_26x2/crypto/ecjpake_alt.c", - "${chip_root}/src/platform/cc13x2_26x2/crypto/sha256_alt.c", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/aes_alt.c", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecdh_alt.c", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecdsa_alt.c", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/ecjpake_alt.c", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/crypto/sha256_alt.c", ] } @@ -79,9 +88,17 @@ config("ti_simplelink_freertos_config") { if (ti_simplelink_device_family == "cc13x2_26x2" || ti_simplelink_device_family == "cc13x2x7_26x2x7") { include_dirs = [ - "${chip_root}/src/platform/cc13x2_26x2", + "${chip_root}/src/platform/cc13xx_26xx", + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2", "${freertos_root}/repo/portable/GCC/ARM_CM4F", ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + include_dirs = [ + "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4", + "${freertos_root}/repo/portable/GCC/ARM_CM33_NTZ", + "${freertos_root}/repo/portable/GCC/ARM_CM33_NTZ/non_secure", + "${chip_root}/src/platform/cc13xx_26xx", + ] } else if (ti_simplelink_device_family == "cc32xx") { include_dirs = [ "${chip_root}/src/platform/cc32xx", @@ -90,12 +107,25 @@ config("ti_simplelink_freertos_config") { } } +config("ti_simplelink_posix_config") { + include_dirs = [ "${ti_simplelink_sdk_root}/source/ti/posix/gcc" ] + cflags_c = [ "-std=c11" ] + cflags_cc = [ "-std=c++14" ] + cflags = [ + "-Wno-maybe-uninitialized", + "-Wno-sign-compare", + ] +} + freertos_target("freertos") { if (ti_simplelink_device_family == "cc13x2_26x2" || ti_simplelink_device_family == "cc13x2x7_26x2x7") { + sources = [ "${freertos_root}/repo/portable/GCC/ARM_CM4F/port.c" ] + } else if (ti_simplelink_device_family == "cc13x4_26x4" || + ti_simplelink_device_family == "cc13x4_26x4") { sources = [ - "${freertos_root}/repo/portable/GCC/ARM_CM4F/port.c", - #"${freertos_root}/repo/portable/MemMang/heap_4.c", + "${freertos_root}/repo/portable/GCC/ARM_CM33_NTZ/non_secure/port.c", + "${freertos_root}/repo/portable/GCC/ARM_CM33_NTZ/non_secure/portasm.c", ] } else if (ti_simplelink_device_family == "cc32xx") { sources = [ @@ -106,7 +136,8 @@ freertos_target("freertos") { public_configs = [ ":ti_simplelink_freertos_config" ] - if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { + if (ti_simplelink_device_family == "cc13x2x7_26x2x7" || + ti_simplelink_device_family == "cc13x4_26x4") { # BLE has to have it's own heap config public_deps = [ "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sysconfig" ] diff --git a/third_party/ti_simplelink_sdk/run_sysconfig.py b/third_party/ti_simplelink_sdk/run_sysconfig.py index c394b59f68fa64..15d5f5dd6de1cd 100644 --- a/third_party/ti_simplelink_sdk/run_sysconfig.py +++ b/third_party/ti_simplelink_sdk/run_sysconfig.py @@ -29,4 +29,6 @@ proc_call += sys.argv[2:] # exec -subprocess.call(proc_call) +ret = subprocess.call(proc_call) + +sys.exit(ret) diff --git a/third_party/ti_simplelink_sdk/ti_simplelink_arm_platform_config.gni b/third_party/ti_simplelink_sdk/ti_simplelink_arm_platform_config.gni index 2ee40881b23bca..79b7aa1f59a695 100644 --- a/third_party/ti_simplelink_sdk/ti_simplelink_arm_platform_config.gni +++ b/third_party/ti_simplelink_sdk/ti_simplelink_arm_platform_config.gni @@ -22,6 +22,13 @@ if (ti_simplelink_device_family == "cc13x2_26x2" || arm_float_abi = "hard" arm_fpu = "fpv5-sp-d16" arm_use_thumb = true +} else if (ti_simplelink_device_family == "cc13x4_26x4") { + arm_arch = "" + arm_abi = "" + arm_cpu = "cortex-m33" + arm_float_abi = "hard" + arm_fpu = "fpv5-sp-d16" + arm_use_thumb = true } else if (ti_simplelink_device_family == "cc32xx") { arm_arch = "armv7e-m" arm_abi = "" diff --git a/third_party/ti_simplelink_sdk/ti_simplelink_board.gni b/third_party/ti_simplelink_sdk/ti_simplelink_board.gni index c6ae89ab2d8d43..a89d2aebc28898 100644 --- a/third_party/ti_simplelink_sdk/ti_simplelink_board.gni +++ b/third_party/ti_simplelink_sdk/ti_simplelink_board.gni @@ -25,13 +25,14 @@ assert(ti_simplelink_board != "", "ti_simplelink_board must be specified") # Differentiate between boards # -# | Development Kit | Device Family | SoC | | -# | ----------------- | --------------- | ---------- | ------------------- | -# | CC1352R1_LAUNCHXL | cc13x2_26x2 | cc1352r1f3 | Thread MTD + no BLE | -# | CC2652R1_LAUNCHXL | cc13x2_26x2 | cc2652r1f3 | Thread MTD + no BLE | -# | LP_CC2652R7 | cc13x2x7_26x2x7 | cc2652r1f7 | Thread FTD + BLE | -# | CC3220SF_LAUNCHXL | cc32xx | cc3220SF | Wi-Fi | -# | CC3235SF_LAUNCHXL | cc32xx | cc3235SF | Wi-Fi | +# | Development Kit | Device Family | SoC | | +# | ----------------- | --------------- | ---------- | ------------------- | +# | CC1352R1_LAUNCHXL | cc13x2_26x2 | cc1352r1f3 | Thread MTD + no BLE | +# | CC2652R1_LAUNCHXL | cc13x2_26x2 | cc2652r1f3 | Thread MTD + no BLE | +# | LP_CC2652R7 | cc13x2x7_26x2x7 | cc2652r1f7 | Thread FTD + BLE | +# | CC134P10_6_LAUNCHXL| cc13x4_26x4 | cc1354p10 | Thread FTD + BLE | +# | CC3220SF_LAUNCHXL | cc32xx | cc3220SF | Wi-Fi | +# | CC3235SF_LAUNCHXL | cc32xx | cc3235SF | Wi-Fi | # XXX: Can we do an array with a case statement? if (ti_simplelink_board == "CC1352R1_LAUNCHXL") { @@ -50,6 +51,12 @@ if (ti_simplelink_board == "CC1352R1_LAUNCHXL") { # set -DDeviceFamily_CC26X2? ti_simplelink_soc = "cc2652r1f3" ti_simplelink_bim_name = "cc2652r1lp" +} else if (ti_simplelink_board == "LP_EM_CC1354P10_6") { + ti_simplelink_device_family = "cc13x4_26x4" + ti_simplelink_soc_family = "cc13x4" + ti_simplelink_isa = "m33f" + ti_simplelink_soc = "cc1354p10" + ti_simplelink_bim_name = "cc1354p10" } else if (ti_simplelink_board == "LP_CC2652R7") { ti_simplelink_device_family = "cc13x2x7_26x2x7" ti_simplelink_soc_family = "cc26x2" diff --git a/third_party/ti_simplelink_sdk/ti_simplelink_executable.gni b/third_party/ti_simplelink_sdk/ti_simplelink_executable.gni index 650f336c443d22..da4dff87a73460 100644 --- a/third_party/ti_simplelink_sdk/ti_simplelink_executable.gni +++ b/third_party/ti_simplelink_sdk/ti_simplelink_executable.gni @@ -47,7 +47,8 @@ template("ti_simplelink_executable") { output_base_name = get_path_info(invoker.output_name, "name") #used for OTA image creator for the cc13xx - if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { + if (ti_simplelink_device_family == "cc13x2x7_26x2x7" || + ti_simplelink_device_family == "cc13x4_26x4") { objcopy_image_name = output_base_name + ".hex" objcopy_image_format = "ihex" } else { @@ -80,10 +81,18 @@ template("ti_simplelink_executable") { if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { if (chip_enable_ota_requestor) { sources += - [ "${chip_root}/src/platform/cc13x2_26x2/oad_image_header.c" ] - ldscript = "${chip_root}/src/platform/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds" + [ "${chip_root}/src/platform/cc13xx_26xx/oad_image_header.c" ] + ldscript = "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos_ota.lds" } else { - ldscript = "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/cc13x2x7_cc26x2x7.lds" + ldscript = "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/cc13x2x7_cc26x2x7_freertos.lds" + } + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + if (chip_enable_ota_requestor) { + sources += + [ "${chip_root}/src/platform/cc13xx_26xx/oad_image_header.c" ] + ldscript = "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos_ota.lds" + } else { + ldscript = "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4/cc13x4_cc26x4_freertos.lds" } } else if (ti_simplelink_device_family == "cc32xx") { ldscript = "${ti_simplelink_sdk_root}/source/ti/boards/cc32xxsf/cc32xxsf_freertos.lds" @@ -143,7 +152,7 @@ template("ti_simplelink_executable") { if (defined(invoker.bim_hex)) { bim_hex = invoker.bim_hex } else { - bim_hex = "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/ble5stack/hexfiles/bim_offchip/Release/${ti_simplelink_bim_name}_bim_offchip.hex" + bim_hex = "${ti_simplelink_sdk_root}/examples/nortos/${ti_simplelink_board}/bim/hexfiles/bim_offchip/Release/bim_offchip.hex" } args = [ diff --git a/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni b/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni index dfbdb5f841bc87..08ef9bd1c6fd8a 100644 --- a/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni +++ b/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni @@ -30,9 +30,12 @@ declare_args() { # Location of the TI SimpleLink SDK. if (ti_simplelink_device_family == "cc13x2_26x2" || - ti_simplelink_device_family == "cc13x2x7_26x2x7") { + ti_simplelink_device_family == "cc13x2x7_26x2x7" || + ti_simplelink_device_family == "cc13x4_26x4") { ti_simplelink_sdk_root = "${chip_root}/third_party/ti_simplelink_sdk/repo_cc13xx_cc26xx" + ot_cc13x2_cc26x2 = + "${chip_root}/third_party/ti_simplelink_sdk/repo_ot-cc13x2_cc26x2" } else if (ti_simplelink_device_family == "cc32xx") { ti_simplelink_sdk_root = "${chip_root}/third_party/ti_simplelink_sdk/repo_cc32xx" @@ -68,11 +71,26 @@ template("ti_sysconfig") { } if (ti_simplelink_device_family == "cc13x2_26x2") { - ldflags += [ "-nostartfiles" ] + ldflags += [ + "-nostartfiles", + "-fno-exceptions", + "-fno-unwind-tables", + ] defines += [ "DeviceFamily_CC13X2_CC26X2" ] } else if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { - ldflags += [ "-nostartfiles" ] + ldflags += [ + "-nostartfiles", + "-fno-exceptions", + "-fno-unwind-tables", + ] defines += [ "DeviceFamily_CC26X2X7" ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + ldflags += [ + "-nostartfiles", + "-fno-exceptions", + "-fno-unwind-tables", + ] + defines += [ "DeviceFamily_CC13X4" ] } else if (ti_simplelink_device_family == "cc32xx") { ldflags += [ "-nostartfiles" ] defines += [ "CC32XXWARE" ] @@ -148,7 +166,8 @@ template("ti_simplelink_sdk") { defines = [] if (ti_simplelink_device_family == "cc13x2_26x2" || - ti_simplelink_device_family == "cc13x2x7_26x2x7") { + ti_simplelink_device_family == "cc13x2x7_26x2x7" || + ti_simplelink_device_family == "cc13x4_26x4") { assert(ti_simplelink_soc_family != "", "ti_simplelink_soc_family must be specified") assert(ti_simplelink_device_family != "", @@ -185,6 +204,9 @@ template("ti_simplelink_sdk") { } else if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { defines += [ "DeviceFamily_CC13X2X7_CC26X2X7" ] libs += [ "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/driverlib/bin/gcc/driverlib.lib" ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + defines += [ "DeviceFamily_CC13X4" ] + libs += [ "${ti_simplelink_sdk_root}/source/ti/devices/cc13x4_cc26x4/driverlib/bin/gcc/driverlib.lib" ] } if (ti_simplelink_device_family == "cc32xx") { @@ -226,6 +248,14 @@ template("ti_simplelink_sdk") { "${ti_simplelink_sdk_root}/kernel/freertos/dpl/TimerPCC26XX_freertos.c", "${ti_simplelink_sdk_root}/kernel/freertos/startup/startup_cc13x2_cc26x2_gcc.c", ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + sources += [ + "${ti_simplelink_sdk_root}/kernel/freertos/dpl/ClockPCC26X2_freertos.c", + "${ti_simplelink_sdk_root}/kernel/freertos/dpl/HwiPCC26X2_freertos.c", + "${ti_simplelink_sdk_root}/kernel/freertos/dpl/PowerCC26X2_freertos.c", + "${ti_simplelink_sdk_root}/kernel/freertos/dpl/TimerPCC26XX_freertos.c", + "${ti_simplelink_sdk_root}/kernel/freertos/startup/startup_cc13x4_cc26x4_gcc.c", + ] } else if (ti_simplelink_device_family == "cc32xx") { sources += [ "${ti_simplelink_sdk_root}/kernel/freertos/dpl/ClockP_freertos.c", @@ -282,69 +312,32 @@ template("ti_simplelink_sdk") { } if (ti_simplelink_device_family == "cc13x2_26x2" || - ti_simplelink_device_family == "cc13x2x7_26x2x7") { - if (chip_openthread_ftd) { - openthread_example = "cli_ftd" - } else { - openthread_example = "cli_mtd" - } - - config("${sdk_target_name}_openthread_platform_config") { + ti_simplelink_device_family == "cc13x2x7_26x2x7" || + ti_simplelink_device_family == "cc13x4_26x4") { + source_set("${sdk_target_name}_nvocmp") { defines = [ "NVOCMP_POSIX_MUTEX" ] - include_dirs = [ - "${chip_root}/third_party/openthread/repo/examples/platforms", - "${chip_root}/third_party/openthread/repo/src/core", - "${ti_simplelink_sdk_root}/source/ti/devices/${ti_simplelink_device_family}", - ] - - if (ti_simplelink_device_family == "cc13x2_26x2") { - include_dirs += [ - "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2_cc26x2", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}", - ] - } else if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { - include_dirs += [ - "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}", - ] - } - } - - source_set("${sdk_target_name}_openthread_platform") { cflags = [ "-Wno-int-conversion", "-Wno-address-of-packed-member", "-Wno-implicit-fallthrough", "-Wno-unused-label", + "-Wno-shadow", ] public_deps = [ ":${sdk_target_name}_freertos", "${chip_root}/third_party/ti_simplelink_sdk:freertos", "${chip_root}/third_party/ti_simplelink_sdk:mbedtls", "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sysconfig", - "${openthread_root}/src/core:libopenthread_core_headers", ] configs -= [ "${build_root}/config/compiler:std_default" ] configs += [ ":${sdk_target_name}_posix_config" ] sources = [ - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/alarm.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/alarm_micro.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/diag.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/entropy.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/misc.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/nv/crc.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/nv/nvocmp.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/radio.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/settings.c", - "${ti_simplelink_sdk_root}/examples/rtos/${ti_simplelink_board}/thread/${openthread_example}/platform/system.c", + "${ti_simplelink_sdk_root}/source/ti/common/nv/crc.c", + "${ti_simplelink_sdk_root}/source/ti/common/nv/nvocmp.c", ] - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_openthread_platform_config", - "${chip_root}/third_party/openthread/repo:openthread_config", - ] + public_configs = [ ":${sdk_target_name}_config" ] if (chip_openthread_ftd) { public_configs += @@ -360,60 +353,11 @@ template("ti_simplelink_sdk") { include_dirs = [] libs = [] - include_dirs += [ - # DMM/BLE: - "${ti_simplelink_sdk_root}/source", - - # Eclipse the SDK config header from DMM - "${chip_root}/src/platform/cc13x2_26x2", - - # CHIPoBLE Added include dirs - "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/", - "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/itm", - "${ti_simplelink_sdk_root}/source/ti/dmm/thread/platform", - "${ti_simplelink_sdk_root}/source/", - "${ti_simplelink_sdk_root}/source/ti/", - "${ti_simplelink_sdk_root}/source/ti/dmm/", - "${ti_simplelink_sdk_root}/source/ti/dmm/apps/", - "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/", - "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/source/activity/", - "${ti_simplelink_sdk_root}/source/ti/common/nv", - - "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7", - "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/inc", - "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/rf_patches", - "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/driverlib", - - "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/npi/stack/", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/rcosc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/controller/cc26xx/inc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/inc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/rom", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/inc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/target/_common", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/target/_common/cc26xx", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/inc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/heapmgr", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/profiles/dev_info", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/target/_common/cc26xx/", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/profiles/simple_profile", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src/inc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/osal/src/inc", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/controller/cc26xx/inc/", - "${ti_simplelink_sdk_root}/source/ti/common/cc26xx", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/", - ] - defines = [ "INCLUDE_BGET_STATS", "USE_DMM", - "FLASH_ROM_BUILD", "NVOCMP_FREERTOS_MUTEX=1", "USEOT", - "ONE_BLE_LIB_SIZE_OPTIMIZATION", "ICALL_EVENTS", "ICALL_JT", "ICALL_LITE", @@ -421,16 +365,12 @@ template("ti_simplelink_sdk") { "ICALL_MAX_NUM_TASKS=3", "ICALL_STACK0_ADDR", "POWER_SAVING", - "STACK_LIBRARY", "TBM_ACTIVE_ITEMS_ONLY", "NPI_USE_UART", "NPI_FLOW_CTRL=0", "OSAL_CBTIMER_NUM_TASKS=1", "USE_ICALL", "BLE_START", - "CC26XX", - "CC26X2", - "CC26X2R1_LAUNCHXL", "FREERTOS", ] @@ -441,11 +381,131 @@ template("ti_simplelink_sdk") { "${ti_simplelink_sdk_root}/source/ti/ble5stack/libraries/cc26x2r1/StackWrapper.a", "${ti_simplelink_sdk_root}/source/ti/ble5stack/libraries/cc26x2r1/ble_r2.symbols", ] + + defines += [ + "FLASH_ROM_BUILD", + "ONE_BLE_LIB_SIZE_OPTIMIZATION", + "STACK_LIBRARY", + "CC26XX", + "CC26X2", + "CC26X2R1_LAUNCHXL", + ] + include_dirs += [ + # DMM/BLE: + "${ti_simplelink_sdk_root}/source", + + # Eclipse the SDK config header from DMM + "${chip_root}/src/platform/cc13x2_26x2", + + # CHIPoBLE Added include dirs + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/itm", + "${ti_simplelink_sdk_root}/source/ti/dmm/thread/platform", + "${ti_simplelink_sdk_root}/source/", + "${ti_simplelink_sdk_root}/source/ti/", + "${ti_simplelink_sdk_root}/source/ti/dmm/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/source/activity/", + "${ti_simplelink_sdk_root}/source/ti/common/nv", + + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7", + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/inc", + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/rf_patches", + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7/driverlib", + + "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/npi/stack/", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/rcosc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/controller/cc26xx/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/rom", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/target/_common", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/target/_common/cc26xx", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/heapmgr", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/profiles/dev_info", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/hal/src/target/_common/cc26xx/", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/profiles/simple_profile", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/osal/src/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/controller/cc26xx/inc/", + "${ti_simplelink_sdk_root}/source/ti/common/cc26xx", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/", + ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + libs += [ + "${ti_simplelink_sdk_root}/source/ti/dmm/lib/gcc/m4f/libdmmlib_freertos.a", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/libraries/cc1354p10_6/OneLib.a", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/libraries/cc1354p10_6/StackWrapper.a", + ] + defines += [ + "ONE_BLE_LIB_SIZE_OPTIMIZATION", + "NVOCMP_NVPAGES=3", + "NVOCMP_NWSAMEITEM=1", + "CC13X2P", + "SYSCFG", + "CC13X4", + "CC13XX", + "EXTENDED_STACK_SETTINGS=EXTENDED_STACK_SETTINGS_DEFAULT", + ] + + include_dirs += [ + # DMM/BLE: + "${ti_simplelink_sdk_root}/source", + + # Eclipse the SDK config header from DMM + "${chip_root}/src/platform/cc13x4_26x4", + "${chip_root}/src/platform/cc13xx_26xx", + + # CHIPoBLE Added include dirs + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/itm", + "${ti_simplelink_sdk_root}/source/ti/dmm/thread/platform", + "${ti_simplelink_sdk_root}/source/", + "${ti_simplelink_sdk_root}/source/ti/", + "${ti_simplelink_sdk_root}/source/ti/dmm/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/", + "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/source/activity/", + "${ti_simplelink_sdk_root}/source/ti/common/nv", + + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x4_cc26x4", + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x4_cc26x4/inc", + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x4_cc26x4/rf_patches", + "${ti_simplelink_sdk_root}/source/ti/devices/cc13x4_cc26x4/driverlib", + + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/common/cc26xx/npi/stack/", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/common/cc26xx/rcosc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/controller/cc26xx/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/rom", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/common/cc26xx", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/common/cc26xx/freertos", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/src", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/hal/src/target/_common", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/hal/src/target/_common/cc26xx", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/hal/src/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/heapmgr", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/profiles/dev_info", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/hal/src/target/_common/cc26xx/", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/profiles/simple_profile", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/src/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/osal/src/inc", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/controller/cc26xx/inc/", + "${ti_simplelink_sdk_root}/source/ti/common/cc26xx", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/", + ] } cflags = [ "-Wno-conversion", "-Wno-comment", + "-Wno-shadow", "@" + rebase_path(ti_simplelink_sdk_root + "/source/ti/ble5stack/config/build_components.opt", root_build_dir), @@ -457,6 +517,7 @@ template("ti_simplelink_sdk") { source_set("${sdk_target_name}_dmm") { if (ti_simplelink_device_family == "cc13x2_26x2" || + ti_simplelink_device_family == "cc13x4_26x4" || ti_simplelink_device_family == "cc13x2x7_26x2x7") { defines = [] include_dirs = [ @@ -474,28 +535,48 @@ template("ti_simplelink_sdk") { ] sources = [ + "${chip_root}/src/platform/cc13xx_26xx/chipOBleProfile.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/TI_heap_wrapper.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/bget.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/rcosc/rcosc_calibration.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/host/gatt_uuid.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/host/gattservapp_util.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/app/icall_api_lite.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src/icall_cc2650.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src/icall_user_config.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/stack/ble_user_config_stack.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/profiles/dev_info/cc26xx/devinfoservice.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/rom/agama_r1/rom_init.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/ble_remote_display/stack/osal_icall_ble.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/icall_FreeRTOS.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/freertos/util.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/thread/source/activity/dmm_thread_activity.c", "${ti_simplelink_sdk_root}/source/ti/dmm/dmm_priority_ble_thread.c", - - # Move this into the SDK - "${chip_root}/src/platform/cc13x2_26x2/ble_user_config.c", - "${chip_root}/src/platform/cc13x2_26x2/chipOBleProfile.c", ] + if (ti_simplelink_device_family == "cc13x2_26x2" || + ti_simplelink_device_family == "cc13x2x7_26x2x7") { + sources += [ + "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/ble_user_config.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/host/gatt_uuid.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/host/gattservapp_util.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/app/icall_api_lite.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src/icall_cc2650.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/src/icall_user_config.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/icall/stack/ble_user_config_stack.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/profiles/dev_info/cc26xx/devinfoservice.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack/rom/agama_r1/rom_init.c", + ] + + include_dirs += [ "${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/" ] + } else if (ti_simplelink_device_family == "cc13x4_26x4") { + sources += [ + "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4/ble_user_config.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/host/gatt_uuid.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/host/gattservapp_util.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/app/icall_api_lite.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/src/icall_cc2650.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/src/icall_user_config.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/icall/stack/ble_user_config_stack.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/profiles/dev_info/cc26xx/devinfoservice.c", + "${ti_simplelink_sdk_root}/source/ti/ble5stack_flash/rom/agama_r1/rom_init.c", + ] + + include_dirs += [ "${chip_root}/src/platform/cc13xx_26xx/cc13x4_26x4/" ] + } + configs -= [ "${build_root}/config/compiler:std_default" ] configs += [ ":${sdk_target_name}_posix_config" ] @@ -517,10 +598,11 @@ template("ti_simplelink_sdk") { ":${sdk_target_name}_freertos", ] if (ti_simplelink_device_family == "cc13x2_26x2" || - ti_simplelink_device_family == "cc13x2x7_26x2x7") { + ti_simplelink_device_family == "cc13x2x7_26x2x7" || + ti_simplelink_device_family == "cc13x4_26x4") { public_deps += [ ":${sdk_target_name}_dmm", - ":${sdk_target_name}_openthread_platform", + ":${sdk_target_name}_nvocmp", ] } if (defined(invoker.public_configs)) { @@ -528,3 +610,68 @@ template("ti_simplelink_sdk") { } } } + +# "${openthread_root}/src/core:libopenthread_core_headers", + +# config("${sdk_target_name}_openthread_platform_config") { +# include_dirs = [ +# "${chip_root}/third_party/openthread/repo/examples/platforms", +# "${chip_root}/third_party/openthread/repo/src/core", +# "${ti_simplelink_sdk_root}/source/ti/devices/${ti_simplelink_device_family}", +# ] + +# if (ti_simplelink_device_family == "cc13x2_26x2") { +# include_dirs += [ +# "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2_cc26x2", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2", +# ] +# } else if (ti_simplelink_device_family == "cc13x2x7_26x2x7") { +# include_dirs += [ +# "${ti_simplelink_sdk_root}/source/ti/devices/cc13x2x7_cc26x2x7", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2", +# ] +# } +# } + +# source_set("${sdk_target_name}_openthread_platform") { +# cflags = [ +# "-Wno-int-conversion", +# "-Wno-address-of-packed-member", +# "-Wno-implicit-fallthrough", +# "-Wno-unused-label", +# ] +# public_deps = [ +# ":${sdk_target_name}_freertos", +# "${chip_root}/third_party/ti_simplelink_sdk:freertos", +# "${chip_root}/third_party/ti_simplelink_sdk:mbedtls", +# "${chip_root}/third_party/ti_simplelink_sdk:ti_simplelink_sysconfig", +# "${openthread_root}/src/core:libopenthread_core_headers", +# ] + +# configs -= [ "${build_root}/config/compiler:std_default" ] +# configs += [ ":${sdk_target_name}_posix_config" ] +# sources = [ +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/alarm.c", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/alarm_micro.c", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/diag.c", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/entropy.c", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/misc.c", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/radio.c", +# "${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/settings.c", +# #"${ot_cc13x2_cc26x2}/src/cc13x2_cc26x2/system.c", +# ] + +# public_configs = [ +# ":${sdk_target_name}_config", +# ":${sdk_target_name}_openthread_platform_config", +# "${chip_root}/third_party/openthread/repo:openthread_config", +# ] + +# if (chip_openthread_ftd) { +# public_configs += +# [ "${chip_root}/third_party/openthread/repo:openthread_ftd_config" ] +# } else { +# public_configs += +# [ "${chip_root}/third_party/openthread/repo:openthread_mtd_config" ] +# } +# } From aea8e0a932e8f39f2f46ae8ae505857959ac30b4 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 09:58:32 -0400 Subject: [PATCH 20/36] Fix isUpperCase/isLowerCase constraint checking in python yaml processing. (#26536) * Fix isUpperCase/isLowerCase constraint checking in python yaml processing. I just got a CI failure like so: TEST OUT: isUpperCase: true <-- The response "9659674627744477" contains lowercase characters: []. but of course it does not. It just happens to be an instance name that didn't end up using any hex chars that are > 9. This change better aligns the way Python tests uppercase/lowercase with the built-in chip-tool constraint impl. * Address review comments. * Fix restyle issue. --- .../matter_yamltests/constraints.py | 8 +- src/app/tests/suites/TestConstraints.yaml | 77 ++++ .../tests/suites/include/ConstraintsChecker.h | 2 +- .../chip-tool/zap-generated/test/Commands.h | 213 ++++++++-- .../zap-generated/test/Commands.h | 388 +++++++++++++++--- 5 files changed, 589 insertions(+), 99 deletions(-) diff --git a/scripts/py_matter_yamltests/matter_yamltests/constraints.py b/scripts/py_matter_yamltests/matter_yamltests/constraints.py index 1c615e784ef51d..65e11b15db9cb8 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/constraints.py +++ b/scripts/py_matter_yamltests/matter_yamltests/constraints.py @@ -582,7 +582,9 @@ def __init__(self, context, is_upper_case): self._is_upper_case = is_upper_case def check_response(self, value, value_type_name) -> bool: - return value.isupper() == self._is_upper_case + # Make sure we don't have any lowercase characters. + hasLower = any(c.islower() for c in value) + return hasLower != self._is_upper_case def get_reason(self, value, value_type_name) -> str: if self._is_upper_case: @@ -608,7 +610,9 @@ def __init__(self, context, is_lower_case): self._is_lower_case = is_lower_case def check_response(self, value, value_type_name) -> bool: - return value.islower() == self._is_lower_case + # Make sure we don't have any uppercase characters. + hasUpper = any(c.isupper() for c in value) + return hasUpper != self._is_lower_case def get_reason(self, value, value_type_name) -> str: if self._is_lower_case: diff --git a/src/app/tests/suites/TestConstraints.yaml b/src/app/tests/suites/TestConstraints.yaml index 4ef38820de4464..60b88ead227c65 100644 --- a/src/app/tests/suites/TestConstraints.yaml +++ b/src/app/tests/suites/TestConstraints.yaml @@ -234,6 +234,83 @@ tests: isUpperCase: false isLowerCase: false + - label: "Write attribute CHAR_STRING Value with only digits" + command: "writeAttribute" + attribute: "char_string" + arguments: + value: "1234567890" + + - label: + "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints" + command: "readAttribute" + attribute: "char_string" + response: + constraints: + isUpperCase: true + isLowerCase: true + + - label: "Write attribute CHAR_STRING Value with only non-letters" + command: "writeAttribute" + attribute: "char_string" + arguments: + value: "12.4,76:" + + - label: + "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints" + command: "readAttribute" + attribute: "char_string" + response: + constraints: + isUpperCase: true + isLowerCase: true + + - label: + "Write attribute CHAR_STRING Value with uppercase letters and symbols" + command: "writeAttribute" + attribute: "char_string" + arguments: + value: "ABC;.* " + + - label: + "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints" + command: "readAttribute" + attribute: "char_string" + response: + constraints: + isUpperCase: true + isLowerCase: false + + - label: + "Write attribute CHAR_STRING Value with lowercase letters and symbols" + command: "writeAttribute" + attribute: "char_string" + arguments: + value: "abc;.* " + + - label: + "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints" + command: "readAttribute" + attribute: "char_string" + response: + constraints: + isUpperCase: false + isLowerCase: true + + - label: "Write attribute CHAR_STRING Value which is empty" + command: "writeAttribute" + attribute: "char_string" + arguments: + value: "" + + - label: + "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints" + command: "readAttribute" + attribute: "char_string" + response: + constraints: + isUpperCase: true + isLowerCase: true + - label: "Write attribute CHAR_STRING Value" command: "writeAttribute" attribute: "char_string" diff --git a/src/app/tests/suites/include/ConstraintsChecker.h b/src/app/tests/suites/include/ConstraintsChecker.h index 84f2dc8dff6321..be446fd3f42c28 100644 --- a/src/app/tests/suites/include/ConstraintsChecker.h +++ b/src/app/tests/suites/include/ConstraintsChecker.h @@ -146,7 +146,7 @@ class ConstraintsChecker bool isUpperCase = true; for (size_t i = 0; i < strlen(current); i++) { - if (!isdigit(current[i]) && !isupper(current[i])) + if (islower(current[i])) { isUpperCase = false; break; diff --git a/zzz_generated/chip-tool/zap-generated/test/Commands.h b/zzz_generated/chip-tool/zap-generated/test/Commands.h index 26be2fb5b4c935..5fd032665223ff 100644 --- a/zzz_generated/chip-tool/zap-generated/test/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/test/Commands.h @@ -65351,7 +65351,7 @@ class TestClusterComplexTypesSuite : public TestCommand class TestConstraintsSuite : public TestCommand { public: - TestConstraintsSuite(CredentialIssuerCommands * credsIssuerConfig) : TestCommand("TestConstraints", 45, credsIssuerConfig) + TestConstraintsSuite(CredentialIssuerCommands * credsIssuerConfig) : TestCommand("TestConstraints", 55, credsIssuerConfig) { AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); AddArgument("cluster", &mCluster); @@ -65573,7 +65573,8 @@ class TestConstraintsSuite : public TestCommand { chip::CharSpan value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); - VerifyOrReturn(CheckConstraintIsHexString("value", value, false)); + VerifyOrReturn(CheckConstraintIsUpperCase("value", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("value", value, true)); } break; case 30: @@ -65584,7 +65585,8 @@ class TestConstraintsSuite : public TestCommand { chip::CharSpan value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); - VerifyOrReturn(CheckConstraintIsHexString("value", value, true)); + VerifyOrReturn(CheckConstraintIsUpperCase("value", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("value", value, true)); } break; case 32: @@ -65593,10 +65595,10 @@ class TestConstraintsSuite : public TestCommand case 33: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); { - chip::app::DataModel::Nullable value; + chip::CharSpan value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); - VerifyOrReturn(CheckValueNonNull("nullableInt8u", value)); - VerifyOrReturn(CheckValue("nullableInt8u.Value()", value.Value(), 0U)); + VerifyOrReturn(CheckConstraintIsUpperCase("value", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("value", value, false)); } break; case 34: @@ -65605,8 +65607,10 @@ class TestConstraintsSuite : public TestCommand case 35: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); { - chip::app::DataModel::Nullable value; + chip::CharSpan value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + VerifyOrReturn(CheckConstraintIsUpperCase("value", value, false)); + VerifyOrReturn(CheckConstraintIsLowerCase("value", value, true)); } break; case 36: @@ -65615,14 +65619,70 @@ class TestConstraintsSuite : public TestCommand case 37: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); { - chip::app::DataModel::Nullable value; + chip::CharSpan value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + VerifyOrReturn(CheckConstraintIsUpperCase("value", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("value", value, true)); } break; case 38: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; case 39: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::CharSpan value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + VerifyOrReturn(CheckConstraintIsHexString("value", value, false)); + } + break; + case 40: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 41: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::CharSpan value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + VerifyOrReturn(CheckConstraintIsHexString("value", value, true)); + } + break; + case 42: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 43: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::app::DataModel::Nullable value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + VerifyOrReturn(CheckValueNonNull("nullableInt8u", value)); + VerifyOrReturn(CheckValue("nullableInt8u.Value()", value.Value(), 0U)); + } + break; + case 44: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 45: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::app::DataModel::Nullable value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + } + break; + case 46: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 47: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::app::DataModel::Nullable value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + } + break; + case 48: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 49: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); { chip::app::DataModel::Nullable value; @@ -65632,27 +65692,27 @@ class TestConstraintsSuite : public TestCommand chip::ByteSpan(chip::Uint8::from_const_char(""), 0))); } break; - case 40: + case 50: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; - case 41: + case 51: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); { chip::app::DataModel::Nullable value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); } break; - case 42: + case 52: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; - case 43: + case 53: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); { chip::app::DataModel::Nullable value; VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); } break; - case 44: + case 54: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; default: @@ -65853,46 +65913,111 @@ class TestConstraintsSuite : public TestCommand chip::NullOptional); } case 28: { - LogStep(28, "Write attribute CHAR_STRING Value"); + LogStep(28, "Write attribute CHAR_STRING Value with only digits"); ListFreer listFreer; chip::CharSpan value; - value = chip::Span("ABCDEF012Vgarbage: not in length on purpose", 10); + value = chip::Span("1234567890garbage: not in length on purpose", 10); return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, chip::NullOptional, chip::NullOptional); } case 29: { - LogStep(29, "Read attribute CHAR_STRING Value isHexString Constraints"); + LogStep(29, "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, chip::NullOptional); } case 30: { - LogStep(30, "Write attribute CHAR_STRING Value"); + LogStep(30, "Write attribute CHAR_STRING Value with only non-letters"); ListFreer listFreer; chip::CharSpan value; - value = chip::Span("ABCDEF0123garbage: not in length on purpose", 10); + value = chip::Span("12.4,76:garbage: not in length on purpose", 8); return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, chip::NullOptional, chip::NullOptional); } case 31: { - LogStep(31, "Read attribute CHAR_STRING Value isHexString Constraints"); + LogStep(31, "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, chip::NullOptional); } case 32: { - LogStep(32, "Write attribute CHAR_STRING Value Back to Default Value"); + LogStep(32, "Write attribute CHAR_STRING Value with uppercase letters and symbols"); ListFreer listFreer; chip::CharSpan value; - value = chip::Span("garbage: not in length on purpose", 0); + value = chip::Span("ABC;.* garbage: not in length on purpose", 7); return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, chip::NullOptional, chip::NullOptional); } case 33: { - LogStep(33, "Read attribute NULLABLE_INT8U Default Value"); - return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, true, + LogStep(33, "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, chip::NullOptional); } case 34: { - LogStep(34, "Write attribute NULLABLE_INT8U with a value"); + LogStep(34, "Write attribute CHAR_STRING Value with lowercase letters and symbols"); + ListFreer listFreer; + chip::CharSpan value; + value = chip::Span("abc;.* garbage: not in length on purpose", 7); + return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, + chip::NullOptional, chip::NullOptional); + } + case 35: { + LogStep(35, "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, + chip::NullOptional); + } + case 36: { + LogStep(36, "Write attribute CHAR_STRING Value which is empty"); + ListFreer listFreer; + chip::CharSpan value; + value = chip::Span("garbage: not in length on purpose", 0); + return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, + chip::NullOptional, chip::NullOptional); + } + case 37: { + LogStep(37, "Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, + chip::NullOptional); + } + case 38: { + LogStep(38, "Write attribute CHAR_STRING Value"); + ListFreer listFreer; + chip::CharSpan value; + value = chip::Span("ABCDEF012Vgarbage: not in length on purpose", 10); + return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, + chip::NullOptional, chip::NullOptional); + } + case 39: { + LogStep(39, "Read attribute CHAR_STRING Value isHexString Constraints"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, + chip::NullOptional); + } + case 40: { + LogStep(40, "Write attribute CHAR_STRING Value"); + ListFreer listFreer; + chip::CharSpan value; + value = chip::Span("ABCDEF0123garbage: not in length on purpose", 10); + return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, + chip::NullOptional, chip::NullOptional); + } + case 41: { + LogStep(41, "Read attribute CHAR_STRING Value isHexString Constraints"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, true, + chip::NullOptional); + } + case 42: { + LogStep(42, "Write attribute CHAR_STRING Value Back to Default Value"); + ListFreer listFreer; + chip::CharSpan value; + value = chip::Span("garbage: not in length on purpose", 0); + return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::CharString::Id, value, + chip::NullOptional, chip::NullOptional); + } + case 43: { + LogStep(43, "Read attribute NULLABLE_INT8U Default Value"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, true, + chip::NullOptional); + } + case 44: { + LogStep(44, "Write attribute NULLABLE_INT8U with a value"); ListFreer listFreer; chip::app::DataModel::Nullable value; value.SetNonNull(); @@ -65900,26 +66025,26 @@ class TestConstraintsSuite : public TestCommand return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, value, chip::NullOptional, chip::NullOptional); } - case 35: { - LogStep(35, "Read attribute NULLABLE_INT8U with a value"); + case 45: { + LogStep(45, "Read attribute NULLABLE_INT8U with a value"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, true, chip::NullOptional); } - case 36: { - LogStep(36, "Write attribute NULLABLE_INT8U without a value"); + case 46: { + LogStep(46, "Write attribute NULLABLE_INT8U without a value"); ListFreer listFreer; chip::app::DataModel::Nullable value; value.SetNull(); return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, value, chip::NullOptional, chip::NullOptional); } - case 37: { - LogStep(37, "Read attribute NULLABLE_INT8U with a value"); + case 47: { + LogStep(47, "Read attribute NULLABLE_INT8U with a value"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, true, chip::NullOptional); } - case 38: { - LogStep(38, "Write attribute NULLABLE_INT8U back to Default Value"); + case 48: { + LogStep(48, "Write attribute NULLABLE_INT8U back to Default Value"); ListFreer listFreer; chip::app::DataModel::Nullable value; value.SetNonNull(); @@ -65927,13 +66052,13 @@ class TestConstraintsSuite : public TestCommand return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableInt8u::Id, value, chip::NullOptional, chip::NullOptional); } - case 39: { - LogStep(39, "Read attribute NULLABLE_OCTET_STRING Default Value"); + case 49: { + LogStep(49, "Read attribute NULLABLE_OCTET_STRING Default Value"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableOctetString::Id, true, chip::NullOptional); } - case 40: { - LogStep(40, "Write attribute NULLABLE_OCTET_STRING"); + case 50: { + LogStep(50, "Write attribute NULLABLE_OCTET_STRING"); ListFreer listFreer; chip::app::DataModel::Nullable value; value.SetNonNull(); @@ -65941,26 +66066,26 @@ class TestConstraintsSuite : public TestCommand return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableOctetString::Id, value, chip::NullOptional, chip::NullOptional); } - case 41: { - LogStep(41, "Read attribute NULLABLE_OCTET_STRING"); + case 51: { + LogStep(51, "Read attribute NULLABLE_OCTET_STRING"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableOctetString::Id, true, chip::NullOptional); } - case 42: { - LogStep(42, "Write attribute NULLABLE_OCTET_STRING"); + case 52: { + LogStep(52, "Write attribute NULLABLE_OCTET_STRING"); ListFreer listFreer; chip::app::DataModel::Nullable value; value.SetNull(); return WriteAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableOctetString::Id, value, chip::NullOptional, chip::NullOptional); } - case 43: { - LogStep(43, "Read attribute NULLABLE_OCTET_STRING"); + case 53: { + LogStep(53, "Read attribute NULLABLE_OCTET_STRING"); return ReadAttribute(kIdentityAlpha, GetEndpoint(1), UnitTesting::Id, UnitTesting::Attributes::NullableOctetString::Id, true, chip::NullOptional); } - case 44: { - LogStep(44, "Write attribute NULLABLE_OCTET_STRING back to Default Value"); + case 54: { + LogStep(54, "Write attribute NULLABLE_OCTET_STRING back to Default Value"); ListFreer listFreer; chip::app::DataModel::Nullable value; value.SetNonNull(); diff --git a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h index a0495741bf95b9..9ef1f81f31958c 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h @@ -95789,72 +95789,119 @@ class TestConstraints : public TestCommandBridge { err = TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_27(); break; case 28: - ChipLogProgress(chipTool, " ***** Test Step 28 : Write attribute CHAR_STRING Value\n"); - err = TestWriteAttributeCharStringValue_28(); + ChipLogProgress(chipTool, " ***** Test Step 28 : Write attribute CHAR_STRING Value with only digits\n"); + err = TestWriteAttributeCharStringValueWithOnlyDigits_28(); break; case 29: - ChipLogProgress(chipTool, " ***** Test Step 29 : Read attribute CHAR_STRING Value isHexString Constraints\n"); - err = TestReadAttributeCharStringValueIsHexStringConstraints_29(); + ChipLogProgress( + chipTool, " ***** Test Step 29 : Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints\n"); + err = TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_29(); break; case 30: - ChipLogProgress(chipTool, " ***** Test Step 30 : Write attribute CHAR_STRING Value\n"); - err = TestWriteAttributeCharStringValue_30(); + ChipLogProgress(chipTool, " ***** Test Step 30 : Write attribute CHAR_STRING Value with only non-letters\n"); + err = TestWriteAttributeCharStringValueWithOnlyNonLetters_30(); break; case 31: - ChipLogProgress(chipTool, " ***** Test Step 31 : Read attribute CHAR_STRING Value isHexString Constraints\n"); - err = TestReadAttributeCharStringValueIsHexStringConstraints_31(); + ChipLogProgress( + chipTool, " ***** Test Step 31 : Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints\n"); + err = TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_31(); break; case 32: - ChipLogProgress(chipTool, " ***** Test Step 32 : Write attribute CHAR_STRING Value Back to Default Value\n"); - err = TestWriteAttributeCharStringValueBackToDefaultValue_32(); + ChipLogProgress( + chipTool, " ***** Test Step 32 : Write attribute CHAR_STRING Value with uppercase letters and symbols\n"); + err = TestWriteAttributeCharStringValueWithUppercaseLettersAndSymbols_32(); break; case 33: - ChipLogProgress(chipTool, " ***** Test Step 33 : Read attribute NULLABLE_INT8U Default Value\n"); - err = TestReadAttributeNullableInt8uDefaultValue_33(); + ChipLogProgress( + chipTool, " ***** Test Step 33 : Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints\n"); + err = TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_33(); break; case 34: - ChipLogProgress(chipTool, " ***** Test Step 34 : Write attribute NULLABLE_INT8U with a value\n"); - err = TestWriteAttributeNullableInt8uWithAValue_34(); + ChipLogProgress( + chipTool, " ***** Test Step 34 : Write attribute CHAR_STRING Value with lowercase letters and symbols\n"); + err = TestWriteAttributeCharStringValueWithLowercaseLettersAndSymbols_34(); break; case 35: - ChipLogProgress(chipTool, " ***** Test Step 35 : Read attribute NULLABLE_INT8U with a value\n"); - err = TestReadAttributeNullableInt8uWithAValue_35(); + ChipLogProgress( + chipTool, " ***** Test Step 35 : Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints\n"); + err = TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_35(); break; case 36: - ChipLogProgress(chipTool, " ***** Test Step 36 : Write attribute NULLABLE_INT8U without a value\n"); - err = TestWriteAttributeNullableInt8uWithoutAValue_36(); + ChipLogProgress(chipTool, " ***** Test Step 36 : Write attribute CHAR_STRING Value which is empty\n"); + err = TestWriteAttributeCharStringValueWhichIsEmpty_36(); break; case 37: - ChipLogProgress(chipTool, " ***** Test Step 37 : Read attribute NULLABLE_INT8U with a value\n"); - err = TestReadAttributeNullableInt8uWithAValue_37(); + ChipLogProgress( + chipTool, " ***** Test Step 37 : Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints\n"); + err = TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_37(); break; case 38: - ChipLogProgress(chipTool, " ***** Test Step 38 : Write attribute NULLABLE_INT8U back to Default Value\n"); - err = TestWriteAttributeNullableInt8uBackToDefaultValue_38(); + ChipLogProgress(chipTool, " ***** Test Step 38 : Write attribute CHAR_STRING Value\n"); + err = TestWriteAttributeCharStringValue_38(); break; case 39: - ChipLogProgress(chipTool, " ***** Test Step 39 : Read attribute NULLABLE_OCTET_STRING Default Value\n"); - err = TestReadAttributeNullableOctetStringDefaultValue_39(); + ChipLogProgress(chipTool, " ***** Test Step 39 : Read attribute CHAR_STRING Value isHexString Constraints\n"); + err = TestReadAttributeCharStringValueIsHexStringConstraints_39(); break; case 40: - ChipLogProgress(chipTool, " ***** Test Step 40 : Write attribute NULLABLE_OCTET_STRING\n"); - err = TestWriteAttributeNullableOctetString_40(); + ChipLogProgress(chipTool, " ***** Test Step 40 : Write attribute CHAR_STRING Value\n"); + err = TestWriteAttributeCharStringValue_40(); break; case 41: - ChipLogProgress(chipTool, " ***** Test Step 41 : Read attribute NULLABLE_OCTET_STRING\n"); - err = TestReadAttributeNullableOctetString_41(); + ChipLogProgress(chipTool, " ***** Test Step 41 : Read attribute CHAR_STRING Value isHexString Constraints\n"); + err = TestReadAttributeCharStringValueIsHexStringConstraints_41(); break; case 42: - ChipLogProgress(chipTool, " ***** Test Step 42 : Write attribute NULLABLE_OCTET_STRING\n"); - err = TestWriteAttributeNullableOctetString_42(); + ChipLogProgress(chipTool, " ***** Test Step 42 : Write attribute CHAR_STRING Value Back to Default Value\n"); + err = TestWriteAttributeCharStringValueBackToDefaultValue_42(); break; case 43: - ChipLogProgress(chipTool, " ***** Test Step 43 : Read attribute NULLABLE_OCTET_STRING\n"); - err = TestReadAttributeNullableOctetString_43(); + ChipLogProgress(chipTool, " ***** Test Step 43 : Read attribute NULLABLE_INT8U Default Value\n"); + err = TestReadAttributeNullableInt8uDefaultValue_43(); break; case 44: - ChipLogProgress(chipTool, " ***** Test Step 44 : Write attribute NULLABLE_OCTET_STRING back to Default Value\n"); - err = TestWriteAttributeNullableOctetStringBackToDefaultValue_44(); + ChipLogProgress(chipTool, " ***** Test Step 44 : Write attribute NULLABLE_INT8U with a value\n"); + err = TestWriteAttributeNullableInt8uWithAValue_44(); + break; + case 45: + ChipLogProgress(chipTool, " ***** Test Step 45 : Read attribute NULLABLE_INT8U with a value\n"); + err = TestReadAttributeNullableInt8uWithAValue_45(); + break; + case 46: + ChipLogProgress(chipTool, " ***** Test Step 46 : Write attribute NULLABLE_INT8U without a value\n"); + err = TestWriteAttributeNullableInt8uWithoutAValue_46(); + break; + case 47: + ChipLogProgress(chipTool, " ***** Test Step 47 : Read attribute NULLABLE_INT8U with a value\n"); + err = TestReadAttributeNullableInt8uWithAValue_47(); + break; + case 48: + ChipLogProgress(chipTool, " ***** Test Step 48 : Write attribute NULLABLE_INT8U back to Default Value\n"); + err = TestWriteAttributeNullableInt8uBackToDefaultValue_48(); + break; + case 49: + ChipLogProgress(chipTool, " ***** Test Step 49 : Read attribute NULLABLE_OCTET_STRING Default Value\n"); + err = TestReadAttributeNullableOctetStringDefaultValue_49(); + break; + case 50: + ChipLogProgress(chipTool, " ***** Test Step 50 : Write attribute NULLABLE_OCTET_STRING\n"); + err = TestWriteAttributeNullableOctetString_50(); + break; + case 51: + ChipLogProgress(chipTool, " ***** Test Step 51 : Read attribute NULLABLE_OCTET_STRING\n"); + err = TestReadAttributeNullableOctetString_51(); + break; + case 52: + ChipLogProgress(chipTool, " ***** Test Step 52 : Write attribute NULLABLE_OCTET_STRING\n"); + err = TestWriteAttributeNullableOctetString_52(); + break; + case 53: + ChipLogProgress(chipTool, " ***** Test Step 53 : Read attribute NULLABLE_OCTET_STRING\n"); + err = TestReadAttributeNullableOctetString_53(); + break; + case 54: + ChipLogProgress(chipTool, " ***** Test Step 54 : Write attribute NULLABLE_OCTET_STRING back to Default Value\n"); + err = TestWriteAttributeNullableOctetStringBackToDefaultValue_54(); break; } @@ -96002,6 +96049,36 @@ class TestConstraints : public TestCommandBridge { case 44: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; + case 45: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 46: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 47: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 48: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 49: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 50: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 51: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 52: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 53: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 54: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; } // Go on to the next test. @@ -96015,7 +96092,7 @@ class TestConstraints : public TestCommandBridge { private: std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 45; + const uint16_t mTestCount = 55; chip::Optional mNodeId; chip::Optional mCluster; @@ -96604,7 +96681,214 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeCharStringValue_28() + CHIP_ERROR TestWriteAttributeCharStringValueWithOnlyDigits_28() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id charStringArgument; + charStringArgument = @"1234567890"; + [cluster writeAttributeCharStringWithValue:charStringArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Write attribute CHAR_STRING Value with only digits Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_29() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + [cluster readAttributeCharStringWithCompletion:^(NSString * _Nullable value, NSError * _Nullable err) { + NSLog(@"Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + VerifyOrReturn(CheckConstraintIsUpperCase("charString", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("charString", value, true)); + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestWriteAttributeCharStringValueWithOnlyNonLetters_30() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id charStringArgument; + charStringArgument = @"12.4,76:"; + [cluster writeAttributeCharStringWithValue:charStringArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Write attribute CHAR_STRING Value with only non-letters Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_31() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + [cluster readAttributeCharStringWithCompletion:^(NSString * _Nullable value, NSError * _Nullable err) { + NSLog(@"Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + VerifyOrReturn(CheckConstraintIsUpperCase("charString", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("charString", value, true)); + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestWriteAttributeCharStringValueWithUppercaseLettersAndSymbols_32() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id charStringArgument; + charStringArgument = @"ABC;.* "; + [cluster writeAttributeCharStringWithValue:charStringArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Write attribute CHAR_STRING Value with uppercase letters and symbols Error: %@", + err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_33() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + [cluster readAttributeCharStringWithCompletion:^(NSString * _Nullable value, NSError * _Nullable err) { + NSLog(@"Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + VerifyOrReturn(CheckConstraintIsUpperCase("charString", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("charString", value, false)); + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestWriteAttributeCharStringValueWithLowercaseLettersAndSymbols_34() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id charStringArgument; + charStringArgument = @"abc;.* "; + [cluster writeAttributeCharStringWithValue:charStringArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Write attribute CHAR_STRING Value with lowercase letters and symbols Error: %@", + err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_35() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + [cluster readAttributeCharStringWithCompletion:^(NSString * _Nullable value, NSError * _Nullable err) { + NSLog(@"Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + VerifyOrReturn(CheckConstraintIsUpperCase("charString", value, false)); + VerifyOrReturn(CheckConstraintIsLowerCase("charString", value, true)); + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestWriteAttributeCharStringValueWhichIsEmpty_36() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id charStringArgument; + charStringArgument = @""; + [cluster writeAttributeCharStringWithValue:charStringArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Write attribute CHAR_STRING Value which is empty Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestReadAttributeCharStringValueIsLowerCaseIsUpperCaseConstraints_37() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterUnitTesting alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + [cluster readAttributeCharStringWithCompletion:^(NSString * _Nullable value, NSError * _Nullable err) { + NSLog(@"Read attribute CHAR_STRING Value isLowerCase/isUpperCase Constraints Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + VerifyOrReturn(CheckConstraintIsUpperCase("charString", value, true)); + VerifyOrReturn(CheckConstraintIsLowerCase("charString", value, true)); + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestWriteAttributeCharStringValue_38() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96625,7 +96909,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeCharStringValueIsHexStringConstraints_29() + CHIP_ERROR TestReadAttributeCharStringValueIsHexStringConstraints_39() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96644,7 +96928,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeCharStringValue_30() + CHIP_ERROR TestWriteAttributeCharStringValue_40() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96665,7 +96949,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeCharStringValueIsHexStringConstraints_31() + CHIP_ERROR TestReadAttributeCharStringValueIsHexStringConstraints_41() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96684,7 +96968,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeCharStringValueBackToDefaultValue_32() + CHIP_ERROR TestWriteAttributeCharStringValueBackToDefaultValue_42() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96705,7 +96989,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeNullableInt8uDefaultValue_33() + CHIP_ERROR TestReadAttributeNullableInt8uDefaultValue_43() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96729,7 +97013,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeNullableInt8uWithAValue_34() + CHIP_ERROR TestWriteAttributeNullableInt8uWithAValue_44() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96750,7 +97034,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeNullableInt8uWithAValue_35() + CHIP_ERROR TestReadAttributeNullableInt8uWithAValue_45() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96771,7 +97055,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeNullableInt8uWithoutAValue_36() + CHIP_ERROR TestWriteAttributeNullableInt8uWithoutAValue_46() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96792,7 +97076,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeNullableInt8uWithAValue_37() + CHIP_ERROR TestReadAttributeNullableInt8uWithAValue_47() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96813,7 +97097,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeNullableInt8uBackToDefaultValue_38() + CHIP_ERROR TestWriteAttributeNullableInt8uBackToDefaultValue_48() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96834,7 +97118,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeNullableOctetStringDefaultValue_39() + CHIP_ERROR TestReadAttributeNullableOctetStringDefaultValue_49() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96859,7 +97143,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeNullableOctetString_40() + CHIP_ERROR TestWriteAttributeNullableOctetString_50() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96880,7 +97164,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeNullableOctetString_41() + CHIP_ERROR TestReadAttributeNullableOctetString_51() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96901,7 +97185,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeNullableOctetString_42() + CHIP_ERROR TestWriteAttributeNullableOctetString_52() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96922,7 +97206,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadAttributeNullableOctetString_43() + CHIP_ERROR TestReadAttributeNullableOctetString_53() { MTRBaseDevice * device = GetDevice("alpha"); @@ -96943,7 +97227,7 @@ class TestConstraints : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestWriteAttributeNullableOctetStringBackToDefaultValue_44() + CHIP_ERROR TestWriteAttributeNullableOctetStringBackToDefaultValue_54() { MTRBaseDevice * device = GetDevice("alpha"); From b4fb147dc47ec6bb95b174f3b8fdebf7f2088891 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Mon, 15 May 2023 16:04:40 +0200 Subject: [PATCH 21/36] [matter_yamltests] Properly convert wait values from str to int if necessary in the WaitFor command (#26541) --- .../matter_yamltests/pseudo_clusters/clusters/delay_commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/delay_commands.py b/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/delay_commands.py index 0536dd2bfb4110..fdb949da9b1449 100644 --- a/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/delay_commands.py +++ b/scripts/py_matter_yamltests/matter_yamltests/pseudo_clusters/clusters/delay_commands.py @@ -58,7 +58,7 @@ async def WaitForMs(self, request): duration_in_ms = argument['value'] sys.stdout.flush() - time.sleep(duration_in_ms / 1000) + time.sleep(int(duration_in_ms) / 1000) async def WaitForMessage(self, request): AccessoryServerBridge.waitForMessage(request) From ef7e6062508581d956fd86e29792efae554b4efe Mon Sep 17 00:00:00 2001 From: Evgeny Margolis Date: Mon, 15 May 2023 08:39:19 -1000 Subject: [PATCH 22/36] Implemented ExtractSerialNumberFromX509Cert() Method (#26485) --- src/crypto/CHIPCryptoPAL.h | 22 ++++++---- src/crypto/CHIPCryptoPALOpenSSL.cpp | 33 +++++++++++++- src/crypto/CHIPCryptoPALPSA.cpp | 36 ++++++++++++++- src/crypto/CHIPCryptoPALmbedTLS.cpp | 36 ++++++++++++++- src/crypto/tests/CHIPCryptoPALTest.cpp | 44 ++++++++++++++++++- .../common/crypto/CHIPCryptoPALTinyCrypt.cpp | 36 ++++++++++++++- .../crypto/CHIPCryptoPALNXPUltrafastP256.cpp | 36 ++++++++++++++- .../silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp | 36 ++++++++++++++- .../silabs/efr32/CHIPCryptoPALPsaEfr32.cpp | 36 ++++++++++++++- 9 files changed, 299 insertions(+), 16 deletions(-) diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index 6df3dc3a631572..3640cdbc372ec9 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -43,13 +43,14 @@ namespace Crypto { constexpr size_t kMax_x509_Certificate_Length = 600; -constexpr size_t kP256_FE_Length = 32; -constexpr size_t kP256_ECDSA_Signature_Length_Raw = (2 * kP256_FE_Length); -constexpr size_t kP256_Point_Length = (2 * kP256_FE_Length + 1); -constexpr size_t kSHA256_Hash_Length = 32; -constexpr size_t kSHA1_Hash_Length = 20; -constexpr size_t kSubjectKeyIdentifierLength = kSHA1_Hash_Length; -constexpr size_t kAuthorityKeyIdentifierLength = kSHA1_Hash_Length; +constexpr size_t kP256_FE_Length = 32; +constexpr size_t kP256_ECDSA_Signature_Length_Raw = (2 * kP256_FE_Length); +constexpr size_t kP256_Point_Length = (2 * kP256_FE_Length + 1); +constexpr size_t kSHA256_Hash_Length = 32; +constexpr size_t kSHA1_Hash_Length = 20; +constexpr size_t kSubjectKeyIdentifierLength = kSHA1_Hash_Length; +constexpr size_t kAuthorityKeyIdentifierLength = kSHA1_Hash_Length; +constexpr size_t kMaxCertificateSerialNumberLength = 20; constexpr size_t CHIP_CRYPTO_GROUP_SIZE_BYTES = kP256_FE_Length; constexpr size_t CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES = kP256_Point_Length; @@ -1566,6 +1567,11 @@ CHIP_ERROR ExtractSKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan **/ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & akid); +/** + * @brief Extracts Serial Number from X509 Certificate. + **/ +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber); + /** * @brief Checks for resigned version of the certificate in the list and returns it. * diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index ad3180447e8022..08ad564452cd90 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -1970,6 +1970,37 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + X509 * x509certificate = nullptr; + auto * pCertificate = Uint8::to_const_uchar(certificate.data()); + const unsigned char ** ppCertificate = &pCertificate; + const ASN1_INTEGER * serialNumberASN1 = nullptr; + size_t serialNumberLen = 0; + + VerifyOrReturnError(!certificate.empty() && CanCastTo(certificate.size()), CHIP_ERROR_INVALID_ARGUMENT); + + x509certificate = d2i_X509(nullptr, ppCertificate, static_cast(certificate.size())); + VerifyOrExit(x509certificate != nullptr, err = CHIP_ERROR_NO_MEMORY); + + serialNumberASN1 = X509_get_serialNumber(x509certificate); + VerifyOrExit(serialNumberASN1 != nullptr, err = CHIP_ERROR_INTERNAL); + VerifyOrExit(serialNumberASN1->data != nullptr, err = CHIP_ERROR_INTERNAL); + VerifyOrExit(CanCastTo(serialNumberASN1->length), err = CHIP_ERROR_INTERNAL); + + serialNumberLen = static_cast(serialNumberASN1->length); + VerifyOrExit(serialNumberLen <= serialNumber.size(), err = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), serialNumberASN1->data, serialNumberLen); + serialNumber.reduce_size(serialNumberLen); + +exit: + X509_free(x509certificate); + + return err; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { ASN1_OBJECT * commonNameObj = OBJ_txt2obj("2.5.4.3", 1); diff --git a/src/crypto/CHIPCryptoPALPSA.cpp b/src/crypto/CHIPCryptoPALPSA.cpp index 3fc7c31e5dd4f2..6a5e488031caac 100644 --- a/src/crypto/CHIPCryptoPALPSA.cpp +++ b/src/crypto/CHIPCryptoPALPSA.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-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. @@ -1651,6 +1651,40 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbed_cert; + + mbedtls_x509_crt_init(&mbed_cert); + + result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + len = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + VerifyOrExit(len <= serialNumber.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), p, len); + serialNumber.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbed_cert); + +#else + (void) certificate; + (void) serialNumber; + CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) + + return error; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) diff --git a/src/crypto/CHIPCryptoPALmbedTLS.cpp b/src/crypto/CHIPCryptoPALmbedTLS.cpp index ae887e755c2330..ec11cd17a9f8aa 100644 --- a/src/crypto/CHIPCryptoPALmbedTLS.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLS.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -1768,6 +1768,40 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbed_cert; + + mbedtls_x509_crt_init(&mbed_cert); + + result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + len = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + VerifyOrExit(len <= serialNumber.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), p, len); + serialNumber.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbed_cert); + +#else + (void) certificate; + (void) serialNumber; + CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) + + return error; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) diff --git a/src/crypto/tests/CHIPCryptoPALTest.cpp b/src/crypto/tests/CHIPCryptoPALTest.cpp index f8d4b476d719c4..269acf11fb428b 100644 --- a/src/crypto/tests/CHIPCryptoPALTest.cpp +++ b/src/crypto/tests/CHIPCryptoPALTest.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -2133,6 +2133,47 @@ static void TestAKID_x509Extraction(nlTestSuite * inSuite, void * inContext) } } +static void TestSerialNumber_x509Extraction(nlTestSuite * inSuite, void * inContext) +{ + using namespace TestCerts; + + HeapChecker heapChecker(inSuite); + CHIP_ERROR err = CHIP_NO_ERROR; + + struct SerialNumberTestCase + { + uint8_t Cert; + ByteSpan mExpectedResult; + }; + + const uint8_t serialNumberRoot01[] = { 0x53, 0x4c, 0x45, 0x82, 0x73, 0x62, 0x35, 0x14 }; + const uint8_t serialNumberICA01[] = { 0x69, 0xd8, 0x6a, 0x8d, 0x80, 0xfc, 0x8f, 0x5d }; + const uint8_t serialNumberNode02_08[] = { 0x3e, 0x67, 0x94, 0x70, 0x7a, 0xec, 0xb8, 0x15 }; + + // clang-format off + static SerialNumberTestCase sSerialNumberTestCases[] = { + // Cert Expected Output + // ==================================================== + { TestCert::kRoot01, ByteSpan(serialNumberRoot01) }, + { TestCert::kICA01, ByteSpan(serialNumberICA01) }, + { TestCert::kNode02_08, ByteSpan(serialNumberNode02_08) }, + }; + // clang-format on + + for (auto & testCase : sSerialNumberTestCases) + { + ByteSpan cert; + err = GetTestCert(testCase.Cert, TestCertLoadFlags::kDERForm, cert); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + + uint8_t serialNumberBuf[kMaxCertificateSerialNumberLength] = { 0 }; + MutableByteSpan serialNumber(serialNumberBuf); + err = ExtractSerialNumberFromX509Cert(cert, serialNumber); + NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, serialNumber.data_equal(testCase.mExpectedResult)); + } +} + static void TestVIDPID_StringExtraction(nlTestSuite * inSuite, void * inContext) { HeapChecker heapChecker(inSuite); @@ -2560,6 +2601,7 @@ static const nlTest sTests[] = { NL_TEST_DEF("Test x509 Certificate Timestamp Validation", TestX509_IssuingTimestampValidation), NL_TEST_DEF("Test Subject Key Id Extraction from x509 Certificate", TestSKID_x509Extraction), NL_TEST_DEF("Test Authority Key Id Extraction from x509 Certificate", TestAKID_x509Extraction), + NL_TEST_DEF("Test Serial Number Extraction from x509 Certificate", TestSerialNumber_x509Extraction), NL_TEST_DEF("Test Vendor ID and Product ID Extraction from Attribute String", TestVIDPID_StringExtraction), NL_TEST_DEF("Test Vendor ID and Product ID Extraction from x509 Attestation Certificate", TestVIDPID_x509Extraction), NL_TEST_DEF("Test Replace Resigned Certificate Version if Found", TestX509_ReplaceCertIfResignedCertFound), diff --git a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp index 4bf07e11a93ffc..292096f2a91fcd 100644 --- a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -1604,6 +1604,40 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbed_cert; + + mbedtls_x509_crt_init(&mbed_cert); + + result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + len = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + VerifyOrExit(len <= serialNumber.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), p, len); + serialNumber.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbed_cert); + +#else + (void) certificate; + (void) serialNumber; + CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) + + return error; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) diff --git a/src/platform/nxp/k32w/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp b/src/platform/nxp/k32w/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp index 032438dd042101..6660105df48985 100644 --- a/src/platform/nxp/k32w/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp +++ b/src/platform/nxp/k32w/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -1573,6 +1573,40 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbed_cert; + + mbedtls_x509_crt_init(&mbed_cert); + + result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + len = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + VerifyOrExit(len <= serialNumber.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), p, len); + serialNumber.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbed_cert); + +#else + (void) certificate; + (void) serialNumber; + CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) + + return error; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) diff --git a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp index 1d8c9a293d438d..cfc4a5ec683cab 100644 --- a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -1604,6 +1604,40 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbed_cert; + + mbedtls_x509_crt_init(&mbed_cert); + + result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + len = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + VerifyOrExit(len <= serialNumber.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), p, len); + serialNumber.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbed_cert); + +#else + (void) certificate; + (void) serialNumber; + CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) + + return error; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) diff --git a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp index 955b4489906887..236efb1d453172 100644 --- a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp +++ b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020-2022 Project CHIP Authors + * Copyright (c) 2020-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. @@ -1965,6 +1965,40 @@ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan return ExtractKIDFromX509Cert(false, certificate, akid); } +CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbed_cert; + + mbedtls_x509_crt_init(&mbed_cert); + + result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + len = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(serial).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + VerifyOrExit(len <= serialNumber.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(serialNumber.data(), p, len); + serialNumber.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbed_cert); + +#else + (void) certificate; + (void) serialNumber; + CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) + + return error; +} + CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) From 6e6a2a62f0c8479baf628d9cb4320003f6b279d1 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 14:48:14 -0400 Subject: [PATCH 23/36] Make pigweed set up clang-format on M1/M2 macs as well. (#26579) The way our codegen works right now expects everyone to be able to run the same version of clang-format from the pigweed setup. But pigweed by default does not install clang (and hence clang-format) on ARM macs. This adds the ARM mac version of clang to the set of things we install in addition to the default pigweed bits. The SHA is unfortunately hardcoded to match the current SHA that pigweed uses on other platforms, but the lint should make sure we don't break that. --- .github/workflows/lint.yml | 5 +++ scripts/lints/clang-format-version-matches.py | 43 +++++++++++++++++++ scripts/setup/clang.json | 9 ++++ scripts/setup/environment.json | 1 + 4 files changed, 58 insertions(+) create mode 100755 scripts/lints/clang-format-version-matches.py create mode 100644 scripts/setup/clang.json diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index fef2d3e1c8dabf..129a1de287cc6b 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -214,3 +214,8 @@ jobs: if: always() run: | git grep -n 'SuccessOrExit(CHIP_ERROR' -- './*' ':(exclude).github/workflows/lint.yml' && exit 1 || exit 0 + + - name: Check that our hardcoded SHA for clang-format on ARM mac matches the pigweed SHA. + if: always() + run: | + ./scripts/lints/clang-format-version-matches.py diff --git a/scripts/lints/clang-format-version-matches.py b/scripts/lints/clang-format-version-matches.py new file mode 100755 index 00000000000000..09bf7eda7d8e15 --- /dev/null +++ b/scripts/lints/clang-format-version-matches.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2021 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 json +import os + +CHIP_ROOT_DIR = os.path.realpath( + os.path.join(os.path.dirname(__file__), '../..')) + + +def readClangRevision(jsonFileName): + with open(os.path.join(CHIP_ROOT_DIR, jsonFileName)) as file: + data = json.load(file) + + packages = data['packages'] + for package in packages: + if package['path'].startswith('fuchsia/third_party/clang/'): + return package['tags'] + + raise Exception('Could not find clang package in %s' % jsonFileName) + + +pigweed_revision = readClangRevision('third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/cipd_setup/pigweed.json') + +our_file = 'scripts/setup/clang.json' +our_revision = readClangRevision(our_file) + +if our_revision != pigweed_revision: + raise Exception('In %s, "%s" should be changed to "%s"' % (our_file, our_revision, pigweed_revision)) diff --git a/scripts/setup/clang.json b/scripts/setup/clang.json new file mode 100644 index 00000000000000..a1f1e6d449e5b6 --- /dev/null +++ b/scripts/setup/clang.json @@ -0,0 +1,9 @@ +{ + "packages": [ + { + "path": "fuchsia/third_party/clang/mac-arm64", + "platforms": ["mac-arm64"], + "tags": ["git_revision:3a20597776a5d2920e511d81653b4d2b6ca0c855"] + } + ] +} diff --git a/scripts/setup/environment.json b/scripts/setup/environment.json index ebe77d9db6dbc8..6c32bb62ebe8e4 100644 --- a/scripts/setup/environment.json +++ b/scripts/setup/environment.json @@ -2,6 +2,7 @@ "cipd_package_files": [ "third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/cipd_setup/arm.json", "third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/cipd_setup/pigweed.json", + "scripts/setup/clang.json", "scripts/setup/python.json", "scripts/setup/zap.json" ], From 9352f8615961e7057ec4ac1e13aeeada9d9287dc Mon Sep 17 00:00:00 2001 From: yunhanw-google Date: Mon, 15 May 2023 17:22:44 -0700 Subject: [PATCH 24/36] Fix JNI type casts in matter jni layer (#26559) --- .../clusterclient/WildcardFragment.kt | 2 +- .../PairOnNetworkLongImInvokeCommand.kt | 2 +- .../ContentAppEndpointManagerImpl.java | 4 +- .../service/ContentAppAgentService.java | 12 +- .../tv/server/service/MatterServant.java | 50 ++-- .../java/ContentAppAttributeDelegate.cpp | 2 +- .../java/ContentAppAttributeDelegate.h | 2 +- .../java/ContentAppCommandDelegate.cpp | 4 +- .../android/java/ContentAppCommandDelegate.h | 2 +- examples/tv-app/android/java/TVApp-JNI.cpp | 4 +- .../com/matter/tv/server/tvapp/Clusters.java | 234 +++++++++--------- .../tvapp/ContentAppEndpointManager.java | 4 +- .../src/com/matter/tv/server/tvapp/TvApp.java | 2 +- .../matter/tv/server/tvapp/TvAppCallback.java | 2 +- src/controller/java/AndroidCallbacks.cpp | 45 ++-- .../java/AndroidCurrentFabricRemover.cpp | 2 +- .../java/AndroidDeviceControllerWrapper.cpp | 5 +- .../model/AttributeWriteRequest.java | 8 +- .../model/ChipAttributePath.java | 2 +- .../devicecontroller/model/ChipEventPath.java | 2 +- .../devicecontroller/model/ClusterState.java | 6 +- .../devicecontroller/model/InvokeElement.java | 2 +- .../devicecontroller/model/NodeState.java | 2 +- src/lib/support/JniReferences.cpp | 2 +- 24 files changed, 197 insertions(+), 205 deletions(-) diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt index c665adaeb97b47..4ceb3d2164147b 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt @@ -450,7 +450,7 @@ class WildcardFragment : Fragment() { private suspend fun readCurrentFabricIndex() : UInt { val context = requireContext() - val endpointId = 0L + val endpointId = 0 val clusterId = 62L // OperationalCredentials val attributeId = 5L // CurrentFabricIndex val deviceId = addressUpdateFragment.deviceId diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt index 7eb38a0d4f950a..f509ad32d38732 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt @@ -79,7 +79,7 @@ class PairOnNetworkLongImInvokeCommand( tlvWriter.endStructure() val element: InvokeElement = InvokeElement.newInstance( /* endpointId= */ - 0L, CLUSTER_ID_IDENTIFY, IDENTIFY_COMMAND, tlvWriter.getEncoded(), null + 0, CLUSTER_ID_IDENTIFY, IDENTIFY_COMMAND, tlvWriter.getEncoded(), null ) currentCommissioner() diff --git a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java index 6f4e6eb98c52e2..f93897f2d2a582 100644 --- a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java +++ b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java @@ -18,7 +18,7 @@ public ContentAppEndpointManagerImpl(Context context) { this.context = context; } - public String sendCommand(int endpointId, int clusterId, int commandId, String commandPayload) { + public String sendCommand(int endpointId, long clusterId, long commandId, String commandPayload) { Log.d(TAG, "Received a command for endpointId " + endpointId + ". Message " + commandPayload); ContentApp discoveredApp = @@ -54,7 +54,7 @@ public String sendCommand(int endpointId, int clusterId, int commandId, String c return "Success"; } - public String readAttribute(int endpointId, int clusterId, int attributeId) { + public String readAttribute(int endpointId, long clusterId, long attributeId) { Log.d( TAG, "Received a attribute read request for endpointId " diff --git a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java index cc311b9481e194..542e8e4f93f33c 100644 --- a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java +++ b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java @@ -107,12 +107,12 @@ public IBinder onBind(final Intent intent) { } public static String sendCommand( - Context context, String packageName, int clusterId, int commandId, String payload) { + Context context, String packageName, long clusterId, long commandId, String payload) { Intent in = new Intent(MatterIntentConstants.ACTION_MATTER_COMMAND); Bundle extras = new Bundle(); extras.putByteArray(MatterIntentConstants.EXTRA_COMMAND_PAYLOAD, payload.getBytes()); - extras.putInt(MatterIntentConstants.EXTRA_COMMAND_ID, commandId); - extras.putInt(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); + extras.putLong(MatterIntentConstants.EXTRA_COMMAND_ID, commandId); + extras.putLong(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); in.putExtras(extras); in.setPackage(packageName); int flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES; @@ -127,13 +127,13 @@ public static String sendCommand( } public static String sendAttributeReadRequest( - Context context, String packageName, int clusterId, int attributeId) { + Context context, String packageName, long clusterId, long attributeId) { Intent in = new Intent(MatterIntentConstants.ACTION_MATTER_COMMAND); Bundle extras = new Bundle(); extras.putString( MatterIntentConstants.EXTRA_ATTRIBUTE_ACTION, MatterIntentConstants.ATTRIBUTE_ACTION_READ); - extras.putInt(MatterIntentConstants.EXTRA_ATTRIBUTE_ID, attributeId); - extras.putInt(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); + extras.putLong(MatterIntentConstants.EXTRA_ATTRIBUTE_ID, attributeId); + extras.putLong(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); in.putExtras(extras); in.setPackage(packageName); int flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES; diff --git a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java index 00963fa1f7e2ae..79b02f01386769 100644 --- a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java +++ b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java @@ -82,36 +82,26 @@ public void init(@NonNull Context context) { mTvApp = new TvApp( (app, clusterId, endpoint) -> { - switch (clusterId) { - case Clusters.ClusterId_KeypadInput: - app.setKeypadInputManager(endpoint, new KeypadInputManagerStub(endpoint)); - break; - case Clusters.ClusterId_WakeOnLan: - app.setWakeOnLanManager(endpoint, new WakeOnLanManagerStub(endpoint)); - break; - case Clusters.ClusterId_MediaInput: - app.setMediaInputManager(endpoint, new MediaInputManagerStub(endpoint)); - break; - case Clusters.ClusterId_ContentLauncher: - app.setContentLaunchManager(endpoint, new ContentLaunchManagerStub(endpoint)); - break; - case Clusters.ClusterId_LowPower: - app.setLowPowerManager(endpoint, new LowPowerManagerStub(endpoint)); - break; - case Clusters.ClusterId_MediaPlayback: - app.setMediaPlaybackManager(endpoint, new MediaPlaybackManagerStub(endpoint)); - break; - case Clusters.ClusterId_Channel: - app.setChannelManager(endpoint, new ChannelManagerStub(endpoint)); - break; - case Clusters.ClusterId_OnOff: - mOnOffEndpoint = endpoint; - app.setOnOffManager(endpoint, new OnOffManagerStub(endpoint)); - break; - case Clusters.ClusterId_LevelControl: - mLevelEndpoint = endpoint; - app.setLevelManager(endpoint, new LevelManagerStub(endpoint)); - break; + if (clusterId == Clusters.ClusterId_KeypadInput) { + app.setKeypadInputManager(endpoint, new KeypadInputManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_WakeOnLan) { + app.setWakeOnLanManager(endpoint, new WakeOnLanManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_MediaInput) { + app.setMediaInputManager(endpoint, new MediaInputManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_ContentLauncher) { + app.setContentLaunchManager(endpoint, new ContentLaunchManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_LowPower) { + app.setLowPowerManager(endpoint, new LowPowerManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_MediaPlayback) { + app.setMediaPlaybackManager(endpoint, new MediaPlaybackManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_Channel) { + app.setChannelManager(endpoint, new ChannelManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_OnOff) { + mOnOffEndpoint = endpoint; + app.setOnOffManager(endpoint, new OnOffManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_LevelControl) { + mLevelEndpoint = endpoint; + app.setLevelManager(endpoint, new LevelManagerStub(endpoint)); } }); mTvApp.setDACProvider(new DACProviderStub()); diff --git a/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp b/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp index 0565d364e2719f..54e4ee633ce7d9 100644 --- a/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp @@ -49,7 +49,7 @@ std::string ContentAppAttributeDelegate::Read(const chip::app::ConcreteReadAttri jstring resp = (jstring) env->CallObjectMethod(mContentAppEndpointManager, mReadAttributeMethod, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); + static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentAppAttributeDelegate::Read"); diff --git a/examples/tv-app/android/java/ContentAppAttributeDelegate.h b/examples/tv-app/android/java/ContentAppAttributeDelegate.h index 4ec02712201d7b..9d22bbc5fff7aa 100644 --- a/examples/tv-app/android/java/ContentAppAttributeDelegate.h +++ b/examples/tv-app/android/java/ContentAppAttributeDelegate.h @@ -67,7 +67,7 @@ class ContentAppAttributeDelegate VerifyOrReturn(ContentAppEndpointManagerClass != nullptr, ChipLogError(Zcl, "Failed to get ContentAppEndpointManager Java class")); - mReadAttributeMethod = env->GetMethodID(ContentAppEndpointManagerClass, "readAttribute", "(III)Ljava/lang/String;"); + mReadAttributeMethod = env->GetMethodID(ContentAppEndpointManagerClass, "readAttribute", "(IJJ)Ljava/lang/String;"); if (mReadAttributeMethod == nullptr) { ChipLogError(Zcl, "Failed to access ContentAppEndpointManager 'readAttribute' method"); diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp index b477b75333866b..1ad6ef2fa40311 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp @@ -73,7 +73,7 @@ void ContentAppCommandDelegate::InvokeCommand(CommandHandlerInterface::HandlerCo jstring resp = (jstring) env->CallObjectMethod( mContentAppEndpointManager, mSendCommandMethod, static_cast(handlerContext.mRequestPath.mEndpointId), - static_cast(handlerContext.mRequestPath.mClusterId), static_cast(handlerContext.mRequestPath.mCommandId), + static_cast(handlerContext.mRequestPath.mClusterId), static_cast(handlerContext.mRequestPath.mCommandId), jsonString.jniValue()); if (env->ExceptionCheck()) { @@ -108,7 +108,7 @@ Status ContentAppCommandDelegate::InvokeCommand(EndpointId epId, ClusterId clust jstring resp = (jstring) env->CallObjectMethod(mContentAppEndpointManager, mSendCommandMethod, static_cast(epId), - static_cast(clusterId), static_cast(commandId), jsonString.jniValue()); + static_cast(clusterId), static_cast(commandId), jsonString.jniValue()); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentAppCommandDelegate::sendCommand"); diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.h b/examples/tv-app/android/java/ContentAppCommandDelegate.h index 610a2c7069f29d..156fa287f2ef9a 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.h +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.h @@ -96,7 +96,7 @@ class ContentAppCommandDelegate : public CommandHandlerInterface ChipLogError(Zcl, "Failed to get ContentAppEndpointManager Java class")); mSendCommandMethod = - env->GetMethodID(ContentAppEndpointManagerClass, "sendCommand", "(IIILjava/lang/String;)Ljava/lang/String;"); + env->GetMethodID(ContentAppEndpointManagerClass, "sendCommand", "(IJJLjava/lang/String;)Ljava/lang/String;"); if (mSendCommandMethod == nullptr) { ChipLogError(Zcl, "Failed to access ContentAppEndpointManager 'sendCommand' method"); diff --git a/examples/tv-app/android/java/TVApp-JNI.cpp b/examples/tv-app/android/java/TVApp-JNI.cpp index a8eeba37344923..d7081419c0c645 100644 --- a/examples/tv-app/android/java/TVApp-JNI.cpp +++ b/examples/tv-app/android/java/TVApp-JNI.cpp @@ -64,7 +64,7 @@ void TvAppJNI::InitializeWithObjects(jobject app) jclass managerClass = env->GetObjectClass(mTvAppObject); VerifyOrReturn(managerClass != nullptr, ChipLogError(Zcl, "Failed to get TvAppJNI Java class")); - mPostClusterInitMethod = env->GetMethodID(managerClass, "postClusterInit", "(II)V"); + mPostClusterInitMethod = env->GetMethodID(managerClass, "postClusterInit", "(JI)V"); if (mPostClusterInitMethod == nullptr) { ChipLogError(Zcl, "Failed to access ChannelManager 'postClusterInit' method"); @@ -79,7 +79,7 @@ void TvAppJNI::PostClusterInit(int clusterId, int endpoint) VerifyOrReturn(mTvAppObject != nullptr, ChipLogError(Zcl, "TvAppJNI::mTvAppObject null")); VerifyOrReturn(mPostClusterInitMethod != nullptr, ChipLogError(Zcl, "TvAppJNI::mPostClusterInitMethod null")); - env->CallVoidMethod(mTvAppObject, mPostClusterInitMethod, static_cast(clusterId), static_cast(endpoint)); + env->CallVoidMethod(mTvAppObject, mPostClusterInitMethod, static_cast(clusterId), static_cast(endpoint)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Failed to call TvAppJNI 'postClusterInit' method"); diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java index 7d7761a7b2050b..5322af22c97ae5 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java @@ -18,121 +18,121 @@ public class Clusters { - public static final int ClusterId_PowerConfiguration = 0x00000001; - public static final int ClusterId_DeviceTemperatureConfiguration = 0x00000002; - public static final int ClusterId_Identify = 0x00000003; - public static final int ClusterId_Groups = 0x00000004; - public static final int ClusterId_Scenes = 0x00000005; - public static final int ClusterId_OnOff = 0x00000006; - public static final int ClusterId_OnOffSwitchConfiguration = 0x00000007; - public static final int ClusterId_LevelControl = 0x00000008; - public static final int ClusterId_Alarms = 0x00000009; - public static final int ClusterId_Time = 0x0000000A; - public static final int ClusterId_BinaryInputBasic = 0x0000000F; - public static final int ClusterId_PowerProfile = 0x0000001A; - public static final int ClusterId_ApplianceControl = 0x0000001B; - public static final int ClusterId_PulseWidthModulation = 0x0000001C; - public static final int ClusterId_Descriptor = 0x0000001D; - public static final int ClusterId_Binding = 0x0000001E; - public static final int ClusterId_AccessControl = 0x0000001F; - public static final int ClusterId_PollControl = 0x00000020; - public static final int ClusterId_Actions = 0x00000025; - public static final int ClusterId_Basic = 0x00000028; - public static final int ClusterId_OtaSoftwareUpdateProvider = 0x00000029; - public static final int ClusterId_OtaSoftwareUpdateRequestor = 0x0000002A; - public static final int ClusterId_LocalizationConfiguration = 0x0000002B; - public static final int ClusterId_LocalizationTimeFormat = 0x0000002C; - public static final int ClusterId_LocalizationUnit = 0x0000002D; - public static final int ClusterId_PowerSourceConfiguration = 0x0000002E; - public static final int ClusterId_PowerSource = 0x0000002F; - public static final int ClusterId_GeneralCommissioning = 0x00000030; - public static final int ClusterId_NetworkCommissioning = 0x00000031; - public static final int ClusterId_DiagnosticLogs = 0x00000032; - public static final int ClusterId_GeneralDiagnostics = 0x00000033; - public static final int ClusterId_SoftwareDiagnostics = 0x00000034; - public static final int ClusterId_ThreadNetworkDiagnostics = 0x00000035; - public static final int ClusterId_WiFiNetworkDiagnostics = 0x00000036; - public static final int ClusterId_EthernetNetworkDiagnostics = 0x00000037; - public static final int ClusterId_TimeSynchronization = 0x00000038; - public static final int ClusterId_BridgedDeviceBasic = 0x00000039; - public static final int ClusterId_Switch = 0x0000003B; - public static final int ClusterId_AdministratorCommissioning = 0x0000003C; - public static final int ClusterId_OperationalCredentials = 0x0000003E; - public static final int ClusterId_GroupKeyManagement = 0x0000003F; - public static final int ClusterId_FixedLabel = 0x00000040; - public static final int ClusterId_UserLabel = 0x00000041; - public static final int ClusterId_ProxyConfiguration = 0x00000042; - public static final int ClusterId_ProxyDiscovery = 0x00000043; - public static final int ClusterId_ProxyValid = 0x00000044; - public static final int ClusterId_BooleanState = 0x00000045; - public static final int ClusterId_ModeSelect = 0x00000050; - public static final int ClusterId_ShadeConfiguration = 0x00000100; - public static final int ClusterId_DoorLock = 0x00000101; - public static final int ClusterId_WindowCovering = 0x00000102; - public static final int ClusterId_BarrierControl = 0x00000103; - public static final int ClusterId_PumpConfigurationAndControl = 0x00000200; - public static final int ClusterId_Thermostat = 0x00000201; - public static final int ClusterId_FanControl = 0x00000202; - public static final int ClusterId_DehumidificationControl = 0x00000203; - public static final int ClusterId_ThermostatUserInterfaceConfiguration = 0x00000204; - public static final int ClusterId_ColorControl = 0x00000300; - public static final int ClusterId_BallastConfiguration = 0x00000301; - public static final int ClusterId_IlluminanceMeasurement = 0x00000400; - public static final int ClusterId_TemperatureMeasurement = 0x00000402; - public static final int ClusterId_PressureMeasurement = 0x00000403; - public static final int ClusterId_FlowMeasurement = 0x00000404; - public static final int ClusterId_RelativeHumidityMeasurement = 0x00000405; - public static final int ClusterId_OccupancySensing = 0x00000406; - public static final int ClusterId_CarbonMonoxideConcentrationMeasurement = 0x0000040C; - public static final int ClusterId_CarbonDioxideConcentrationMeasurement = 0x0000040D; - public static final int ClusterId_EthyleneConcentrationMeasurement = 0x0000040E; - public static final int ClusterId_EthyleneOxideConcentrationMeasurement = 0x0000040F; - public static final int ClusterId_HydrogenConcentrationMeasurement = 0x00000410; - public static final int ClusterId_HydrogenSulphideConcentrationMeasurement = 0x00000411; - public static final int ClusterId_NitricOxideConcentrationMeasurement = 0x00000412; - public static final int ClusterId_NitrogenDioxideConcentrationMeasurement = 0x00000413; - public static final int ClusterId_OxygenConcentrationMeasurement = 0x00000414; - public static final int ClusterId_OzoneConcentrationMeasurement = 0x00000415; - public static final int ClusterId_SulfurDioxideConcentrationMeasurement = 0x00000416; - public static final int ClusterId_DissolvedOxygenConcentrationMeasurement = 0x00000417; - public static final int ClusterId_BromateConcentrationMeasurement = 0x00000418; - public static final int ClusterId_ChloraminesConcentrationMeasurement = 0x00000419; - public static final int ClusterId_ChlorineConcentrationMeasurement = 0x0000041A; - public static final int ClusterId_FecalColiformAndEColiConcentrationMeasurement = 0x0000041B; - public static final int ClusterId_FluorideConcentrationMeasurement = 0x0000041C; - public static final int ClusterId_HaloaceticAcidsConcentrationMeasurement = 0x0000041D; - public static final int ClusterId_TotalTrihalomethanesConcentrationMeasurement = 0x0000041E; - public static final int ClusterId_TotalColiformBacteriaConcentrationMeasurement = 0x0000041F; - public static final int ClusterId_TurbidityConcentrationMeasurement = 0x00000420; - public static final int ClusterId_CopperConcentrationMeasurement = 0x00000421; - public static final int ClusterId_LeadConcentrationMeasurement = 0x00000422; - public static final int ClusterId_ManganeseConcentrationMeasurement = 0x00000423; - public static final int ClusterId_SulfateConcentrationMeasurement = 0x00000424; - public static final int ClusterId_BromodichloromethaneConcentrationMeasurement = 0x00000425; - public static final int ClusterId_BromoformConcentrationMeasurement = 0x00000426; - public static final int ClusterId_ChlorodibromomethaneConcentrationMeasurement = 0x00000427; - public static final int ClusterId_ChloroformConcentrationMeasurement = 0x00000428; - public static final int ClusterId_SodiumConcentrationMeasurement = 0x00000429; - public static final int ClusterId_IasZone = 0x00000500; - public static final int ClusterId_IasAce = 0x00000501; - public static final int ClusterId_IasWd = 0x00000502; - public static final int ClusterId_WakeOnLan = 0x00000503; - public static final int ClusterId_Channel = 0x00000504; - public static final int ClusterId_TargetNavigator = 0x00000505; - public static final int ClusterId_MediaPlayback = 0x00000506; - public static final int ClusterId_MediaInput = 0x00000507; - public static final int ClusterId_LowPower = 0x00000508; - public static final int ClusterId_KeypadInput = 0x00000509; - public static final int ClusterId_ContentLauncher = 0x0000050A; - public static final int ClusterId_AudioOutput = 0x0000050B; - public static final int ClusterId_ApplicationLauncher = 0x0000050C; - public static final int ClusterId_ApplicationBasic = 0x0000050D; - public static final int ClusterId_AccountLogin = 0x0000050E; - public static final int ClusterId_TestCluster = 0xFFF1FC05; - public static final int ClusterId_Messaging = 0x00000703; - public static final int ClusterId_ApplianceIdentification = 0x00000B00; - public static final int ClusterId_MeterIdentification = 0x00000B01; - public static final int ClusterId_ApplianceEventsAndAlert = 0x00000B02; - public static final int ClusterId_ApplianceStatistics = 0x00000B03; - public static final int ClusterId_ElectricalMeasurement = 0x00000B04; + public static final long ClusterId_PowerConfiguration = 0x00000001; + public static final long ClusterId_DeviceTemperatureConfiguration = 0x00000002; + public static final long ClusterId_Identify = 0x00000003; + public static final long ClusterId_Groups = 0x00000004; + public static final long ClusterId_Scenes = 0x00000005; + public static final long ClusterId_OnOff = 0x00000006; + public static final long ClusterId_OnOffSwitchConfiguration = 0x00000007; + public static final long ClusterId_LevelControl = 0x00000008; + public static final long ClusterId_Alarms = 0x00000009; + public static final long ClusterId_Time = 0x0000000A; + public static final long ClusterId_BinaryInputBasic = 0x0000000F; + public static final long ClusterId_PowerProfile = 0x0000001A; + public static final long ClusterId_ApplianceControl = 0x0000001B; + public static final long ClusterId_PulseWidthModulation = 0x0000001C; + public static final long ClusterId_Descriptor = 0x0000001D; + public static final long ClusterId_Binding = 0x0000001E; + public static final long ClusterId_AccessControl = 0x0000001F; + public static final long ClusterId_PollControl = 0x00000020; + public static final long ClusterId_Actions = 0x00000025; + public static final long ClusterId_Basic = 0x00000028; + public static final long ClusterId_OtaSoftwareUpdateProvider = 0x00000029; + public static final long ClusterId_OtaSoftwareUpdateRequestor = 0x0000002A; + public static final long ClusterId_LocalizationConfiguration = 0x0000002B; + public static final long ClusterId_LocalizationTimeFormat = 0x0000002C; + public static final long ClusterId_LocalizationUnit = 0x0000002D; + public static final long ClusterId_PowerSourceConfiguration = 0x0000002E; + public static final long ClusterId_PowerSource = 0x0000002F; + public static final long ClusterId_GeneralCommissioning = 0x00000030; + public static final long ClusterId_NetworkCommissioning = 0x00000031; + public static final long ClusterId_DiagnosticLogs = 0x00000032; + public static final long ClusterId_GeneralDiagnostics = 0x00000033; + public static final long ClusterId_SoftwareDiagnostics = 0x00000034; + public static final long ClusterId_ThreadNetworkDiagnostics = 0x00000035; + public static final long ClusterId_WiFiNetworkDiagnostics = 0x00000036; + public static final long ClusterId_EthernetNetworkDiagnostics = 0x00000037; + public static final long ClusterId_TimeSynchronization = 0x00000038; + public static final long ClusterId_BridgedDeviceBasic = 0x00000039; + public static final long ClusterId_Switch = 0x0000003B; + public static final long ClusterId_AdministratorCommissioning = 0x0000003C; + public static final long ClusterId_OperationalCredentials = 0x0000003E; + public static final long ClusterId_GroupKeyManagement = 0x0000003F; + public static final long ClusterId_FixedLabel = 0x00000040; + public static final long ClusterId_UserLabel = 0x00000041; + public static final long ClusterId_ProxyConfiguration = 0x00000042; + public static final long ClusterId_ProxyDiscovery = 0x00000043; + public static final long ClusterId_ProxyValid = 0x00000044; + public static final long ClusterId_BooleanState = 0x00000045; + public static final long ClusterId_ModeSelect = 0x00000050; + public static final long ClusterId_ShadeConfiguration = 0x00000100; + public static final long ClusterId_DoorLock = 0x00000101; + public static final long ClusterId_WindowCovering = 0x00000102; + public static final long ClusterId_BarrierControl = 0x00000103; + public static final long ClusterId_PumpConfigurationAndControl = 0x00000200; + public static final long ClusterId_Thermostat = 0x00000201; + public static final long ClusterId_FanControl = 0x00000202; + public static final long ClusterId_DehumidificationControl = 0x00000203; + public static final long ClusterId_ThermostatUserInterfaceConfiguration = 0x00000204; + public static final long ClusterId_ColorControl = 0x00000300; + public static final long ClusterId_BallastConfiguration = 0x00000301; + public static final long ClusterId_IlluminanceMeasurement = 0x00000400; + public static final long ClusterId_TemperatureMeasurement = 0x00000402; + public static final long ClusterId_PressureMeasurement = 0x00000403; + public static final long ClusterId_FlowMeasurement = 0x00000404; + public static final long ClusterId_RelativeHumidityMeasurement = 0x00000405; + public static final long ClusterId_OccupancySensing = 0x00000406; + public static final long ClusterId_CarbonMonoxideConcentrationMeasurement = 0x0000040C; + public static final long ClusterId_CarbonDioxideConcentrationMeasurement = 0x0000040D; + public static final long ClusterId_EthyleneConcentrationMeasurement = 0x0000040E; + public static final long ClusterId_EthyleneOxideConcentrationMeasurement = 0x0000040F; + public static final long ClusterId_HydrogenConcentrationMeasurement = 0x00000410; + public static final long ClusterId_HydrogenSulphideConcentrationMeasurement = 0x00000411; + public static final long ClusterId_NitricOxideConcentrationMeasurement = 0x00000412; + public static final long ClusterId_NitrogenDioxideConcentrationMeasurement = 0x00000413; + public static final long ClusterId_OxygenConcentrationMeasurement = 0x00000414; + public static final long ClusterId_OzoneConcentrationMeasurement = 0x00000415; + public static final long ClusterId_SulfurDioxideConcentrationMeasurement = 0x00000416; + public static final long ClusterId_DissolvedOxygenConcentrationMeasurement = 0x00000417; + public static final long ClusterId_BromateConcentrationMeasurement = 0x00000418; + public static final long ClusterId_ChloraminesConcentrationMeasurement = 0x00000419; + public static final long ClusterId_ChlorineConcentrationMeasurement = 0x0000041A; + public static final long ClusterId_FecalColiformAndEColiConcentrationMeasurement = 0x0000041B; + public static final long ClusterId_FluorideConcentrationMeasurement = 0x0000041C; + public static final long ClusterId_HaloaceticAcidsConcentrationMeasurement = 0x0000041D; + public static final long ClusterId_TotalTrihalomethanesConcentrationMeasurement = 0x0000041E; + public static final long ClusterId_TotalColiformBacteriaConcentrationMeasurement = 0x0000041F; + public static final long ClusterId_TurbidityConcentrationMeasurement = 0x00000420; + public static final long ClusterId_CopperConcentrationMeasurement = 0x00000421; + public static final long ClusterId_LeadConcentrationMeasurement = 0x00000422; + public static final long ClusterId_ManganeseConcentrationMeasurement = 0x00000423; + public static final long ClusterId_SulfateConcentrationMeasurement = 0x00000424; + public static final long ClusterId_BromodichloromethaneConcentrationMeasurement = 0x00000425; + public static final long ClusterId_BromoformConcentrationMeasurement = 0x00000426; + public static final long ClusterId_ChlorodibromomethaneConcentrationMeasurement = 0x00000427; + public static final long ClusterId_ChloroformConcentrationMeasurement = 0x00000428; + public static final long ClusterId_SodiumConcentrationMeasurement = 0x00000429; + public static final long ClusterId_IasZone = 0x00000500; + public static final long ClusterId_IasAce = 0x00000501; + public static final long ClusterId_IasWd = 0x00000502; + public static final long ClusterId_WakeOnLan = 0x00000503; + public static final long ClusterId_Channel = 0x00000504; + public static final long ClusterId_TargetNavigator = 0x00000505; + public static final long ClusterId_MediaPlayback = 0x00000506; + public static final long ClusterId_MediaInput = 0x00000507; + public static final long ClusterId_LowPower = 0x00000508; + public static final long ClusterId_KeypadInput = 0x00000509; + public static final long ClusterId_ContentLauncher = 0x0000050A; + public static final long ClusterId_AudioOutput = 0x0000050B; + public static final long ClusterId_ApplicationLauncher = 0x0000050C; + public static final long ClusterId_ApplicationBasic = 0x0000050D; + public static final long ClusterId_AccountLogin = 0x0000050E; + public static final long ClusterId_TestCluster = 0xFFF1FC05; + public static final long ClusterId_Messaging = 0x00000703; + public static final long ClusterId_ApplianceIdentification = 0x00000B00; + public static final long ClusterId_MeterIdentification = 0x00000B01; + public static final long ClusterId_ApplianceEventsAndAlert = 0x00000B02; + public static final long ClusterId_ApplianceStatistics = 0x00000B03; + public static final long ClusterId_ElectricalMeasurement = 0x00000B04; } diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java index 92c5e5243b85ad..ed6253fd446ed9 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java @@ -2,7 +2,7 @@ public interface ContentAppEndpointManager { - public String sendCommand(int endpointId, int clusterId, int commandId, String commandPayload); + public String sendCommand(int endpointId, long clusterId, long commandId, String commandPayload); - public String readAttribute(int endpointId, int clusterId, int attributeId); + public String readAttribute(int endpointId, long clusterId, long attributeId); } diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java index 92c41fdebc7e6f..d8bb564370afa4 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java @@ -28,7 +28,7 @@ public TvApp(TvAppCallback callback) { nativeInit(); } - private void postClusterInit(int clusterId, int endpoint) { + private void postClusterInit(long clusterId, int endpoint) { Log.d(TAG, "postClusterInit for " + clusterId + " at " + endpoint); if (mCallback != null) { mCallback.onClusterInit(this, clusterId, endpoint); diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java index 27d2c7e1aa1e2b..d5bf7a090bc0de 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java @@ -17,5 +17,5 @@ package com.matter.tv.server.tvapp; public interface TvAppCallback { - void onClusterInit(TvApp app, int clusterId, int endpoint); + void onClusterInit(TvApp app, long clusterId, int endpoint); } diff --git a/src/controller/java/AndroidCallbacks.cpp b/src/controller/java/AndroidCallbacks.cpp index 017f377b59e1d2..d004de149235cb 100644 --- a/src/controller/java/AndroidCallbacks.cpp +++ b/src/controller/java/AndroidCallbacks.cpp @@ -334,10 +334,10 @@ void ReportCallback::UpdateClusterDataVersion() // SetDataVersion to NodeState jmethodID setDataVersionMethod; - CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mNodeStateObj, "setDataVersion", "(IJI)V", &setDataVersionMethod); + CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mNodeStateObj, "setDataVersion", "(IJJ)V", &setDataVersionMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find setDataVersion method")); env->CallVoidMethod(mNodeStateObj, setDataVersionMethod, static_cast(lastConcreteClusterPath.mEndpointId), - static_cast(lastConcreteClusterPath.mClusterId), static_cast(committedDataVersion.Value())); + static_cast(lastConcreteClusterPath.mClusterId), static_cast(committedDataVersion.Value())); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); } @@ -428,11 +428,11 @@ CHIP_ERROR CreateChipAttributePath(const app::ConcreteDataAttributePath & aPath, JniClass attributePathJniCls(attributePathCls); jmethodID attributePathCtor = - env->GetStaticMethodID(attributePathCls, "newInstance", "(JJJ)Lchip/devicecontroller/model/ChipAttributePath;"); + env->GetStaticMethodID(attributePathCls, "newInstance", "(IJJ)Lchip/devicecontroller/model/ChipAttributePath;"); VerifyOrReturnError(attributePathCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); - outObj = - env->CallStaticObjectMethod(attributePathCls, attributePathCtor, aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId); + outObj = env->CallStaticObjectMethod(attributePathCls, attributePathCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); return err; @@ -449,7 +449,7 @@ CHIP_ERROR InvokeCallback::CreateInvokeElement(const app::ConcreteCommandPath & JniClass invokeElementJniCls(invokeElementCls); jmethodID invokeElementCtor = env->GetStaticMethodID(invokeElementCls, "newInstance", - "(JJJ[BLjava/lang/String;)Lchip/devicecontroller/model/InvokeElement;"); + "(IJJ[BLjava/lang/String;)Lchip/devicecontroller/model/InvokeElement;"); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); VerifyOrReturnError(invokeElementCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); @@ -480,13 +480,15 @@ CHIP_ERROR InvokeCallback::CreateInvokeElement(const app::ConcreteCommandPath & ReturnErrorOnFailure(err); UtfString jsonString(env, JsonToString(json).c_str()); - outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, aPath.mEndpointId, aPath.mClusterId, - aPath.mCommandId, jniByteArray.jniValue(), jsonString.jniValue()); + outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), + jniByteArray.jniValue(), jsonString.jniValue()); } else { - outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, aPath.mEndpointId, aPath.mClusterId, - aPath.mCommandId, nullptr, nullptr); + outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), nullptr, + nullptr); } VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); @@ -504,10 +506,11 @@ CHIP_ERROR ReportCallback::CreateChipEventPath(const app::ConcreteEventPath & aP JniClass eventPathJniCls(eventPathCls); jmethodID eventPathCtor = - env->GetStaticMethodID(eventPathCls, "newInstance", "(JJJ)Lchip/devicecontroller/model/ChipEventPath;"); + env->GetStaticMethodID(eventPathCls, "newInstance", "(IJJ)Lchip/devicecontroller/model/ChipEventPath;"); VerifyOrReturnError(eventPathCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); - outObj = env->CallStaticObjectMethod(eventPathCls, eventPathCtor, aPath.mEndpointId, aPath.mClusterId, aPath.mEventId); + outObj = env->CallStaticObjectMethod(eventPathCls, eventPathCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mEventId)); VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); return err; @@ -558,8 +561,9 @@ CHIP_ERROR ReportCallback::OnResubscriptionNeeded(app::ReadClient * apReadClient env, mResubscriptionAttemptCallbackRef, "onResubscriptionAttempt", "(II)V", &onResubscriptionAttemptMethod)); DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(mResubscriptionAttemptCallbackRef, onResubscriptionAttemptMethod, aTerminationCause.AsInteger(), - apReadClient->ComputeTimeTillNextSubscription()); + env->CallVoidMethod(mResubscriptionAttemptCallbackRef, onResubscriptionAttemptMethod, + static_cast(aTerminationCause.AsInteger()), + static_cast(apReadClient->ComputeTimeTillNextSubscription())); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); return CHIP_NO_ERROR; } @@ -763,10 +767,11 @@ CHIP_ERROR ReportEventCallback::CreateChipEventPath(const app::ConcreteEventPath JniClass eventPathJniCls(eventPathCls); jmethodID eventPathCtor = - env->GetStaticMethodID(eventPathCls, "newInstance", "(JJJ)Lchip/devicecontroller/model/ChipEventPath;"); + env->GetStaticMethodID(eventPathCls, "newInstance", "(IJJ)Lchip/devicecontroller/model/ChipEventPath;"); VerifyOrReturnError(eventPathCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); - outObj = env->CallStaticObjectMethod(eventPathCls, eventPathCtor, aPath.mEndpointId, aPath.mClusterId, aPath.mEventId); + outObj = env->CallStaticObjectMethod(eventPathCls, eventPathCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mEventId)); VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); return err; @@ -811,8 +816,9 @@ CHIP_ERROR ReportEventCallback::OnResubscriptionNeeded(app::ReadClient * apReadC env, mResubscriptionAttemptCallbackRef, "onResubscriptionAttempt", "(II)V", &onResubscriptionAttemptMethod)); DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(mResubscriptionAttemptCallbackRef, onResubscriptionAttemptMethod, aTerminationCause.AsInteger(), - apReadClient->ComputeTimeTillNextSubscription()); + env->CallVoidMethod(mResubscriptionAttemptCallbackRef, onResubscriptionAttemptMethod, + static_cast(aTerminationCause.AsInteger()), + static_cast(apReadClient->ComputeTimeTillNextSubscription())); return CHIP_NO_ERROR; } @@ -996,8 +1002,7 @@ void InvokeCallback::OnResponse(app::CommandSender * apCommandSender, const app: VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onError method: %s", ErrorStr(err))); DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(mJavaCallbackRef, onResponseMethod, invokeElementObj, - static_cast>(aStatusIB.mStatus)); + env->CallVoidMethod(mJavaCallbackRef, onResponseMethod, invokeElementObj, static_cast(aStatusIB.mStatus)); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); } diff --git a/src/controller/java/AndroidCurrentFabricRemover.cpp b/src/controller/java/AndroidCurrentFabricRemover.cpp index 1029177ae3db31..4c4ab28412719c 100644 --- a/src/controller/java/AndroidCurrentFabricRemover.cpp +++ b/src/controller/java/AndroidCurrentFabricRemover.cpp @@ -38,7 +38,7 @@ AndroidCurrentFabricRemover::AndroidCurrentFabricRemover(DeviceController * cont env->ExceptionClear(); } - mOnErrorMethod = env->GetMethodID(callbackClass, "onError", "(IJ)V"); + mOnErrorMethod = env->GetMethodID(callbackClass, "onError", "(JI)V"); if (mOnErrorMethod == nullptr) { ChipLogError(Controller, "Failed to access callback 'onError' method"); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index b1c8b02ff2e597..466c7d6ba92bdb 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -528,7 +528,8 @@ void AndroidDeviceControllerWrapper::OnCommissioningComplete(NodeId deviceId, CH CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningComplete", "(JI)V", &onCommissioningCompleteMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format())); - env->CallVoidMethod(mJavaObjectRef, onCommissioningCompleteMethod, static_cast(deviceId), error.AsInteger()); + env->CallVoidMethod(mJavaObjectRef, onCommissioningCompleteMethod, static_cast(deviceId), + static_cast(error.AsInteger())); if (ssidStr != nullptr) { @@ -560,7 +561,7 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, UtfString jStageCompleted(env, StageToString(stageCompleted)); env->CallVoidMethod(mJavaObjectRef, onCommissioningStatusUpdateMethod, static_cast(peerId.GetNodeId()), - jStageCompleted.jniValue(), error.AsInteger()); + jStageCompleted.jniValue(), static_cast(error.AsInteger())); } void AndroidDeviceControllerWrapper::OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) diff --git a/src/controller/java/src/chip/devicecontroller/model/AttributeWriteRequest.java b/src/controller/java/src/chip/devicecontroller/model/AttributeWriteRequest.java index b479076e13e40a..0b74693480f5ba 100644 --- a/src/controller/java/src/chip/devicecontroller/model/AttributeWriteRequest.java +++ b/src/controller/java/src/chip/devicecontroller/model/AttributeWriteRequest.java @@ -107,7 +107,7 @@ public static AttributeWriteRequest newInstance( /** Create a new {@link AttributeWriteRequest} with only concrete ids. */ public static AttributeWriteRequest newInstance( - long endpointId, long clusterId, long attributeId, byte[] tlv) { + int endpointId, long clusterId, long attributeId, byte[] tlv) { return new AttributeWriteRequest( ChipPathId.forId(endpointId), ChipPathId.forId(clusterId), @@ -117,11 +117,7 @@ public static AttributeWriteRequest newInstance( } public static AttributeWriteRequest newInstance( - long endpointId, - long clusterId, - long attributeId, - byte[] tlv, - Optional dataVersion) { + int endpointId, long clusterId, long attributeId, byte[] tlv, Optional dataVersion) { return new AttributeWriteRequest( ChipPathId.forId(endpointId), ChipPathId.forId(clusterId), diff --git a/src/controller/java/src/chip/devicecontroller/model/ChipAttributePath.java b/src/controller/java/src/chip/devicecontroller/model/ChipAttributePath.java index 31d7a366994c2b..f4b085f0350de4 100644 --- a/src/controller/java/src/chip/devicecontroller/model/ChipAttributePath.java +++ b/src/controller/java/src/chip/devicecontroller/model/ChipAttributePath.java @@ -74,7 +74,7 @@ public static ChipAttributePath newInstance( } /** Create a new {@link ChipAttributePath} with only concrete ids. */ - public static ChipAttributePath newInstance(long endpointId, long clusterId, long attributeId) { + public static ChipAttributePath newInstance(int endpointId, long clusterId, long attributeId) { return new ChipAttributePath( ChipPathId.forId(endpointId), ChipPathId.forId(clusterId), ChipPathId.forId(attributeId)); } diff --git a/src/controller/java/src/chip/devicecontroller/model/ChipEventPath.java b/src/controller/java/src/chip/devicecontroller/model/ChipEventPath.java index b5d1a95315516a..5f6f7c6dcd6be5 100644 --- a/src/controller/java/src/chip/devicecontroller/model/ChipEventPath.java +++ b/src/controller/java/src/chip/devicecontroller/model/ChipEventPath.java @@ -98,7 +98,7 @@ public static ChipEventPath newInstance( /** Create a new {@link ChipEventPath} with only concrete ids. */ public static ChipEventPath newInstance( - long endpointId, long clusterId, long eventId, boolean isUrgent) { + int endpointId, long clusterId, long eventId, boolean isUrgent) { return new ChipEventPath( ChipPathId.forId(endpointId), ChipPathId.forId(clusterId), diff --git a/src/controller/java/src/chip/devicecontroller/model/ClusterState.java b/src/controller/java/src/chip/devicecontroller/model/ClusterState.java index d31069ceac2953..8507682968edc5 100644 --- a/src/controller/java/src/chip/devicecontroller/model/ClusterState.java +++ b/src/controller/java/src/chip/devicecontroller/model/ClusterState.java @@ -26,7 +26,7 @@ public final class ClusterState { private Map attributes; private Map> events; - private Optional dataVersion; + private Optional dataVersion; public ClusterState( Map attributes, Map> events) { @@ -43,11 +43,11 @@ public Map> getEventStates() { return events; } - public void setDataVersion(int version) { + public void setDataVersion(long version) { dataVersion = Optional.of(version); } - public Optional getDataVersion() { + public Optional getDataVersion() { return dataVersion; } diff --git a/src/controller/java/src/chip/devicecontroller/model/InvokeElement.java b/src/controller/java/src/chip/devicecontroller/model/InvokeElement.java index 413d5ac8f4e1dc..2ae4b55ff423e6 100644 --- a/src/controller/java/src/chip/devicecontroller/model/InvokeElement.java +++ b/src/controller/java/src/chip/devicecontroller/model/InvokeElement.java @@ -119,7 +119,7 @@ public static InvokeElement newInstance( /** Create a new {@link InvokeElement} with only concrete ids. */ public static InvokeElement newInstance( - long endpointId, + int endpointId, long clusterId, long commandId, @Nullable byte[] tlv, diff --git a/src/controller/java/src/chip/devicecontroller/model/NodeState.java b/src/controller/java/src/chip/devicecontroller/model/NodeState.java index 7e84997085bc00..c60e3b6205b2cd 100644 --- a/src/controller/java/src/chip/devicecontroller/model/NodeState.java +++ b/src/controller/java/src/chip/devicecontroller/model/NodeState.java @@ -35,7 +35,7 @@ public Map getEndpointStates() { } // Called from native code only, which ignores access modifiers. - private void setDataVersion(int endpointId, long clusterId, int dataVersion) { + private void setDataVersion(int endpointId, long clusterId, long dataVersion) { EndpointState endpointState = getEndpointState(endpointId); ClusterState clusterState = endpointState.getClusterState(clusterId); diff --git a/src/lib/support/JniReferences.cpp b/src/lib/support/JniReferences.cpp index 1a4fae9e22ff32..66c16eb74dc70a 100644 --- a/src/lib/support/JniReferences.cpp +++ b/src/lib/support/JniReferences.cpp @@ -290,7 +290,7 @@ CHIP_ERROR JniReferences::CallSubscriptionEstablished(jobject javaCallback, long &subscriptionEstablishedMethod); VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_JNI_ERROR_METHOD_NOT_FOUND); - env->CallVoidMethod(javaCallback, subscriptionEstablishedMethod, subscriptionId); + env->CallVoidMethod(javaCallback, subscriptionEstablishedMethod, static_cast(subscriptionId)); VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); return err; From db47b1bb2a961f618bf11f2df18210e08929eba6 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 21:44:56 -0400 Subject: [PATCH 25/36] Change Server to not validate certificate expiration by default. (#26530) If an explicit validity policy is injected that validates notBefore/notAfter, we will do that, but if the app author just doesn't think about time-based validation default to not validating, because there's a good chance it will just lead to unexpected failures due to bad clocks and whatnot. --- src/app/server/Server.cpp | 12 ++++++++++-- src/app/server/Server.h | 9 ++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index e741b9e34f0122..c0d3e108babe65 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -128,7 +128,14 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams) mOperationalKeystore = initParams.operationalKeystore; mOpCertStore = initParams.opCertStore; - mCertificateValidityPolicy.Init(initParams.certificateValidityPolicy); + if (initParams.certificateValidityPolicy) + { + mCertificateValidityPolicy.Init(initParams.certificateValidityPolicy); + } + else + { + mCertificateValidityPolicy.Init(&sDefaultCertValidityPolicy); + } #if defined(CHIP_SUPPORT_ENABLE_STORAGE_API_AUDIT) VerifyOrDie(chip::audit::ExecutePersistentStorageApiAudit(*mDeviceStorage)); @@ -531,11 +538,12 @@ void Server::ResumeSubscriptions() } #endif +Credentials::IgnoreCertificateValidityPeriodPolicy Server::sDefaultCertValidityPolicy; + KvsPersistentStorageDelegate CommonCaseDeviceServerInitParams::sKvsPersistenStorageDelegate; PersistentStorageOperationalKeystore CommonCaseDeviceServerInitParams::sPersistentStorageOperationalKeystore; Credentials::PersistentStorageOpCertStore CommonCaseDeviceServerInitParams::sPersistentStorageOpCertStore; Credentials::GroupDataProviderImpl CommonCaseDeviceServerInitParams::sGroupDataProvider; -Credentials::IgnoreCertificateValidityPeriodPolicy CommonCaseDeviceServerInitParams::sDefaultCertValidityPolicy; #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION SimpleSessionResumptionStorage CommonCaseDeviceServerInitParams::sSessionResumptionStorage; #endif diff --git a/src/app/server/Server.h b/src/app/server/Server.h index 0a6bc5c54801f6..eee11b0bc6ff60 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -233,10 +233,6 @@ struct CommonCaseDeviceServerInitParams : public ServerInitParams // Inject ACL storage. (Don't initialize it.) this->aclStorage = &sAclStorage; - // Inject certificate validation policy compatible with non-wall-clock-time-synced - // embedded systems. - this->certificateValidityPolicy = &sDefaultCertValidityPolicy; - #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS ChipLogProgress(AppServer, "Initializing subscription resumption storage..."); ReturnErrorOnFailure(sSubscriptionResumptionStorage.Init(this->persistentStorageDelegate)); @@ -253,7 +249,6 @@ struct CommonCaseDeviceServerInitParams : public ServerInitParams static PersistentStorageOperationalKeystore sPersistentStorageOperationalKeystore; static Credentials::PersistentStorageOpCertStore sPersistentStorageOpCertStore; static Credentials::GroupDataProviderImpl sGroupDataProvider; - static Credentials::IgnoreCertificateValidityPeriodPolicy sDefaultCertValidityPolicy; #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION static SimpleSessionResumptionStorage sSessionResumptionStorage; #endif @@ -554,6 +549,10 @@ class Server Ble::BleLayer * mBleLayer = nullptr; #endif + // By default, use a certificate validation policy compatible with non-wall-clock-time-synced + // embedded systems. + static Credentials::IgnoreCertificateValidityPeriodPolicy sDefaultCertValidityPolicy; + ServerTransportMgr mTransports; SessionManager mSessions; CASEServer mCASEServer; From 315668397c8d6d623f71930c8ab5a48187356ee8 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 21:45:27 -0400 Subject: [PATCH 26/36] Improve discovery logging in SetUpCodePairer. (#26534) We should log why we are ignoring discovered devices. --- src/controller/SetUpCodePairer.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/controller/SetUpCodePairer.cpp b/src/controller/SetUpCodePairer.cpp index ee5a31365ad82c..de32224c4fc9c6 100644 --- a/src/controller/SetUpCodePairer.cpp +++ b/src/controller/SetUpCodePairer.cpp @@ -309,6 +309,7 @@ bool SetUpCodePairer::NodeMatchesCurrentFilter(const Dnssd::DiscoveredNodeData & { if (nodeData.commissionData.commissioningMode == 0) { + ChipLogProgress(Controller, "Discovered device does not have an open commissioning window."); return false; } @@ -316,6 +317,7 @@ bool SetUpCodePairer::NodeMatchesCurrentFilter(const Dnssd::DiscoveredNodeData & if (IdIsPresent(mPayloadVendorID) && IdIsPresent(nodeData.commissionData.vendorId) && mPayloadVendorID != nodeData.commissionData.vendorId) { + ChipLogProgress(Controller, "Discovered device does not match our vendor id."); return false; } @@ -323,19 +325,28 @@ bool SetUpCodePairer::NodeMatchesCurrentFilter(const Dnssd::DiscoveredNodeData & if (IdIsPresent(mPayloadProductID) && IdIsPresent(nodeData.commissionData.productId) && mPayloadProductID != nodeData.commissionData.productId) { + ChipLogProgress(Controller, "Discovered device does not match our product id."); return false; } + bool discriminatorMatches = false; switch (mCurrentFilter.type) { case Dnssd::DiscoveryFilterType::kShortDiscriminator: - return ((nodeData.commissionData.longDiscriminator >> 8) & 0x0F) == mCurrentFilter.code; + discriminatorMatches = (((nodeData.commissionData.longDiscriminator >> 8) & 0x0F) == mCurrentFilter.code); + break; case Dnssd::DiscoveryFilterType::kLongDiscriminator: - return nodeData.commissionData.longDiscriminator == mCurrentFilter.code; + discriminatorMatches = (nodeData.commissionData.longDiscriminator == mCurrentFilter.code); + break; default: + ChipLogError(Controller, "Unknown filter type; all matches will fail"); return false; } - return false; + if (!discriminatorMatches) + { + ChipLogProgress(Controller, "Discovered device does not match our discriminator."); + } + return discriminatorMatches; } void SetUpCodePairer::NotifyCommissionableDeviceDiscovered(const Dnssd::DiscoveredNodeData & nodeData) From 5d033a5b42355b0b9f14c98cc319b4cace88ebf5 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 21:45:45 -0400 Subject: [PATCH 27/36] Rename Nullable::HasValidValue so people won't try to use it. (#26535) This function is a pretty specific thing, and people are confusing it with IsNull(). Rename to something that will make it less likely. --- .../dynamic-bridge-app/linux/include/data-model/DataModel.h | 4 ++-- src/app/data-model/Decode.h | 2 +- src/app/data-model/Encode.h | 2 +- src/app/data-model/Nullable.h | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h b/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h index cba8d3c9907129..053cd785aac472 100644 --- a/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h +++ b/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h @@ -201,7 +201,7 @@ CHIP_ERROR Encode(const ConcreteReadAttributePath & aPath, AttributeValueEncoder // CONFIG_BUILD_FOR_HOST_UNIT_TEST is true, so we can test how the other side // responds. #if !CONFIG_BUILD_FOR_HOST_UNIT_TEST - if (!x.HasValidValue()) + if (!x.ExistingValueInEncodableRange()) { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } @@ -313,7 +313,7 @@ CHIP_ERROR Decode(const ConcreteDataAttributePath & aPath, AttributeValueDecoder // We have a value; decode it. ReturnErrorOnFailure(Decode(aPath, aDecoder, x.SetNonNull())); - if (!x.HasValidValue()) + if (!x.ExistingValueInEncodableRange()) { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } diff --git a/src/app/data-model/Decode.h b/src/app/data-model/Decode.h index 5124fa44337a52..4acc96f138c50e 100644 --- a/src/app/data-model/Decode.h +++ b/src/app/data-model/Decode.h @@ -170,7 +170,7 @@ CHIP_ERROR Decode(TLV::TLVReader & reader, Nullable & x) // We have a value; decode it. ReturnErrorOnFailure(Decode(reader, x.SetNonNull())); - if (!x.HasValidValue()) + if (!x.ExistingValueInEncodableRange()) { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } diff --git a/src/app/data-model/Encode.h b/src/app/data-model/Encode.h index 0546098a74184d..84a32cf745983c 100644 --- a/src/app/data-model/Encode.h +++ b/src/app/data-model/Encode.h @@ -188,7 +188,7 @@ CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag, const Nullable & x) // CONFIG_BUILD_FOR_HOST_UNIT_TEST is true, so we can test how the other side // responds. #if !CONFIG_BUILD_FOR_HOST_UNIT_TEST - if (!x.HasValidValue()) + if (!x.ExistingValueInEncodableRange()) { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } diff --git a/src/app/data-model/Nullable.h b/src/app/data-model/Nullable.h index 844a7c1b385ae9..ad6bdaf9e2c172 100644 --- a/src/app/data-model/Nullable.h +++ b/src/app/data-model/Nullable.h @@ -65,7 +65,7 @@ struct Nullable : protected Optional template < typename U = std::decay_t, typename std::enable_if_t<(std::is_integral::value && !std::is_same::value) || std::is_enum::value, int> = 0> - constexpr bool HasValidValue() const + constexpr bool ExistingValueInEncodableRange() const { return NumericAttributeTraits::CanRepresentValue(/* isNullable = */ true, Value()); } @@ -74,7 +74,7 @@ struct Nullable : protected Optional template , typename std::enable_if_t<(!std::is_integral::value || std::is_same::value) && !std::is_enum::value, int> = 0> - constexpr bool HasValidValue() const + constexpr bool ExistingValueInEncodableRange() const { return true; } From 9a26662af8ebaaf4a59ce05d391f62d3b0570c9e Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 21:46:40 -0400 Subject: [PATCH 28/36] Add new time types that got addded to the spec. (#26547) * Add new time types that got addded to the spec. * Address review comment. --- .../py_matter_idl/matter_idl/generators/types.py | 3 +++ src/app/util/ember-compatibility-functions.cpp | 14 +++++++++----- src/app/zap-templates/common/override.js | 3 +++ .../zcl/data-model/chip/chip-types.xml | 9 +++++++++ .../app-common/zap-generated/attribute-size.h | 5 +++-- .../app-common/zap-generated/attribute-type.h | 3 +++ 6 files changed, 30 insertions(+), 7 deletions(-) diff --git a/scripts/py_matter_idl/matter_idl/generators/types.py b/scripts/py_matter_idl/matter_idl/generators/types.py index 65e09915703749..b8c9f37b1d179a 100644 --- a/scripts/py_matter_idl/matter_idl/generators/types.py +++ b/scripts/py_matter_idl/matter_idl/generators/types.py @@ -199,6 +199,7 @@ def is_struct(self) -> bool: "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), @@ -208,8 +209,10 @@ def is_struct(self) -> bool: "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), "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), diff --git a/src/app/util/ember-compatibility-functions.cpp b/src/app/util/ember-compatibility-functions.cpp index 7faf6116890300..4bde3b05be8178 100644 --- a/src/app/util/ember-compatibility-functions.cpp +++ b/src/app/util/ember-compatibility-functions.cpp @@ -103,6 +103,7 @@ EmberAfAttributeType BaseType(EmberAfAttributeType type) case ZCL_DATA_VER_ATTRIBUTE_TYPE: // Data Version case ZCL_BITMAP32_ATTRIBUTE_TYPE: // 32-bit bitmap case ZCL_EPOCH_S_ATTRIBUTE_TYPE: // Epoch Seconds + case ZCL_ELAPSED_S_ATTRIBUTE_TYPE: // Elapsed Seconds static_assert(std::is_same::value, "chip::Cluster is expected to be uint32_t, change this when necessary"); static_assert(std::is_same::value, @@ -121,11 +122,14 @@ EmberAfAttributeType BaseType(EmberAfAttributeType type) "chip::DataVersion is expected to be uint32_t, change this when necessary"); return ZCL_INT32U_ATTRIBUTE_TYPE; - case ZCL_EVENT_NO_ATTRIBUTE_TYPE: // Event Number - case ZCL_FABRIC_ID_ATTRIBUTE_TYPE: // Fabric Id - case ZCL_NODE_ID_ATTRIBUTE_TYPE: // Node Id - case ZCL_BITMAP64_ATTRIBUTE_TYPE: // 64-bit bitmap - case ZCL_EPOCH_US_ATTRIBUTE_TYPE: // Epoch Microseconds + case ZCL_EVENT_NO_ATTRIBUTE_TYPE: // Event Number + case ZCL_FABRIC_ID_ATTRIBUTE_TYPE: // Fabric Id + case ZCL_NODE_ID_ATTRIBUTE_TYPE: // Node Id + case ZCL_BITMAP64_ATTRIBUTE_TYPE: // 64-bit bitmap + case ZCL_EPOCH_US_ATTRIBUTE_TYPE: // Epoch Microseconds + case ZCL_POSIX_MS_ATTRIBUTE_TYPE: // POSIX Milliseconds + case ZCL_SYSTIME_MS_ATTRIBUTE_TYPE: // System time Milliseconds + case ZCL_SYSTIME_US_ATTRIBUTE_TYPE: // System time Microseconds static_assert(std::is_same::value, "chip::EventNumber is expected to be uint64_t, change this when necessary"); static_assert(std::is_same::value, diff --git a/src/app/zap-templates/common/override.js b/src/app/zap-templates/common/override.js index 9552bf4e113101..97a90a58af4a77 100644 --- a/src/app/zap-templates/common/override.js +++ b/src/app/zap-templates/common/override.js @@ -76,9 +76,12 @@ function atomicType(arg) return 'chip::Percent100ths'; case 'epoch_us': case 'systime_us': + case 'posix_ms': + case 'systime_ms': return 'uint64_t'; case 'epoch_s': case 'utc': + case 'elapsed_s': return 'uint32_t'; default: throw 'not overriding'; diff --git a/src/app/zap-templates/zcl/data-model/chip/chip-types.xml b/src/app/zap-templates/zcl/data-model/chip/chip-types.xml index c1bd6043813ff4..464b8bb31848ab 100644 --- a/src/app/zap-templates/zcl/data-model/chip/chip-types.xml +++ b/src/app/zap-templates/zcl/data-model/chip/chip-types.xml @@ -16,6 +16,12 @@ limitations under the License. --> + @@ -55,7 +61,10 @@ limitations under the License. + + + diff --git a/zzz_generated/app-common/app-common/zap-generated/attribute-size.h b/zzz_generated/app-common/app-common/zap-generated/attribute-size.h index 8d51c73d95580c..e2f7d4a0d160a9 100644 --- a/zzz_generated/app-common/app-common/zap-generated/attribute-size.h +++ b/zzz_generated/app-common/app-common/zap-generated/attribute-size.h @@ -27,8 +27,9 @@ ZCL_BOOLEAN_ATTRIBUTE_TYPE, 1, ZCL_BITMAP8_ATTRIBUTE_TYPE, 1, ZCL_BITMAP16_ATTRI ZCL_INT56U_ATTRIBUTE_TYPE, 7, ZCL_INT64U_ATTRIBUTE_TYPE, 8, ZCL_INT8S_ATTRIBUTE_TYPE, 1, ZCL_INT16S_ATTRIBUTE_TYPE, 2, ZCL_INT24S_ATTRIBUTE_TYPE, 3, ZCL_INT32S_ATTRIBUTE_TYPE, 4, ZCL_INT40S_ATTRIBUTE_TYPE, 5, ZCL_INT48S_ATTRIBUTE_TYPE, 6, ZCL_INT56S_ATTRIBUTE_TYPE, 7, ZCL_INT64S_ATTRIBUTE_TYPE, 8, ZCL_ENUM8_ATTRIBUTE_TYPE, 1, ZCL_ENUM16_ATTRIBUTE_TYPE, 2, - ZCL_SINGLE_ATTRIBUTE_TYPE, 4, ZCL_DOUBLE_ATTRIBUTE_TYPE, 8, ZCL_TOD_ATTRIBUTE_TYPE, 4, ZCL_DATE_ATTRIBUTE_TYPE, 4, - ZCL_EPOCH_US_ATTRIBUTE_TYPE, 8, ZCL_EPOCH_S_ATTRIBUTE_TYPE, 4, ZCL_SYSTIME_US_ATTRIBUTE_TYPE, 8, ZCL_PERCENT_ATTRIBUTE_TYPE, 1, + ZCL_SINGLE_ATTRIBUTE_TYPE, 4, ZCL_DOUBLE_ATTRIBUTE_TYPE, 8, ZCL_POSIX_MS_ATTRIBUTE_TYPE, 8, ZCL_SYSTIME_MS_ATTRIBUTE_TYPE, 8, + ZCL_ELAPSED_S_ATTRIBUTE_TYPE, 4, ZCL_TOD_ATTRIBUTE_TYPE, 4, ZCL_DATE_ATTRIBUTE_TYPE, 4, ZCL_EPOCH_US_ATTRIBUTE_TYPE, 8, + ZCL_EPOCH_S_ATTRIBUTE_TYPE, 4, ZCL_SYSTIME_US_ATTRIBUTE_TYPE, 8, ZCL_PERCENT_ATTRIBUTE_TYPE, 1, ZCL_PERCENT100THS_ATTRIBUTE_TYPE, 2, ZCL_CLUSTER_ID_ATTRIBUTE_TYPE, 4, ZCL_ATTRIB_ID_ATTRIBUTE_TYPE, 4, ZCL_FIELD_ID_ATTRIBUTE_TYPE, 4, ZCL_EVENT_ID_ATTRIBUTE_TYPE, 4, ZCL_COMMAND_ID_ATTRIBUTE_TYPE, 4, ZCL_ACTION_ID_ATTRIBUTE_TYPE, 1, ZCL_TRANS_ID_ATTRIBUTE_TYPE, 4, ZCL_NODE_ID_ATTRIBUTE_TYPE, 8, ZCL_VENDOR_ID_ATTRIBUTE_TYPE, 2, diff --git a/zzz_generated/app-common/app-common/zap-generated/attribute-type.h b/zzz_generated/app-common/app-common/zap-generated/attribute-type.h index b53b87637673c2..c7f2f874229d8c 100644 --- a/zzz_generated/app-common/app-common/zap-generated/attribute-type.h +++ b/zzz_generated/app-common/app-common/zap-generated/attribute-type.h @@ -56,6 +56,9 @@ enum ZCL_LONG_CHAR_STRING_ATTRIBUTE_TYPE = 0x44, // Long Character String ZCL_ARRAY_ATTRIBUTE_TYPE = 0x48, // List ZCL_STRUCT_ATTRIBUTE_TYPE = 0x4C, // Structure + ZCL_POSIX_MS_ATTRIBUTE_TYPE = 0xD0, // Posix Time Milliseconds + ZCL_SYSTIME_MS_ATTRIBUTE_TYPE = 0xD1, // System Time Milliseconds + ZCL_ELAPSED_S_ATTRIBUTE_TYPE = 0xD2, // Elapsed Time Seconds ZCL_TOD_ATTRIBUTE_TYPE = 0xE0, // Time of day ZCL_DATE_ATTRIBUTE_TYPE = 0xE1, // Date ZCL_EPOCH_US_ATTRIBUTE_TYPE = 0xE3, // Epoch Microseconds From 6a82676006654cbe258d7b18fb282462717c351b Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 15 May 2023 21:49:48 -0400 Subject: [PATCH 29/36] Remove dependency on controller-clusters.zap from DataModelLogger. (#26577) For some reason DataModelLogger was only enabling logging for things enabled in controller-clusters.zap, even though everything else in chip-tool ignores that configuration. This just makes DataModelLogger ignore that configuration too, so we can log everything we can request. --- .../logging/DataModelLogger-src.zapt | 16 +- .../templates/logging/DataModelLogger.zapt | 4 +- .../cluster/logging/DataModelLogger.cpp | 418 ++++++++++++++++++ .../cluster/logging/DataModelLogger.h | 5 + 4 files changed, 433 insertions(+), 10 deletions(-) diff --git a/examples/chip-tool/templates/logging/DataModelLogger-src.zapt b/examples/chip-tool/templates/logging/DataModelLogger-src.zapt index d400874cf67ffb..167021f49577d2 100644 --- a/examples/chip-tool/templates/logging/DataModelLogger-src.zapt +++ b/examples/chip-tool/templates/logging/DataModelLogger-src.zapt @@ -40,7 +40,7 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const {{ {{/zcl_events}} {{/zcl_clusters}} -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_commands_source_server}} CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const {{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::DecodableType & value) { @@ -52,7 +52,7 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const {{ return CHIP_NO_ERROR; } {{/zcl_commands_source_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data) { @@ -61,7 +61,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP switch (path.mClusterId) { -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_attributes_server}} {{#first}} case {{asUpperCamelCase parent.name}}::Id: @@ -81,7 +81,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } {{/last}} {{/zcl_attributes_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} default: break; } @@ -96,7 +96,7 @@ CHIP_ERROR DataModelLogger::LogCommand(const chip::app::ConcreteCommandPath & pa switch (path.mClusterId) { -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_commands_source_server}} {{#first}} case {{asUpperCamelCase parent.name}}::Id: @@ -116,7 +116,7 @@ CHIP_ERROR DataModelLogger::LogCommand(const chip::app::ConcreteCommandPath & pa } {{/last}} {{/zcl_commands_source_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} default: break; } @@ -152,7 +152,7 @@ CHIP_ERROR DataModelLogger::LogEvent(const chip::app::EventHeader & header, chip switch (header.mPath.mClusterId) { -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_events}} {{#first}} case {{asUpperCamelCase parent.name}}::Id: @@ -172,7 +172,7 @@ CHIP_ERROR DataModelLogger::LogEvent(const chip::app::EventHeader & header, chip } {{/last}} {{/zcl_events}} -{{/all_user_clusters}} +{{/zcl_clusters}} default: break; } diff --git a/examples/chip-tool/templates/logging/DataModelLogger.zapt b/examples/chip-tool/templates/logging/DataModelLogger.zapt index 222ab67dee0364..befe9d4210ce07 100644 --- a/examples/chip-tool/templates/logging/DataModelLogger.zapt +++ b/examples/chip-tool/templates/logging/DataModelLogger.zapt @@ -23,8 +23,8 @@ static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::C {{/zcl_events}} {{/zcl_clusters}} -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_commands_source_server}} static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::DecodableType & value); {{/zcl_commands_source_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp index c46841fe3ea27f..36103a317f7d12 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -4112,6 +4112,14 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, DataModelLogger::LogString(indent, "}"); return CHIP_NO_ERROR; } +CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, + const TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType & value) +{ + DataModelLogger::LogString(label, indent, "{"); + ReturnErrorOnFailure(DataModelLogger::LogValue("DSTOffsetRequired", indent + 1, value.DSTOffsetRequired)); + DataModelLogger::LogString(indent, "}"); + return CHIP_NO_ERROR; +} CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const OperationalCredentials::Commands::AttestationResponse::DecodableType & value) { @@ -4340,6 +4348,15 @@ DataModelLogger::LogValue(const char * label, size_t indent, DataModelLogger::LogString(indent, "}"); return CHIP_NO_ERROR; } +CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, + const ClientMonitoring::Commands::RegisterClientMonitoringResponse::DecodableType & value) +{ + DataModelLogger::LogString(label, indent, "{"); + ReturnErrorOnFailure(DataModelLogger::LogValue("status", indent + 1, value.status)); + ReturnErrorOnFailure(DataModelLogger::LogValue("ICDCounter", indent + 1, value.ICDCounter)); + DataModelLogger::LogString(indent, "}"); + return CHIP_NO_ERROR; +} CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const UnitTesting::Commands::TestSpecificResponse::DecodableType & value) { @@ -4934,6 +4951,42 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } break; } + case PulseWidthModulation::Id: { + switch (path.mAttributeId) + { + case PulseWidthModulation::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case PulseWidthModulation::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case PulseWidthModulation::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case PulseWidthModulation::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case PulseWidthModulation::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case PulseWidthModulation::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } case Descriptor::Id: { switch (path.mAttributeId) { @@ -6605,6 +6658,111 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } break; } + case TimeSynchronization::Id: { + switch (path.mAttributeId) + { + case TimeSynchronization::Attributes::UTCTime::Id: { + chip::app::DataModel::Nullable value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("UTCTime", 1, value); + } + case TimeSynchronization::Attributes::Granularity::Id: { + chip::app::Clusters::TimeSynchronization::GranularityEnum value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("Granularity", 1, value); + } + case TimeSynchronization::Attributes::TimeSource::Id: { + chip::app::Clusters::TimeSynchronization::TimeSourceEnum value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TimeSource", 1, value); + } + case TimeSynchronization::Attributes::TrustedTimeSource::Id: { + chip::app::DataModel::Nullable< + chip::app::Clusters::TimeSynchronization::Structs::TrustedTimeSourceStruct::DecodableType> + value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TrustedTimeSource", 1, value); + } + case TimeSynchronization::Attributes::DefaultNTP::Id: { + chip::app::DataModel::Nullable value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("DefaultNTP", 1, value); + } + case TimeSynchronization::Attributes::TimeZone::Id: { + chip::app::DataModel::DecodableList + value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TimeZone", 1, value); + } + case TimeSynchronization::Attributes::DSTOffset::Id: { + chip::app::DataModel::DecodableList + value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("DSTOffset", 1, value); + } + case TimeSynchronization::Attributes::LocalTime::Id: { + chip::app::DataModel::Nullable value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("LocalTime", 1, value); + } + case TimeSynchronization::Attributes::TimeZoneDatabase::Id: { + chip::app::Clusters::TimeSynchronization::TimeZoneDatabaseEnum value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TimeZoneDatabase", 1, value); + } + case TimeSynchronization::Attributes::NTPServerAvailable::Id: { + bool value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("NTPServerAvailable", 1, value); + } + case TimeSynchronization::Attributes::TimeZoneListMaxSize::Id: { + uint8_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TimeZoneListMaxSize", 1, value); + } + case TimeSynchronization::Attributes::DSTOffsetListMaxSize::Id: { + uint8_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("DSTOffsetListMaxSize", 1, value); + } + case TimeSynchronization::Attributes::SupportsDNSResolve::Id: { + bool value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("SupportsDNSResolve", 1, value); + } + case TimeSynchronization::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case TimeSynchronization::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case TimeSynchronization::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case TimeSynchronization::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case TimeSynchronization::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case TimeSynchronization::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } case BridgedDeviceBasicInformation::Id: { switch (path.mAttributeId) { @@ -7032,6 +7190,114 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } break; } + case ProxyConfiguration::Id: { + switch (path.mAttributeId) + { + case ProxyConfiguration::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case ProxyConfiguration::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case ProxyConfiguration::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case ProxyConfiguration::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case ProxyConfiguration::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case ProxyConfiguration::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } + case ProxyDiscovery::Id: { + switch (path.mAttributeId) + { + case ProxyDiscovery::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case ProxyDiscovery::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case ProxyDiscovery::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case ProxyDiscovery::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case ProxyDiscovery::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case ProxyDiscovery::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } + case ProxyValid::Id: { + switch (path.mAttributeId) + { + case ProxyValid::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case ProxyValid::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case ProxyValid::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case ProxyValid::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case ProxyValid::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case ProxyValid::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } case BooleanState::Id: { switch (path.mAttributeId) { @@ -10225,6 +10491,69 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } break; } + case ClientMonitoring::Id: { + switch (path.mAttributeId) + { + case ClientMonitoring::Attributes::IdleModeInterval::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("IdleModeInterval", 1, value); + } + case ClientMonitoring::Attributes::ActiveModeInterval::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ActiveModeInterval", 1, value); + } + case ClientMonitoring::Attributes::ActiveModeThreshold::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ActiveModeThreshold", 1, value); + } + case ClientMonitoring::Attributes::ExpectedClients::Id: { + chip::app::DataModel::DecodableList< + chip::app::Clusters::ClientMonitoring::Structs::MonitoringRegistrationStruct::DecodableType> + value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ExpectedClients", 1, value); + } + case ClientMonitoring::Attributes::ICDCounter::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ICDCounter", 1, value); + } + case ClientMonitoring::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case ClientMonitoring::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case ClientMonitoring::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case ClientMonitoring::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case ClientMonitoring::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case ClientMonitoring::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } case UnitTesting::Id: { switch (path.mAttributeId) { @@ -10674,6 +11003,42 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } break; } + case FaultInjection::Id: { + switch (path.mAttributeId) + { + case FaultInjection::Attributes::GeneratedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("GeneratedCommandList", 1, value); + } + case FaultInjection::Attributes::AcceptedCommandList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AcceptedCommandList", 1, value); + } + case FaultInjection::Attributes::EventList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("EventList", 1, value); + } + case FaultInjection::Attributes::AttributeList::Id: { + chip::app::DataModel::DecodableList value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("AttributeList", 1, value); + } + case FaultInjection::Attributes::FeatureMap::Id: { + uint32_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("FeatureMap", 1, value); + } + case FaultInjection::Attributes::ClusterRevision::Id: { + uint16_t value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("ClusterRevision", 1, value); + } + } + break; + } default: break; } @@ -10834,6 +11199,17 @@ CHIP_ERROR DataModelLogger::LogCommand(const chip::app::ConcreteCommandPath & pa } break; } + case TimeSynchronization::Id: { + switch (path.mCommandId) + { + case TimeSynchronization::Commands::SetTimeZoneResponse::Id: { + TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("SetTimeZoneResponse", 1, value); + } + } + break; + } case OperationalCredentials::Id: { switch (path.mCommandId) { @@ -11016,6 +11392,17 @@ CHIP_ERROR DataModelLogger::LogCommand(const chip::app::ConcreteCommandPath & pa } break; } + case ClientMonitoring::Id: { + switch (path.mCommandId) + { + case ClientMonitoring::Commands::RegisterClientMonitoringResponse::Id: { + ClientMonitoring::Commands::RegisterClientMonitoringResponse::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("RegisterClientMonitoringResponse", 1, value); + } + } + break; + } case UnitTesting::Id: { switch (path.mCommandId) { @@ -11291,6 +11678,37 @@ CHIP_ERROR DataModelLogger::LogEvent(const chip::app::EventHeader & header, chip } break; } + case TimeSynchronization::Id: { + switch (header.mPath.mEventId) + { + case TimeSynchronization::Events::DSTTableEmpty::Id: { + chip::app::Clusters::TimeSynchronization::Events::DSTTableEmpty::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("DSTTableEmpty", 1, value); + } + case TimeSynchronization::Events::DSTStatus::Id: { + chip::app::Clusters::TimeSynchronization::Events::DSTStatus::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("DSTStatus", 1, value); + } + case TimeSynchronization::Events::TimeZoneStatus::Id: { + chip::app::Clusters::TimeSynchronization::Events::TimeZoneStatus::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TimeZoneStatus", 1, value); + } + case TimeSynchronization::Events::TimeFailure::Id: { + chip::app::Clusters::TimeSynchronization::Events::TimeFailure::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("TimeFailure", 1, value); + } + case TimeSynchronization::Events::MissingTrustedTimeSource::Id: { + chip::app::Clusters::TimeSynchronization::Events::MissingTrustedTimeSource::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("MissingTrustedTimeSource", 1, value); + } + } + break; + } case BridgedDeviceBasicInformation::Id: { switch (header.mPath.mEventId) { diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h index a1a038ba506b0b..56b6d369f2984a 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h @@ -403,6 +403,8 @@ LogValue(const char * label, size_t indent, const chip::app::Clusters::NetworkCommissioning::Commands::ConnectNetworkResponse::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::DiagnosticLogs::Commands::RetrieveLogsResponse::DecodableType & value); +static CHIP_ERROR LogValue(const char * label, size_t indent, + const chip::app::Clusters::TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::OperationalCredentials::Commands::AttestationResponse::DecodableType & value); static CHIP_ERROR @@ -451,6 +453,9 @@ LogValue(const char * label, size_t indent, static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::ElectricalMeasurement::Commands::GetMeasurementProfileResponseCommand::DecodableType & value); +static CHIP_ERROR +LogValue(const char * label, size_t indent, + const chip::app::Clusters::ClientMonitoring::Commands::RegisterClientMonitoringResponse::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::UnitTesting::Commands::TestSpecificResponse::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, From 83ca91f45f69414e404505c1e1a53513112f56e4 Mon Sep 17 00:00:00 2001 From: weicheng Date: Tue, 16 May 2023 10:45:27 +0800 Subject: [PATCH 30/36] [ASR] implement docker best practices (#26561) --- .../docker/images/chip-build-asr/Dockerfile | 22 +++++++++++-------- integrations/docker/images/chip-build/version | 2 +- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/integrations/docker/images/chip-build-asr/Dockerfile b/integrations/docker/images/chip-build-asr/Dockerfile index c03a5533856241..49ddaad6332789 100644 --- a/integrations/docker/images/chip-build-asr/Dockerfile +++ b/integrations/docker/images/chip-build-asr/Dockerfile @@ -1,20 +1,24 @@ ARG VERSION=latest FROM connectedhomeip/chip-build:${VERSION} -# Setup ASR -ARG ASR_DIR=/opt/asr RUN set -x \ && apt-get update \ - && apt-get install -y git git-lfs \ + && DEBIAN_FRONTEND=noninteractive apt-get install -fy --no-install-recommends \ + wget \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/ \ + && : # last line + +# Setup toolchain for ASR582X +ARG ASR_DIR=/opt/asr +RUN set -x \ && mkdir ${ASR_DIR} \ && cd ${ASR_DIR} \ - && git clone --depth=1 https://github.com/asriot/Tools.git \ - && cd Tools \ - && git lfs pull \ - && cd toolchain \ + && mkdir -p Tools/toolchain \ + && cd Tools/toolchain \ + && wget https://developer.arm.com/-/media/Files/downloads/gnu-rm/9-2019q4/RC2.1/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 \ && tar -jxvf gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 \ - && mkdir -p asr_riscv_gnu_toolchain_10.2_ubuntu-16.04 \ - && tar -jxvf asr_riscv_gnu_toolchain_10.2_ubuntu-16.04.tar.bz2 -C asr_riscv_gnu_toolchain_10.2_ubuntu-16.04/ \ + && rm gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 \ && : # last line ENV ASR_TOOLCHAIN_PATH=${ASR_DIR}/Tools/toolchain/gcc-arm-none-eabi-9-2019-q4-major/bin/ diff --git a/integrations/docker/images/chip-build/version b/integrations/docker/images/chip-build/version index e330c9368becf5..829aa492cebacb 100644 --- a/integrations/docker/images/chip-build/version +++ b/integrations/docker/images/chip-build/version @@ -1 +1 @@ -0.7.9 Version bump reason: Fix path for sysroot for crosscompile image +0.7.10 Version bump reason: [ASR] implement docker best practices From c6f6584df804c55eada2b085580bc9ee35b07e34 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 15 May 2023 19:53:07 -0700 Subject: [PATCH 31/36] [Java] Add API pairDeviceWithCode to test pair with setup code (#26494) * [Java] Add pairDeviceWithCode API * Address review comments --- .github/workflows/tests.yaml | 24 +++++++++++++++++++ .../commands/pairing/PairCodeCommand.kt | 2 ++ .../commands/pairing/PairCodeThreadCommand.kt | 2 ++ .../commands/pairing/PairCodeWifiCommand.kt | 2 ++ .../commands/pairing/PairingCommand.kt | 12 ++++++++-- scripts/tests/java/commissioning_test.py | 22 ++++++++++++++++- src/controller/CHIPDeviceController.cpp | 1 + src/controller/CHIPDeviceController.h | 1 + .../java/CHIPDeviceController-JNI.cpp | 17 +++++++++++-- .../ChipDeviceController.java | 16 ++++++++++++- 10 files changed, 93 insertions(+), 6 deletions(-) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 4266a3abe945dc..5d3555383992f5 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -674,6 +674,30 @@ jobs: --tool-args "address-paseonly --nodeid 1 --setup-pin-code 20202021 --address ::1 --port 5540 -t 1000" \ --factoryreset \ ' + - name: Run Pairing SetupQRCode Test + timeout-minutes: 10 + run: | + scripts/run_in_build_env.sh \ + './scripts/tests/run_java_test.py \ + --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app \ + --app-args "--discriminator 3840 --interface-id -1" \ + --tool-path out/linux-x64-java-matter-controller \ + --tool-cluster "pairing" \ + --tool-args "code --nodeid 1 --setup-payload MT:-24J0AFN00KA0648G00 --discover-once 1 --use-only-onnetwork-discovery 0 -t 1000" \ + --factoryreset \ + ' + - name: Run Pairing ManualCode Test + timeout-minutes: 10 + run: | + scripts/run_in_build_env.sh \ + './scripts/tests/run_java_test.py \ + --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app \ + --app-args "--discriminator 3840 --interface-id -1" \ + --tool-path out/linux-x64-java-matter-controller \ + --tool-cluster "pairing" \ + --tool-args "code --nodeid 1 --setup-payload 34970112332 --discover-once 1 --use-only-onnetwork-discovery 0 -t 1000" \ + --factoryreset \ + ' - name: Uploading core files uses: actions/upload-artifact@v3 if: ${{ failure() && !env.ACT }} diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt index bf6e18cceedafd..4c4d191d83fcb0 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt @@ -27,6 +27,8 @@ class PairCodeCommand(controller: ChipDeviceController, credsIssue: CredentialsI .pairDeviceWithCode( getNodeId(), getOnboardingPayload(), + getDiscoverOnce(), + getUseOnlyOnNetworkDiscovery(), null, getWifiNetworkCredentials(), ) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt index 419525733c496a..1168f7f93e30a2 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt @@ -27,6 +27,8 @@ class PairCodeThreadCommand(controller: ChipDeviceController, credsIssue: Creden .pairDeviceWithCode( getNodeId(), getOnboardingPayload(), + getDiscoverOnce(), + getUseOnlyOnNetworkDiscovery(), null, getThreadNetworkCredentials(), ) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt index ffecb2e9529df8..09b639b1c251c1 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt @@ -27,6 +27,8 @@ class PairCodeWifiCommand(controller: ChipDeviceController, credsIssue: Credenti .pairDeviceWithCode( getNodeId(), getOnboardingPayload(), + getDiscoverOnce(), + getUseOnlyOnNetworkDiscovery(), null, getWifiNetworkCredentials(), ) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt index e7f90832d0c25c..e2112c7486a9ba 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt @@ -70,8 +70,8 @@ abstract class PairingCommand( PairingModeType.NONE -> {} PairingModeType.CODE, PairingModeType.CODE_PASE_ONLY -> { addArgument("payload", onboardingPayload, null, false) - addArgument("discover-once", discoverOnce, null, false) - addArgument("use-only-onnetwork-discovery", useOnlyOnNetworkDiscovery, null, false) + addArgument("discover-once", discoverOnce, null, true) + addArgument("use-only-onnetwork-discovery", useOnlyOnNetworkDiscovery, null, true) } PairingModeType.ADDRESS_PASE_ONLY -> { @@ -244,6 +244,14 @@ abstract class PairingCommand( return chunked(2).map { byteStr -> byteStr.toUByte(16).toByte() }.toByteArray() } + fun getDiscoverOnce(): Boolean { + return discoverOnce.get() + } + + fun getUseOnlyOnNetworkDiscovery(): Boolean { + return useOnlyOnNetworkDiscovery.get() + } + companion object { private val logger = Logger.getLogger(PairingCommand::class.java.name) } diff --git a/scripts/tests/java/commissioning_test.py b/scripts/tests/java/commissioning_test.py index 138c9efa49065a..806f64d8746659 100755 --- a/scripts/tests/java/commissioning_test.py +++ b/scripts/tests/java/commissioning_test.py @@ -47,7 +47,10 @@ def __init__(self, thread_list: typing.List[threading.Thread], queue: queue.Queu "session establishment (PASE) with the Commissionee")) parser.add_argument('-n', '--nodeid', help="The Node ID issued to the device", default='1') parser.add_argument('-d', '--discriminator', help="Discriminator of the device", default='3840') - parser.add_argument('-u', '--paa-trust-store-path', dest='paa_trust_store_path', + parser.add_argument('-o', '--discover-once', help="Enable to disable PASE auto retry mechanism", default='false') + parser.add_argument('-u', '--use-only-onnetwork-discovery', + help="Enable when the commissionable device is available on the network", default='false') + parser.add_argument('-r', '--paa-trust-store-path', dest='paa_trust_store_path', help="Path that contains valid and trusted PAA Root Certificates") args = parser.parse_args(args.split()) @@ -59,6 +62,8 @@ def __init__(self, thread_list: typing.List[threading.Thread], queue: queue.Queu self.setup_payload = args.setup_payload self.setup_pin_code = args.setup_pin_code self.discriminator = args.discriminator + self.discover_once = args.discover_once + self.use_only_onnetwork_discovery = args.use_only_onnetwork_discovery self.timeout = args.timeout logging.basicConfig(level=logging.INFO) @@ -87,6 +92,15 @@ def TestCmdAddressPaseOnly(self, nodeid, setuppin, address, port, timeout): DumpProgramOutputToQueue(self.thread_list, Fore.GREEN + "JAVA " + Style.RESET_ALL, java_process, self.queue) return java_process.wait() + def TestCmdCode(self, nodeid, setup_payload, discover_once, use_only_onnetwork_discovery, timeout): + java_command = self.command + ['pairing', 'code', nodeid, setup_payload, timeout, + '--discover-once', discover_once, '--use-only-onnetwork-discovery', use_only_onnetwork_discovery] + logging.info(f"Execute: {java_command}") + java_process = subprocess.Popen( + java_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + DumpProgramOutputToQueue(self.thread_list, Fore.GREEN + "JAVA " + Style.RESET_ALL, java_process, self.queue) + return java_process.wait() + def RunTest(self): if self.command_name == 'onnetwork-long': logging.info("Testing pairing onnetwork-long") @@ -103,5 +117,11 @@ def RunTest(self): code = self.TestCmdAddressPaseOnly(self.nodeid, self.setup_pin_code, self.address, self.port, self.timeout) if code != 0: raise Exception(f"Testing pairing address-paseonly failed with error {code}") + elif self.command_name == 'code': + logging.info("Testing pairing setup-code") + code = self.TestCmdCode(self.nodeid, self.setup_payload, self.discover_once, + self.use_only_onnetwork_discovery, self.timeout) + if code != 0: + raise Exception(f"Testing pairing code failed with error {code}") else: raise Exception(f"Unsupported command {self.command_name}") diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index e483a83b140d06..8fd93b36d28559 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -590,6 +590,7 @@ CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * se DiscoveryType discoveryType) { MATTER_TRACE_EVENT_SCOPE("PairDevice", "DeviceCommissioner"); + if (mDefaultCommissioner == nullptr) { ChipLogError(Controller, "No default commissioner is specified"); diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index c3f6cd3ff49f41..3f6f5c65c89fc0 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -443,6 +443,7 @@ class DLL_EXPORT DeviceCommissioner : public DeviceController, * @param[in] rendezvousParams The Rendezvous connection parameters */ CHIP_ERROR PairDevice(NodeId remoteDeviceId, RendezvousParameters & rendezvousParams); + /** * @overload * @param[in] remoteDeviceId The remote device Id. diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 9b40721795d0a4..d7bb27b126b3f3 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -654,7 +654,8 @@ JNI_METHOD(void, pairDeviceWithAddress) } JNI_METHOD(void, pairDeviceWithCode) -(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jstring setUpCode, jbyteArray csrNonce, jobject networkCredentials) +(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jstring setUpCode, jboolean discoverOnce, + jboolean useOnlyOnNetworkDiscovery, jbyteArray csrNonce, jobject networkCredentials) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -665,6 +666,18 @@ JNI_METHOD(void, pairDeviceWithCode) JniUtfString setUpCodeJniString(env, setUpCode); CommissioningParameters commissioningParams = wrapper->GetCommissioningParameters(); + + auto discoveryType = DiscoveryType::kAll; + if (useOnlyOnNetworkDiscovery) + { + discoveryType = DiscoveryType::kDiscoveryNetworkOnly; + } + + if (discoverOnce) + { + discoveryType = DiscoveryType::kDiscoveryNetworkOnlyWithoutPASEAutoRetry; + } + if (csrNonce != nullptr) { JniByteArray jniCsrNonce(env, csrNonce); @@ -680,7 +693,7 @@ JNI_METHOD(void, pairDeviceWithCode) { commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); } - err = wrapper->Controller()->PairDevice(deviceId, setUpCodeJniString.c_str(), commissioningParams, DiscoveryType::kAll); + err = wrapper->Controller()->PairDevice(deviceId, setUpCodeJniString.c_str(), commissioningParams, discoveryType); if (err != CHIP_NO_ERROR) { diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index ed8e09873fc02e..438f4a107dc62d 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -180,6 +180,9 @@ public void pairDeviceWithAddress( * * @param deviceId the node ID to assign to the device * @param setupCode the scanned QR code or manual entry code + * @param discoverOnce the flag to enable/disable PASE auto retry mechanism + * @param useOnlyOnNetworkDiscovery the flag to indicate the commissionable device is available on + * the network * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly * generated CSR nonce. * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned @@ -187,9 +190,18 @@ public void pairDeviceWithAddress( public void pairDeviceWithCode( long deviceId, String setupCode, + boolean discoverOnce, + boolean useOnlyOnNetworkDiscovery, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials) { - pairDeviceWithCode(deviceControllerPtr, deviceId, setupCode, csrNonce, networkCredentials); + pairDeviceWithCode( + deviceControllerPtr, + deviceId, + setupCode, + discoverOnce, + useOnlyOnNetworkDiscovery, + csrNonce, + networkCredentials); } public void establishPaseConnection(long deviceId, int connId, long setupPincode) { @@ -1017,6 +1029,8 @@ private native void pairDeviceWithCode( long deviceControllerPtr, long deviceId, String setupCode, + boolean discoverOnce, + boolean useOnlyOnNetworkDiscovery, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials); From df615a65126ce38808fc4777c759d31c7603117e Mon Sep 17 00:00:00 2001 From: Jean-Francois Penven <67962328+jepenven-silabs@users.noreply.github.com> Date: Mon, 15 May 2023 22:53:27 -0400 Subject: [PATCH 32/36] Complete Button Abstraction (#26581) --- examples/chef/efr32/src/AppTask.cpp | 4 ---- .../silabs/SiWx917/src/AppTask.cpp | 7 ++++--- .../silabs/efr32/src/AppTask.cpp | 9 +++------ .../silabs/SiWx917/src/AppTask.cpp | 5 +++-- .../silabs/efr32/include/AppTask.h | 4 ++-- .../lighting-app/silabs/efr32/src/AppTask.cpp | 19 +++++-------------- .../lock-app/silabs/SiWx917/src/AppTask.cpp | 5 +++-- .../lock-app/silabs/efr32/src/AppTask.cpp | 7 ++----- .../silabs/SiWx917/BaseApplication.cpp | 5 ++++- .../platform/silabs/efr32/BaseApplication.cpp | 16 +++++++--------- .../platform/silabs/efr32/BaseApplication.h | 7 ++----- .../thermostat/silabs/efr32/src/AppTask.cpp | 4 ---- .../silabs/efr32/src/WindowAppImpl.cpp | 9 +++------ .../platformAbstraction/SilabsPlatform.h | 8 ++++++++ 14 files changed, 46 insertions(+), 63 deletions(-) mode change 100755 => 100644 examples/lighting-app/silabs/efr32/src/AppTask.cpp diff --git a/examples/chef/efr32/src/AppTask.cpp b/examples/chef/efr32/src/AppTask.cpp index ee2e2921202fc6..d166243033cdd6 100644 --- a/examples/chef/efr32/src/AppTask.cpp +++ b/examples/chef/efr32/src/AppTask.cpp @@ -125,9 +125,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif err = BaseApplication::Init(&gIdentify); if (err != CHIP_NO_ERROR) @@ -169,7 +167,6 @@ void AppTask::AppTaskMain(void * pvParameter) } } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent button_event = {}; @@ -182,4 +179,3 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&button_event); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT diff --git a/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp b/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp index 3cf6d9a034cae7..d76dc9de2526e4 100644 --- a/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp @@ -69,6 +69,7 @@ constexpr chip::EndpointId kGenericSwitchEndpoint = 2; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -239,7 +240,7 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) static bool mCurrentButtonState = false; - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { mCurrentButtonState = !mCurrentButtonState; LightSwitchMgr::LightSwitchAction action = @@ -252,7 +253,7 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) sAppTask.GetLCD().WriteDemoUI(mCurrentButtonState); #endif } - else if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_RELEASED) + else if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonReleased)) { LightSwitchMgr::GetInstance().GenericSwitchOnShortRelease(); } @@ -268,7 +269,7 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Handler = SwitchActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + else if (button == SIWx917_BTN0 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/light-switch-app/silabs/efr32/src/AppTask.cpp b/examples/light-switch-app/silabs/efr32/src/AppTask.cpp index 81ba6afad54c0a..38dea28cc6abd8 100644 --- a/examples/light-switch-app/silabs/efr32/src/AppTask.cpp +++ b/examples/light-switch-app/silabs/efr32/src/AppTask.cpp @@ -68,6 +68,7 @@ constexpr chip::EndpointId kGenericSwitchEndpoint = 2; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -153,9 +154,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Light Switch"); @@ -229,14 +228,13 @@ void AppTask::OnIdentifyStop(Identify * identify) #endif } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::SwitchActionEventHandler(AppEvent * aEvent) { VerifyOrReturn(aEvent->Type == AppEvent::kEventType_Button); static bool mCurrentButtonState = false; - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { mCurrentButtonState = !mCurrentButtonState; LightSwitchMgr::LightSwitchAction action = @@ -249,7 +247,7 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) sAppTask.GetLCD().WriteDemoUI(mCurrentButtonState); #endif } - else if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_RELEASED) + else if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonReleased)) { LightSwitchMgr::GetInstance().GenericSwitchOnShortRelease(); } @@ -272,4 +270,3 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&button_event); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT diff --git a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp index 15474dc8527065..d57caba69674f0 100644 --- a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp @@ -43,6 +43,7 @@ using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -240,12 +241,12 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == SIWx917_BTN1 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == SIWx917_BTN1 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LightActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + else if (button == SIWx917_BTN0 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/lighting-app/silabs/efr32/include/AppTask.h b/examples/lighting-app/silabs/efr32/include/AppTask.h index f8ad1b45367a0b..9c988e9b3d8807 100644 --- a/examples/lighting-app/silabs/efr32/include/AppTask.h +++ b/examples/lighting-app/silabs/efr32/include/AppTask.h @@ -68,7 +68,7 @@ class AppTask : public BaseApplication static void AppTaskMain(void * pvParameter); CHIP_ERROR StartAppTask(); -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + /** * @brief Event handler when a button is pressed * Function posts an event for button processing @@ -78,7 +78,7 @@ class AppTask : public BaseApplication * SL_SIMPLE_BUTTON_RELEASED or SL_SIMPLE_BUTTON_DISABLED */ static void ButtonEventHandler(uint8_t button, uint8_t btnAction); -#endif + /** * @brief Callback called by the identify-server when an identify command is received * diff --git a/examples/lighting-app/silabs/efr32/src/AppTask.cpp b/examples/lighting-app/silabs/efr32/src/AppTask.cpp old mode 100755 new mode 100644 index a8c63c8e61b1d0..f40e13a7c01135 --- a/examples/lighting-app/silabs/efr32/src/AppTask.cpp +++ b/examples/lighting-app/silabs/efr32/src/AppTask.cpp @@ -46,14 +46,12 @@ #define LIGHT_LED 0 #endif -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT - #define APP_FUNCTION_BUTTON 0 #define APP_LIGHT_SWITCH 1 -#endif using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -132,9 +130,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Lighting-App"); @@ -241,13 +237,11 @@ void AppTask::LightActionEventHandler(AppEvent * aEvent) action = static_cast(aEvent->LightEvent.Action); actor = aEvent->LightEvent.Actor; } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT else if (aEvent->Type == AppEvent::kEventType_Button) { action = (LightMgr().IsLightOn()) ? LightingManager::OFF_ACTION : LightingManager::ON_ACTION; actor = AppEvent::kEventType_Button; } -#endif else { err = APP_ERROR_UNHANDLED_EVENT; @@ -263,14 +257,14 @@ void AppTask::LightActionEventHandler(AppEvent * aEvent) } } } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == APP_LIGHT_SWITCH && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == APP_LIGHT_SWITCH && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LightActionEventHandler; AppTask::GetAppTask().PostEvent(&button_event); @@ -281,7 +275,6 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) AppTask::GetAppTask().PostEvent(&button_event); } } -#endif void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) { @@ -294,12 +287,11 @@ void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) #ifdef DISPLAY_ENABLED sAppTask.GetLCD().WriteDemoUI(lightOn); #endif -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + if (aActor == AppEvent::kEventType_Button) { sAppTask.mSyncClusterToButtonAction = true; } -#endif } void AppTask::ActionCompleted(LightingManager::Action_t aAction) @@ -313,13 +305,12 @@ void AppTask::ActionCompleted(LightingManager::Action_t aAction) { SILABS_LOG("Light OFF") } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + if (sAppTask.mSyncClusterToButtonAction) { chip::DeviceLayer::PlatformMgr().ScheduleWork(UpdateClusterState, reinterpret_cast(nullptr)); sAppTask.mSyncClusterToButtonAction = false; } -#endif } void AppTask::PostLightActionRequest(int32_t aActor, LightingManager::Action_t aAction) diff --git a/examples/lock-app/silabs/SiWx917/src/AppTask.cpp b/examples/lock-app/silabs/SiWx917/src/AppTask.cpp index fe1d267e465f02..006d81ef66d0b0 100644 --- a/examples/lock-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lock-app/silabs/SiWx917/src/AppTask.cpp @@ -61,6 +61,7 @@ using chip::app::Clusters::DoorLock::OperationSourceEnum; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; using namespace ::chip::DeviceLayer::Internal; using namespace SI917DoorLock::LockInitParams; @@ -348,12 +349,12 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == SIWx917_BTN1 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == SIWx917_BTN1 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LockActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + else if (button == SIWx917_BTN0 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/lock-app/silabs/efr32/src/AppTask.cpp b/examples/lock-app/silabs/efr32/src/AppTask.cpp index 93226e14f28646..cf3d1f5e40cfcc 100644 --- a/examples/lock-app/silabs/efr32/src/AppTask.cpp +++ b/examples/lock-app/silabs/efr32/src/AppTask.cpp @@ -64,6 +64,7 @@ using chip::app::Clusters::DoorLock::OperationSourceEnum; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; using namespace ::chip::DeviceLayer::Internal; using namespace EFR32DoorLock::LockInitParams; @@ -143,9 +144,7 @@ CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Lock-App", true); @@ -361,14 +360,13 @@ void AppTask::LockActionEventHandler(AppEvent * aEvent) } } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == APP_LOCK_SWITCH && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == APP_LOCK_SWITCH && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LockActionEventHandler; sAppTask.PostEvent(&button_event); @@ -379,7 +377,6 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&button_event); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ActionInitiated(LockManager::Action_t aAction, int32_t aActor) { diff --git a/examples/platform/silabs/SiWx917/BaseApplication.cpp b/examples/platform/silabs/SiWx917/BaseApplication.cpp index 62b5f4cc1bc361..8412eff3e81fc7 100644 --- a/examples/platform/silabs/SiWx917/BaseApplication.cpp +++ b/examples/platform/silabs/SiWx917/BaseApplication.cpp @@ -47,6 +47,8 @@ #include #include +#include + #ifdef SL_WIFI #include "wfx_host_events.h" #include @@ -70,6 +72,7 @@ using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -355,7 +358,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { if ((!mFunctionTimerActive) && (mFunction == kFunction_NoneSelected)) { diff --git a/examples/platform/silabs/efr32/BaseApplication.cpp b/examples/platform/silabs/efr32/BaseApplication.cpp index 9d096f23353cab..baf16e78cc2510 100644 --- a/examples/platform/silabs/efr32/BaseApplication.cpp +++ b/examples/platform/silabs/efr32/BaseApplication.cpp @@ -53,6 +53,8 @@ #include #endif // CHIP_ENABLE_OPENTHREAD +#include + #ifdef SL_WIFI #include "wfx_host_events.h" #include @@ -75,12 +77,11 @@ #if defined(ENABLE_WSTK_LEDS) && defined(SL_CATALOG_SIMPLE_LED_LED1_PRESENT) #define SYSTEM_STATE_LED 0 #endif // ENABLE_WSTK_LEDS -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT #define APP_FUNCTION_BUTTON 0 -#endif using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -397,7 +398,7 @@ void BaseApplication::LightEventHandler() sStatusLED.Animate(); #endif // ENABLE_WSTK_LEDS } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + void BaseApplication::ButtonHandler(AppEvent * aEvent) { // To trigger software update: press the APP_FUNCTION_BUTTON button briefly (< @@ -407,7 +408,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { if (!mFunctionTimerActive && mFunction == kFunction_NoneSelected) { @@ -444,10 +445,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) SILABS_LOG("Failed to open the Basic Commissioning Window"); } } - else - { - SILABS_LOG("Network is already provisioned, Ble advertissement not enabled"); - } + else { SILABS_LOG("Network is already provisioned, Ble advertissement not enabled"); } } else if (mFunctionTimerActive && mFunction == kFunction_FactoryReset) { @@ -464,7 +462,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) } } } -#endif + void BaseApplication::CancelFunctionTimer() { if (xTimerStop(sFunctionTimer, pdMS_TO_TICKS(0)) == pdFAIL) diff --git a/examples/platform/silabs/efr32/BaseApplication.h b/examples/platform/silabs/efr32/BaseApplication.h index 191fcba4aaf3f3..d8bd8e9a6a7502 100644 --- a/examples/platform/silabs/efr32/BaseApplication.h +++ b/examples/platform/silabs/efr32/BaseApplication.h @@ -28,9 +28,6 @@ #include "AppEvent.h" #include "FreeRTOS.h" -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT -#include "sl_simple_button_instances.h" -#endif #include "timers.h" // provides FreeRTOS timer support #include #include @@ -153,7 +150,7 @@ class BaseApplication * @param aEvent post event being processed */ static void FunctionEventHandler(AppEvent * aEvent); -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + /** * @brief PB0 Button event processing function * Press and hold will trigger a factory reset timer start @@ -162,7 +159,7 @@ class BaseApplication * @param aEvent button event being processed */ static void ButtonHandler(AppEvent * aEvent); -#endif + /** * @brief Light Timer finished callback function * Calls LED processing function diff --git a/examples/thermostat/silabs/efr32/src/AppTask.cpp b/examples/thermostat/silabs/efr32/src/AppTask.cpp index ef7204cbfd4b82..2e506d1658223c 100644 --- a/examples/thermostat/silabs/efr32/src/AppTask.cpp +++ b/examples/thermostat/silabs/efr32/src/AppTask.cpp @@ -142,9 +142,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Thermostat-App"); @@ -246,7 +244,6 @@ void AppTask::UpdateThermoStatUI() #endif // DISPLAY_ENABLED } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent aEvent = {}; @@ -259,4 +256,3 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&aEvent); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT diff --git a/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp b/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp index 51c6652c6da149..c4e48212e56e42 100644 --- a/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp +++ b/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp @@ -31,9 +31,6 @@ #include #include #endif // QR_CODE_ENABLED -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT -#include -#endif #include @@ -60,6 +57,7 @@ SilabsLCD slLCD; using namespace chip::app::Clusters::WindowCovering; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; #define APP_STATE_LED 0 #define APP_ACTION_LED 1 @@ -518,9 +516,9 @@ WindowAppImpl::Button::Button(WindowApp::Button::Id id, const char * name) : Win void WindowAppImpl::OnButtonChange(uint8_t button, uint8_t btnAction) { -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT WindowApp::Button * btn = static_cast