xref: /aosp_15_r20/external/ot-br-posix/src/ncp/rcp_host.hpp (revision 4a64e381480ef79f0532b2421e44e6ee336b8e0d)
1 /*
2  *  Copyright (c) 2017, The OpenThread Authors.
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *  1. Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  *  2. Redistributions in binary form must reproduce the above copyright
10  *     notice, this list of conditions and the following disclaimer in the
11  *     documentation and/or other materials provided with the distribution.
12  *  3. Neither the name of the copyright holder nor the
13  *     names of its contributors may be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  *   This file includes definitions of Thread Controller under RCP mode.
32  */
33 
34 #ifndef OTBR_AGENT_RCP_HOST_HPP_
35 #define OTBR_AGENT_RCP_HOST_HPP_
36 
37 #include "openthread-br/config.h"
38 
39 #include <chrono>
40 #include <memory>
41 
42 #include <assert.h>
43 
44 #include <openthread/backbone_router_ftd.h>
45 #include <openthread/cli.h>
46 #include <openthread/instance.h>
47 #include <openthread/openthread-system.h>
48 
49 #include "common/mainloop.hpp"
50 #include "common/task_runner.hpp"
51 #include "common/types.hpp"
52 #include "ncp/thread_host.hpp"
53 #include "utils/thread_helper.hpp"
54 
55 namespace otbr {
56 #if OTBR_ENABLE_FEATURE_FLAGS
57 // Forward declaration of FeatureFlagList proto.
58 class FeatureFlagList;
59 #endif
60 
61 namespace Ncp {
62 
63 /**
64  * This class implements the NetworkProperties for architectures where OT APIs are directly accessible.
65  */
66 class OtNetworkProperties : virtual public NetworkProperties
67 {
68 public:
69     /**
70      * Constructor.
71      */
72     explicit OtNetworkProperties(void);
73 
74     // NetworkProperties methods
75     otDeviceRole GetDeviceRole(void) const override;
76     bool         Ip6IsEnabled(void) const override;
77     uint32_t     GetPartitionId(void) const override;
78     void         GetDatasetActiveTlvs(otOperationalDatasetTlvs &aDatasetTlvs) const override;
79     void         GetDatasetPendingTlvs(otOperationalDatasetTlvs &aDatasetTlvs) const override;
80 
81     // Set the otInstance
82     void SetInstance(otInstance *aInstance);
83 
84 private:
85     otInstance *mInstance;
86 };
87 
88 /**
89  * This interface defines OpenThread Controller under RCP mode.
90  */
91 class RcpHost : public MainloopProcessor, public ThreadHost, public OtNetworkProperties
92 {
93 public:
94     /**
95      * This constructor initializes this object.
96      *
97      * @param[in]   aInterfaceName          A string of the NCP interface name.
98      * @param[in]   aRadioUrls              The radio URLs (can be IEEE802.15.4 or TREL radio).
99      * @param[in]   aBackboneInterfaceName  The Backbone network interface name.
100      * @param[in]   aDryRun                 TRUE to indicate dry-run mode. FALSE otherwise.
101      * @param[in]   aEnableAutoAttach       Whether or not to automatically attach to the saved network.
102      */
103     RcpHost(const char                      *aInterfaceName,
104             const std::vector<const char *> &aRadioUrls,
105             const char                      *aBackboneInterfaceName,
106             bool                             aDryRun,
107             bool                             aEnableAutoAttach);
108 
109     /**
110      * This method initialize the Thread controller.
111      */
112     void Init(void) override;
113 
114     /**
115      * This method deinitialize the Thread controller.
116      */
117     void Deinit(void) override;
118 
119     /**
120      * Returns an OpenThread instance.
121      *
122      * @retval Non-null OpenThread instance if `RcpHost::Init()` has been called.
123      *         Otherwise, it's guaranteed to be `null`
124      */
GetInstance(void)125     otInstance *GetInstance(void) { return mInstance; }
126 
127     /**
128      * This method gets the thread functionality helper.
129      *
130      * @retval The pointer to the helper object.
131      */
GetThreadHelper(void)132     otbr::agent::ThreadHelper *GetThreadHelper(void)
133     {
134         assert(mThreadHelper != nullptr);
135         return mThreadHelper.get();
136     }
137 
138     void Update(MainloopContext &aMainloop) override;
139     void Process(const MainloopContext &aMainloop) override;
140 
141     /**
142      * This method posts a task to the timer
143      *
144      * @param[in] aDelay  The delay in milliseconds before executing the task.
145      * @param[in] aTask   The task function.
146      */
147     void PostTimerTask(Milliseconds aDelay, TaskRunner::Task<void> aTask);
148 
149     /**
150      * This method registers a reset handler.
151      *
152      * @param[in] aHandler  The handler function.
153      */
154     void RegisterResetHandler(std::function<void(void)> aHandler);
155 
156     /**
157      * This method resets the OpenThread instance.
158      */
159     void Reset(void);
160 
161     /**
162      * This method returns the Thread protocol version as a string.
163      *
164      * @returns A pointer to the Thread version string.
165      */
166     static const char *GetThreadVersion(void);
167 
168     /**
169      * This method returns the Thread network interface name.
170      *
171      * @returns A pointer to the Thread network interface name string.
172      */
GetInterfaceName(void) const173     const char *GetInterfaceName(void) const override { return mConfig.mInterfaceName; }
174 
175     static otbrLogLevel ConvertToOtbrLogLevel(otLogLevel aLogLevel);
176 
177 #if OTBR_ENABLE_FEATURE_FLAGS
178     /**
179      * Apply the feature flag values to OpenThread through OpenThread APIs.
180      *
181      * @param[in] aFeatureFlagList  The feature flag list to be applied to OpenThread.
182      *
183      * @returns The error value of underlying OpenThread API calls.
184      */
185     otError ApplyFeatureFlagList(const FeatureFlagList &aFeatureFlagList);
186 
187     /**
188      * This method returns the applied FeatureFlagList in ApplyFeatureFlagList call.
189      *
190      * @returns the applied FeatureFlagList's serialized bytes.
191      */
GetAppliedFeatureFlagListBytes(void)192     const std::string &GetAppliedFeatureFlagListBytes(void)
193     {
194         return mAppliedFeatureFlagListBytes;
195     }
196 #endif
197 
198     ~RcpHost(void) override;
199 
200     // Thread Control virtual methods
201     void Join(const otOperationalDatasetTlvs &aActiveOpDatasetTlvs, const AsyncResultReceiver &aRecevier) override;
202     void Leave(const AsyncResultReceiver &aRecevier) override;
203     void ScheduleMigration(const otOperationalDatasetTlvs &aPendingOpDatasetTlvs,
204                            const AsyncResultReceiver       aReceiver) override;
205     void SetThreadEnabled(bool aEnabled, const AsyncResultReceiver aReceiver) override;
206     void SetCountryCode(const std::string &aCountryCode, const AsyncResultReceiver &aReceiver) override;
207     void GetChannelMasks(const ChannelMasksReceiver &aReceiver, const AsyncResultReceiver &aErrReceiver) override;
208     void SetChannelMaxPowers(const std::vector<ChannelMaxPower> &aChannelMaxPowers,
209                              const AsyncResultReceiver          &aReceiver) override;
210     void AddThreadStateChangedCallback(ThreadStateChangedCallback aCallback) override;
211 
GetCoprocessorType(void)212     CoprocessorType GetCoprocessorType(void) override
213     {
214         return OT_COPROCESSOR_RCP;
215     }
216 
GetCoprocessorVersion(void)217     const char *GetCoprocessorVersion(void) override
218     {
219         return otPlatRadioGetVersionString(mInstance);
220     }
221 
222 private:
SafeInvokeAndClear(AsyncResultReceiver & aReceiver,otError aError,const std::string & aErrorInfo="")223     static void SafeInvokeAndClear(AsyncResultReceiver &aReceiver, otError aError, const std::string &aErrorInfo = "")
224     {
225         if (aReceiver)
226         {
227             aReceiver(aError, aErrorInfo);
228             aReceiver = nullptr;
229         }
230     }
231 
HandleStateChanged(otChangedFlags aFlags,void * aContext)232     static void HandleStateChanged(otChangedFlags aFlags, void *aContext)
233     {
234         static_cast<RcpHost *>(aContext)->HandleStateChanged(aFlags);
235     }
236     void HandleStateChanged(otChangedFlags aFlags);
237 
238     static void HandleBackboneRouterDomainPrefixEvent(void                             *aContext,
239                                                       otBackboneRouterDomainPrefixEvent aEvent,
240                                                       const otIp6Prefix                *aDomainPrefix);
241     void        HandleBackboneRouterDomainPrefixEvent(otBackboneRouterDomainPrefixEvent aEvent,
242                                                       const otIp6Prefix                *aDomainPrefix);
243 
244 #if OTBR_ENABLE_DUA_ROUTING
245     static void HandleBackboneRouterNdProxyEvent(void                        *aContext,
246                                                  otBackboneRouterNdProxyEvent aEvent,
247                                                  const otIp6Address          *aAddress);
248     void        HandleBackboneRouterNdProxyEvent(otBackboneRouterNdProxyEvent aEvent, const otIp6Address *aAddress);
249 #endif
250 
251     static void DisableThreadAfterDetach(void *aContext);
252     void        DisableThreadAfterDetach(void);
253     static void SendMgmtPendingSetCallback(otError aError, void *aContext);
254     void        SendMgmtPendingSetCallback(otError aError);
255 
256     bool IsAutoAttachEnabled(void);
257     void DisableAutoAttach(void);
258 
259     bool IsAttached(void);
260 
261     otError SetOtbrAndOtLogLevel(otbrLogLevel aLevel);
262 
263     otInstance *mInstance;
264 
265     otPlatformConfig                           mConfig;
266     std::unique_ptr<otbr::agent::ThreadHelper> mThreadHelper;
267     std::vector<std::function<void(void)>>     mResetHandlers;
268     TaskRunner                                 mTaskRunner;
269     std::vector<ThreadStateChangedCallback>    mThreadStateChangedCallbacks;
270     bool                                       mEnableAutoAttach = false;
271 
272     AsyncResultReceiver mSetThreadEnabledReceiver;
273     AsyncResultReceiver mScheduleMigrationReceiver;
274 
275 #if OTBR_ENABLE_FEATURE_FLAGS
276     // The applied FeatureFlagList in ApplyFeatureFlagList call, used for debugging purpose.
277     std::string mAppliedFeatureFlagListBytes;
278 #endif
279 };
280 
281 } // namespace Ncp
282 } // namespace otbr
283 
284 #endif // OTBR_AGENT_RCP_HOST_HPP_
285