diff --git a/tests/nexus/CMakeLists.txt b/tests/nexus/CMakeLists.txt index b1e7d4dc5..58b7a8e93 100644 --- a/tests/nexus/CMakeLists.txt +++ b/tests/nexus/CMakeLists.txt @@ -392,6 +392,7 @@ ot_nexus_test(border_agent "core;nexus") ot_nexus_test(border_agent_tracker "core;nexus") ot_nexus_test(child_supervision "core;nexus") ot_nexus_test(coap_block "core;nexus") +ot_nexus_test(coap_observe "core;nexus") ot_nexus_test(dataset_updater "core;nexus") ot_nexus_test(discover_scan "core;nexus") ot_nexus_test(dnssd "core;nexus") diff --git a/tests/nexus/openthread-core-nexus-config.h b/tests/nexus/openthread-core-nexus-config.h index 4359b1947..0d0e65eb7 100644 --- a/tests/nexus/openthread-core-nexus-config.h +++ b/tests/nexus/openthread-core-nexus-config.h @@ -61,6 +61,7 @@ #define OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE 1 #define OPENTHREAD_CONFIG_COAP_API_ENABLE 1 #define OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE 1 +#define OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE 1 #define OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE 1 #define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 1 #define OPENTHREAD_CONFIG_COMMISSIONER_MAX_JOINER_ENTRIES 4 diff --git a/tests/nexus/test_coap_observe.cpp b/tests/nexus/test_coap_observe.cpp new file mode 100644 index 000000000..a9bf39b33 --- /dev/null +++ b/tests/nexus/test_coap_observe.cpp @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2026, 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. + */ + +#include +#include +#include + +#include "platform/nexus_core.hpp" +#include "platform/nexus_node.hpp" + +namespace ot { +namespace Nexus { + +static bool sRequestHandlerCalled = false; +static bool sNotificationReceived = false; +static uint32_t sObserveValue = 0; +static char sReceivedPayload[32]; +static bool sSubscriptionActive = false; + +static Coap::Token sSubscriberToken; +static otIp6Address sSubscriberAddr; +static uint16_t sSubscriberPort; +static bool sSubscriberPresent = false; + +static void HandleRequest(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) +{ + Instance &instance = *static_cast(aContext); + Coap::Message &message = AsCoapMessage(aMessage); + Coap::Code code = static_cast(message.ReadCode()); + Coap::Message *response = nullptr; + + Log("HandleRequest called"); + + sRequestHandlerCalled = true; + + if (code == Coap::kCodeGet) + { + response = instance.Get().NewMessage(); + VerifyOrQuit(response != nullptr); + + SuccessOrQuit(response->InitAsResponse(Coap::kTypeAck, Coap::kCodeContent, message)); + + Coap::Option::Iterator iterator; + SuccessOrQuit(iterator.Init(message, Coap::kOptionObserve)); + if (iterator.GetOption() != nullptr) + { + uint64_t observe = 0; + SuccessOrQuit(iterator.ReadOptionValue(observe)); + + if (observe == 0) + { + // New subscriber + sSubscriberAddr = aMessageInfo->mPeerAddr; + sSubscriberPort = aMessageInfo->mPeerPort; + SuccessOrQuit(message.ReadToken(sSubscriberToken)); + sSubscriberPresent = true; + + // Append Observe option to response + SuccessOrQuit(response->AppendObserveOption(0)); + } + else if (observe == 1) + { + // Cancel subscription + sSubscriberPresent = false; + } + } + + SuccessOrQuit(response->AppendPayloadMarker()); + SuccessOrQuit(response->AppendBytes("Test123", 7)); + + SuccessOrQuit(instance.Get().SendMessage(*response, AsCoreType(aMessageInfo))); + } +} + +static void HandleNotification(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, otError aResult) +{ + OT_UNUSED_VARIABLE(aContext); + OT_UNUSED_VARIABLE(aMessageInfo); + + Log("HandleNotification called with result %d", aResult); + + if (!sSubscriptionActive) + { + Log("Subscription inactive, ignoring message"); + return; + } + + if (aResult != OT_ERROR_NONE) + { + return; + } + + sNotificationReceived = true; + + uint16_t length = AsCoapMessage(aMessage).GetLength() - AsCoapMessage(aMessage).GetOffset(); + Log("Message length: %u, offset: %u", AsCoapMessage(aMessage).GetLength(), AsCoapMessage(aMessage).GetOffset()); + + if (length > 0) + { + length = Min(length, static_cast(sizeof(sReceivedPayload) - 1)); + SuccessOrQuit(AsCoapMessage(aMessage).Read(AsCoapMessage(aMessage).GetOffset(), sReceivedPayload, length)); + sReceivedPayload[length] = '\0'; + } + + // Only check options if it's a notification (payload starts with "msg") + if (strncmp(sReceivedPayload, "msg", 3) == 0) + { + Coap::Option::Iterator iterator; + SuccessOrQuit(iterator.Init(AsCoapMessage(aMessage), Coap::kOptionObserve)); + if (iterator.GetOption() != nullptr) + { + uint64_t observe = 0; + SuccessOrQuit(iterator.ReadOptionValue(observe)); + sObserveValue = static_cast(observe); + } + } +} + +void TestCoapObserve(void) +{ + Core nexus; + + Node &leader = nexus.CreateNode(); + Node &router = nexus.CreateNode(); + + nexus.AdvanceTime(0); + + SuccessOrQuit(Instance::SetGlobalLogLevel(kLogLevelInfo)); + + Log("Form network"); + leader.Form(); + nexus.AdvanceTime(13 * 1000); + VerifyOrQuit(leader.Get().IsLeader()); + + router.Join(leader); + nexus.AdvanceTime(10 * 1000); + VerifyOrQuit(router.Get().IsChild() || router.Get().IsRouter()); + + // Start CoAP on Leader + SuccessOrQuit(leader.Get().Start(OT_DEFAULT_COAP_PORT)); + + Coap::Resource resource("test", &HandleRequest, &leader.GetInstance()); + leader.Get().AddResource(resource); + + // Start CoAP on Router + SuccessOrQuit(router.Get().Start(OT_DEFAULT_COAP_PORT)); + + // Router sends Observe request + Coap::Message *message = router.Get().NewMessage(); + VerifyOrQuit(message != nullptr); + SuccessOrQuit(message->Init(Coap::kTypeConfirmable, Coap::kCodeGet)); + SuccessOrQuit(message->AppendObserveOption(0)); + SuccessOrQuit(message->AppendUriPathOptions("test")); + + Coap::Token token; + SuccessOrQuit(token.SetToken(reinterpret_cast("12345678"), 8)); + IgnoreError(message->WriteToken(token)); + + Ip6::MessageInfo messageInfo; + messageInfo.SetPeerAddr(leader.Get().GetMeshLocalEid()); + messageInfo.SetPeerPort(OT_DEFAULT_COAP_PORT); + + sRequestHandlerCalled = false; + sSubscriberPresent = false; + sSubscriptionActive = true; + + SuccessOrQuit(router.Get().SendMessageWithResponseHandlerSeparateParams( + *message, messageInfo, nullptr, &HandleNotification, nullptr, nullptr, nullptr)); + + nexus.AdvanceTime(5 * 1000); + + VerifyOrQuit(sRequestHandlerCalled); + VerifyOrQuit(sSubscriberPresent); + VerifyOrQuit(sNotificationReceived); // Initial response acts as first notification + VerifyOrQuit(strcmp(sReceivedPayload, "Test123") == 0); + + // Now Leader sends a notification + sNotificationReceived = false; + + Coap::Message *notification = leader.Get().NewMessage(); + VerifyOrQuit(notification != nullptr); + SuccessOrQuit(notification->Init(Coap::kTypeNonConfirmable, Coap::kCodeContent)); + SuccessOrQuit(notification->WriteToken(sSubscriberToken)); + SuccessOrQuit(notification->AppendObserveOption(1)); + SuccessOrQuit(notification->AppendPayloadMarker()); + SuccessOrQuit(notification->AppendBytes("msg0", 4)); + + messageInfo.SetPeerAddr(AsCoreType(&sSubscriberAddr)); + messageInfo.SetPeerPort(sSubscriberPort); + + SuccessOrQuit(leader.Get().SendMessageWithResponseHandlerSeparateParams( + *notification, messageInfo, nullptr, nullptr, nullptr, nullptr, nullptr)); + + nexus.AdvanceTime(5 * 1000); + + VerifyOrQuit(sNotificationReceived); + VerifyOrQuit(sObserveValue == 1); + VerifyOrQuit(strcmp(sReceivedPayload, "msg0") == 0); + + // Router cancels subscription + message = router.Get().NewMessage(); + VerifyOrQuit(message != nullptr); + SuccessOrQuit(message->Init(Coap::kTypeConfirmable, Coap::kCodeGet)); + SuccessOrQuit(message->WriteToken(sSubscriberToken)); // Use same token + SuccessOrQuit(message->AppendObserveOption(1)); // Observe=1 means cancel + SuccessOrQuit(message->AppendUriPathOptions("test")); + + sRequestHandlerCalled = false; + sSubscriptionActive = false; + + messageInfo.SetPeerAddr(leader.Get().GetMeshLocalEid()); + messageInfo.SetPeerPort(OT_DEFAULT_COAP_PORT); + + SuccessOrQuit(router.Get().SendMessageWithResponseHandlerSeparateParams( + *message, messageInfo, nullptr, &HandleNotification, nullptr, nullptr, nullptr)); + + nexus.AdvanceTime(5 * 1000); + + VerifyOrQuit(sRequestHandlerCalled); + VerifyOrQuit(!sSubscriberPresent); + + leader.Get().RemoveResource(resource); + IgnoreError(leader.Get().Stop()); + IgnoreError(router.Get().Stop()); +} + +} // namespace Nexus +} // namespace ot + +int main(void) +{ + ot::Nexus::TestCoapObserve(); + printf("All tests passed\n"); + return 0; +} diff --git a/tests/scripts/thread-cert/test_coap_observe.py b/tests/scripts/thread-cert/test_coap_observe.py deleted file mode 100755 index 5aa89db03..000000000 --- a/tests/scripts/thread-cert/test_coap_observe.py +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (c) 2020, 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. -# - -import unittest - -import pexpect -import config -import thread_cert - -LEADER = 1 -ROUTER = 2 - - -class TestCoapObserve(thread_cert.TestCase): - """ - Test suite for CoAP Observations (RFC7641). - """ - - SUPPORT_NCP = False - - TOPOLOGY = { - LEADER: { - 'mode': 'rdn', - 'allowlist': [ROUTER] - }, - ROUTER: { - 'mode': 'rdn', - 'allowlist': [LEADER] - }, - } - - def _do_notification_test(self, con): - self.nodes[LEADER].start() - self.simulator.go(config.LEADER_STARTUP_DELAY) - self.assertEqual(self.nodes[LEADER].get_state(), 'leader') - - self.nodes[ROUTER].start() - self.simulator.go(config.ROUTER_STARTUP_DELAY) - self.assertEqual(self.nodes[ROUTER].get_state(), 'router') - - mleid = self.nodes[LEADER].get_ip6_address(config.ADDRESS_TYPE.ML_EID) - - self.nodes[LEADER].coap_start() - self.nodes[LEADER].coap_set_resource_path('test') - self.nodes[LEADER].coap_set_content('Test123') - - self.nodes[ROUTER].coap_start() - response = self.nodes[ROUTER].coap_observe(mleid, 'test', con=con) - - first_observe = response['observe'] - self.assertIsNotNone(first_observe) - self.assertEqual(response['payload'], 'Test123') - self.assertEqual(response['source'], mleid) - - # This should have been emitted already, so should return immediately - self.nodes[LEADER].coap_wait_subscribe() - - # Now change the content on the leader and wait for it to show up - # on the router. We will do this a few times with a short delay. - for n in range(0, 5): - content = 'msg%d' % n - - self.nodes[LEADER].coap_set_content(content) - - response = self.nodes[ROUTER].coap_wait_response() - self.assertGreater(response['observe'], first_observe) - self.assertEqual(response['payload'], content) - self.assertEqual(response['source'], mleid) - - # Stop subscription - self.nodes[ROUTER].coap_cancel() - - # We should see the response, but with no Observe option - response = self.nodes[ROUTER].coap_wait_response() - self.assertIsNone(response['observe']) - # Content won't have changed. - self.assertEqual(response['payload'], content) - - # Make another change, no notification should be sent - self.nodes[LEADER].coap_set_content('LastNote') - - # This should time out! - try: - self.nodes[ROUTER].coap_wait_response() - self.fail('Should not have received notification') - except pexpect.exceptions.TIMEOUT: - pass - - self.nodes[ROUTER].coap_stop() - self.nodes[LEADER].coap_stop() - - def test_con(self): - """ - Test notification using CON messages. - """ - for trial in range(0, 3): - try: - self._do_notification_test(con=True) - break - except (AssertionError, pexpect.exceptions.TIMEOUT): - continue - - def test_non(self): - """ - Test notification using NON messages. - """ - for trial in range(0, 3): - try: - self._do_notification_test(con=False) - break - except (AssertionError, pexpect.exceptions.TIMEOUT): - continue - - -if __name__ == '__main__': - unittest.main()