• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "host/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 Host {
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(bool aEraseDataset, 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 #if OTBR_ENABLE_POWER_CALIBRATION
209     void SetChannelMaxPowers(const std::vector<ChannelMaxPower> &aChannelMaxPowers,
210                              const AsyncResultReceiver          &aReceiver) override;
211 #endif
212     void AddThreadStateChangedCallback(ThreadStateChangedCallback aCallback) override;
213     void AddThreadEnabledStateChangedCallback(ThreadEnabledStateCallback aCallback) override;
214 
GetCoprocessorType(void)215     CoprocessorType GetCoprocessorType(void) override
216     {
217         return OT_COPROCESSOR_RCP;
218     }
219 
GetCoprocessorVersion(void)220     const char *GetCoprocessorVersion(void) override
221     {
222         return otPlatRadioGetVersionString(mInstance);
223     }
224 
225 private:
SafeInvokeAndClear(AsyncResultReceiver & aReceiver,otError aError,const std::string & aErrorInfo="")226     static void SafeInvokeAndClear(AsyncResultReceiver &aReceiver, otError aError, const std::string &aErrorInfo = "")
227     {
228         if (aReceiver)
229         {
230             aReceiver(aError, aErrorInfo);
231             aReceiver = nullptr;
232         }
233     }
SafeInvoke(const AsyncResultReceiver & aReceiver,otError aError,const std::string & aErrorInfo="")234     static void SafeInvoke(const AsyncResultReceiver &aReceiver, otError aError, const std::string &aErrorInfo = "")
235     {
236         if (aReceiver)
237         {
238             aReceiver(aError, aErrorInfo);
239         }
240     }
241 
HandleStateChanged(otChangedFlags aFlags,void * aContext)242     static void HandleStateChanged(otChangedFlags aFlags, void *aContext)
243     {
244         static_cast<RcpHost *>(aContext)->HandleStateChanged(aFlags);
245     }
246     void HandleStateChanged(otChangedFlags aFlags);
247 
248     using DetachGracefullyCallback = std::function<void()>;
249     void        ThreadDetachGracefully(const DetachGracefullyCallback &aCallback);
250     static void ThreadDetachGracefullyCallback(void *aContext);
251     void        ThreadDetachGracefullyCallback(void);
252     void        ConditionalErasePersistentInfo(bool aErase);
253     void        DisableThreadAfterDetach(void);
254     static void SendMgmtPendingSetCallback(otError aError, void *aContext);
255     void        SendMgmtPendingSetCallback(otError aError);
256 
257     bool IsAutoAttachEnabled(void);
258     void DisableAutoAttach(void);
259 
260     bool IsAttached(void);
261 
262     void UpdateThreadEnabledState(ThreadEnabledState aState);
263 
264     otError SetOtbrAndOtLogLevel(otbrLogLevel aLevel);
265 
266     otInstance *mInstance;
267 
268     otPlatformConfig                           mConfig;
269     std::unique_ptr<otbr::agent::ThreadHelper> mThreadHelper;
270     std::vector<std::function<void(void)>>     mResetHandlers;
271     TaskRunner                                 mTaskRunner;
272 
273     std::vector<ThreadStateChangedCallback> mThreadStateChangedCallbacks;
274     std::vector<ThreadEnabledStateCallback> mThreadEnabledStateChangedCallbacks;
275     bool                                    mEnableAutoAttach = false;
276     ThreadEnabledState                      mThreadEnabledState;
277     AsyncResultReceiver                     mJoinReceiver;
278     AsyncResultReceiver                     mSetThreadEnabledReceiver;
279     AsyncResultReceiver                     mScheduleMigrationReceiver;
280     std::vector<DetachGracefullyCallback>   mDetachGracefullyCallbacks;
281 
282 #if OTBR_ENABLE_FEATURE_FLAGS
283     // The applied FeatureFlagList in ApplyFeatureFlagList call, used for debugging purpose.
284     std::string mAppliedFeatureFlagListBytes;
285 #endif
286 };
287 
288 } // namespace Host
289 } // namespace otbr
290 
291 #endif // OTBR_AGENT_RCP_HOST_HPP_
292