• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2018, 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 implements Channel Manager.
32  *
33  */
34 
35 #include "channel_manager.hpp"
36 
37 #if OPENTHREAD_CONFIG_CHANNEL_MANAGER_ENABLE && OPENTHREAD_FTD
38 
39 #include "common/code_utils.hpp"
40 #include "common/instance.hpp"
41 #include "common/locator_getters.hpp"
42 #include "common/log.hpp"
43 #include "common/random.hpp"
44 #include "common/string.hpp"
45 #include "meshcop/dataset_updater.hpp"
46 #include "radio/radio.hpp"
47 
48 namespace ot {
49 namespace Utils {
50 
51 RegisterLogModule("ChannelManager");
52 
ChannelManager(Instance & aInstance)53 ChannelManager::ChannelManager(Instance &aInstance)
54     : InstanceLocator(aInstance)
55     , mSupportedChannelMask(0)
56     , mFavoredChannelMask(0)
57     , mDelay(kMinimumDelay)
58     , mChannel(0)
59     , mState(kStateIdle)
60     , mTimer(aInstance, ChannelManager::HandleTimer)
61     , mAutoSelectInterval(kDefaultAutoSelectInterval)
62     , mAutoSelectEnabled(false)
63     , mCcaFailureRateThreshold(kCcaFailureRateThreshold)
64 {
65 }
66 
RequestChannelChange(uint8_t aChannel)67 void ChannelManager::RequestChannelChange(uint8_t aChannel)
68 {
69     LogInfo("Request to change to channel %d with delay %d sec", aChannel, mDelay);
70 
71     if (aChannel == Get<Mac::Mac>().GetPanChannel())
72     {
73         LogInfo("Already operating on the requested channel %d", aChannel);
74         ExitNow();
75     }
76 
77     if (mState == kStateChangeInProgress)
78     {
79         VerifyOrExit(mChannel != aChannel);
80     }
81 
82     mState   = kStateChangeRequested;
83     mChannel = aChannel;
84 
85     mTimer.Start(1 + Random::NonCrypto::GetUint32InRange(0, kRequestStartJitterInterval));
86 
87     Get<Notifier>().Signal(kEventChannelManagerNewChannelChanged);
88 
89 exit:
90     return;
91 }
92 
SetDelay(uint16_t aDelay)93 Error ChannelManager::SetDelay(uint16_t aDelay)
94 {
95     Error error = kErrorNone;
96 
97     VerifyOrExit(aDelay >= kMinimumDelay, error = kErrorInvalidArgs);
98     mDelay = aDelay;
99 
100 exit:
101     return error;
102 }
103 
StartDatasetUpdate(void)104 void ChannelManager::StartDatasetUpdate(void)
105 {
106     MeshCoP::Dataset::Info dataset;
107 
108     dataset.Clear();
109     dataset.SetChannel(mChannel);
110     dataset.SetDelay(Time::SecToMsec(mDelay));
111 
112     switch (Get<MeshCoP::DatasetUpdater>().RequestUpdate(dataset, HandleDatasetUpdateDone, this))
113     {
114     case kErrorNone:
115         mState = kStateChangeInProgress;
116         // Wait for the `HandleDatasetUpdateDone()` callback.
117         break;
118 
119     case kErrorBusy:
120     case kErrorNoBufs:
121         mTimer.Start(kPendingDatasetTxRetryInterval);
122         break;
123 
124     case kErrorInvalidState:
125         LogInfo("Request to change to channel %d failed. Device is disabled", mChannel);
126 
127         OT_FALL_THROUGH;
128 
129     default:
130         mState = kStateIdle;
131         StartAutoSelectTimer();
132         break;
133     }
134 }
135 
HandleDatasetUpdateDone(Error aError,void * aContext)136 void ChannelManager::HandleDatasetUpdateDone(Error aError, void *aContext)
137 {
138     static_cast<ChannelManager *>(aContext)->HandleDatasetUpdateDone(aError);
139 }
140 
HandleDatasetUpdateDone(Error aError)141 void ChannelManager::HandleDatasetUpdateDone(Error aError)
142 {
143     if (aError == kErrorNone)
144     {
145         LogInfo("Channel changed to %d", mChannel);
146     }
147     else
148     {
149         LogInfo("Canceling channel change to %d%s", mChannel,
150                 (aError == kErrorAlready) ? " since current ActiveDataset is more recent" : "");
151     }
152 
153     mState = kStateIdle;
154     StartAutoSelectTimer();
155 }
156 
HandleTimer(Timer & aTimer)157 void ChannelManager::HandleTimer(Timer &aTimer)
158 {
159     aTimer.Get<ChannelManager>().HandleTimer();
160 }
161 
HandleTimer(void)162 void ChannelManager::HandleTimer(void)
163 {
164     switch (mState)
165     {
166     case kStateIdle:
167         LogInfo("Auto-triggered channel select");
168         IgnoreError(RequestChannelSelect(false));
169         StartAutoSelectTimer();
170         break;
171 
172     case kStateChangeRequested:
173         StartDatasetUpdate();
174         break;
175 
176     case kStateChangeInProgress:
177         break;
178     }
179 }
180 
181 #if OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE
182 
FindBetterChannel(uint8_t & aNewChannel,uint16_t & aOccupancy)183 Error ChannelManager::FindBetterChannel(uint8_t &aNewChannel, uint16_t &aOccupancy)
184 {
185     Error            error = kErrorNone;
186     Mac::ChannelMask favoredAndSupported;
187     Mac::ChannelMask favoredBest;
188     Mac::ChannelMask supportedBest;
189     uint16_t         favoredOccupancy;
190     uint16_t         supportedOccupancy;
191 
192     if (Get<ChannelMonitor>().GetSampleCount() <= kMinChannelMonitorSampleCount)
193     {
194         LogInfo("Too few samples (%d <= %d) to select channel", Get<ChannelMonitor>().GetSampleCount(),
195                 kMinChannelMonitorSampleCount);
196         ExitNow(error = kErrorInvalidState);
197     }
198 
199     favoredAndSupported = mFavoredChannelMask;
200     favoredAndSupported.Intersect(mSupportedChannelMask);
201 
202     favoredBest   = Get<ChannelMonitor>().FindBestChannels(favoredAndSupported, favoredOccupancy);
203     supportedBest = Get<ChannelMonitor>().FindBestChannels(mSupportedChannelMask, supportedOccupancy);
204 
205     LogInfo("Best favored %s, occupancy 0x%04x", favoredBest.ToString().AsCString(), favoredOccupancy);
206     LogInfo("Best overall %s, occupancy 0x%04x", supportedBest.ToString().AsCString(), supportedOccupancy);
207 
208     // Prefer favored channels unless there is no favored channel,
209     // or the occupancy rate of the best favored channel is worse
210     // than the best overall by at least `kThresholdToSkipFavored`.
211 
212     if (favoredBest.IsEmpty() || ((favoredOccupancy >= kThresholdToSkipFavored) &&
213                                   (supportedOccupancy < favoredOccupancy - kThresholdToSkipFavored)))
214     {
215         if (!favoredBest.IsEmpty())
216         {
217             LogInfo("Preferring an unfavored channel due to high occupancy rate diff");
218         }
219 
220         favoredBest      = supportedBest;
221         favoredOccupancy = supportedOccupancy;
222     }
223 
224     VerifyOrExit(!favoredBest.IsEmpty(), error = kErrorNotFound);
225 
226     aNewChannel = favoredBest.ChooseRandomChannel();
227     aOccupancy  = favoredOccupancy;
228 
229 exit:
230     return error;
231 }
232 
ShouldAttemptChannelChange(void)233 bool ChannelManager::ShouldAttemptChannelChange(void)
234 {
235     uint16_t ccaFailureRate = Get<Mac::Mac>().GetCcaFailureRate();
236     bool     shouldAttempt  = (ccaFailureRate >= mCcaFailureRateThreshold);
237 
238     LogInfo("CCA-err-rate: 0x%04x %s 0x%04x, selecting channel: %s", ccaFailureRate, shouldAttempt ? ">=" : "<",
239             mCcaFailureRateThreshold, ToYesNo(shouldAttempt));
240 
241     return shouldAttempt;
242 }
243 
RequestChannelSelect(bool aSkipQualityCheck)244 Error ChannelManager::RequestChannelSelect(bool aSkipQualityCheck)
245 {
246     Error    error = kErrorNone;
247     uint8_t  curChannel, newChannel;
248     uint16_t curOccupancy, newOccupancy;
249 
250     LogInfo("Request to select channel (skip quality check: %s)", ToYesNo(aSkipQualityCheck));
251 
252     VerifyOrExit(!Get<Mle::Mle>().IsDisabled(), error = kErrorInvalidState);
253 
254     VerifyOrExit(aSkipQualityCheck || ShouldAttemptChannelChange());
255 
256     SuccessOrExit(error = FindBetterChannel(newChannel, newOccupancy));
257 
258     curChannel   = Get<Mac::Mac>().GetPanChannel();
259     curOccupancy = Get<ChannelMonitor>().GetChannelOccupancy(curChannel);
260 
261     if (newChannel == curChannel)
262     {
263         LogInfo("Already on best possible channel %d", curChannel);
264         ExitNow();
265     }
266 
267     LogInfo("Cur channel %d, occupancy 0x%04x - Best channel %d, occupancy 0x%04x", curChannel, curOccupancy,
268             newChannel, newOccupancy);
269 
270     // Switch only if new channel's occupancy rate is better than current
271     // channel's occupancy rate by threshold `kThresholdToChangeChannel`.
272 
273     if ((newOccupancy >= curOccupancy) ||
274         (static_cast<uint16_t>(curOccupancy - newOccupancy) < kThresholdToChangeChannel))
275     {
276         LogInfo("Occupancy rate diff too small to change channel");
277         ExitNow();
278     }
279 
280     RequestChannelChange(newChannel);
281 
282 exit:
283 
284     if (error != kErrorNone)
285     {
286         LogInfo("Request to select better channel failed, error: %s", ErrorToString(error));
287     }
288 
289     return error;
290 }
291 #endif // OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE
292 
StartAutoSelectTimer(void)293 void ChannelManager::StartAutoSelectTimer(void)
294 {
295     VerifyOrExit(mState == kStateIdle);
296 
297     if (mAutoSelectEnabled)
298     {
299         mTimer.Start(Time::SecToMsec(mAutoSelectInterval));
300     }
301     else
302     {
303         mTimer.Stop();
304     }
305 
306 exit:
307     return;
308 }
309 
SetAutoChannelSelectionEnabled(bool aEnabled)310 void ChannelManager::SetAutoChannelSelectionEnabled(bool aEnabled)
311 {
312     if (aEnabled != mAutoSelectEnabled)
313     {
314         mAutoSelectEnabled = aEnabled;
315         IgnoreError(RequestChannelSelect(false));
316         StartAutoSelectTimer();
317     }
318 }
319 
SetAutoChannelSelectionInterval(uint32_t aInterval)320 Error ChannelManager::SetAutoChannelSelectionInterval(uint32_t aInterval)
321 {
322     Error    error        = kErrorNone;
323     uint32_t prevInterval = mAutoSelectInterval;
324 
325     VerifyOrExit((aInterval != 0) && (aInterval <= Time::MsecToSec(Timer::kMaxDelay)), error = kErrorInvalidArgs);
326 
327     mAutoSelectInterval = aInterval;
328 
329     if (mAutoSelectEnabled && (mState == kStateIdle) && mTimer.IsRunning() && (prevInterval != aInterval))
330     {
331         mTimer.StartAt(mTimer.GetFireTime() - Time::SecToMsec(prevInterval), Time::SecToMsec(aInterval));
332     }
333 
334 exit:
335     return error;
336 }
337 
SetSupportedChannels(uint32_t aChannelMask)338 void ChannelManager::SetSupportedChannels(uint32_t aChannelMask)
339 {
340     mSupportedChannelMask.SetMask(aChannelMask & Get<Mac::Mac>().GetSupportedChannelMask().GetMask());
341 
342     LogInfo("Supported channels: %s", mSupportedChannelMask.ToString().AsCString());
343 }
344 
SetFavoredChannels(uint32_t aChannelMask)345 void ChannelManager::SetFavoredChannels(uint32_t aChannelMask)
346 {
347     mFavoredChannelMask.SetMask(aChannelMask & Get<Mac::Mac>().GetSupportedChannelMask().GetMask());
348 
349     LogInfo("Favored channels: %s", mFavoredChannelMask.ToString().AsCString());
350 }
351 
SetCcaFailureRateThreshold(uint16_t aThreshold)352 void ChannelManager::SetCcaFailureRateThreshold(uint16_t aThreshold)
353 {
354     mCcaFailureRateThreshold = aThreshold;
355 
356     LogInfo("CCA threshold: 0x%04x", mCcaFailureRateThreshold);
357 }
358 
359 } // namespace Utils
360 } // namespace ot
361 
362 #endif // #if OPENTHREAD_CONFIG_CHANNEL_MANAGER_ENABLE
363