1 /*
2  *  Copyright (c) 2016, 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 link quality information processing and storage.
32  */
33 
34 #include "link_quality.hpp"
35 
36 #include <stdio.h>
37 
38 #include "common/code_utils.hpp"
39 #include "common/locator_getters.hpp"
40 #include "common/num_utils.hpp"
41 #include "instance/instance.hpp"
42 
43 namespace ot {
44 
45 // This array gives the decimal point digits representing 0/8, 1/8, ..., 7/8 (does not include the '.').
46 static const char *const kDigitsString[8] = {
47     // 0/8,  1/8,   2/8,   3/8,   4/8,   5/8,   6/8,   7/8
48     "0", "125", "25", "375", "5", "625", "75", "875"};
49 
AddSample(bool aSuccess,uint16_t aWeight)50 void SuccessRateTracker::AddSample(bool aSuccess, uint16_t aWeight)
51 {
52     uint32_t oldAverage = mFailureRate;
53     uint32_t newValue   = (aSuccess) ? 0 : kMaxRateValue;
54     uint32_t n          = aWeight;
55 
56     // `n/2` is added to the sum to ensure rounding the value to the nearest integer when dividing by `n`
57     // (e.g., 1.2 -> 1, 3.5 -> 4).
58 
59     mFailureRate = static_cast<uint16_t>(((oldAverage * (n - 1)) + newValue + (n / 2)) / n);
60 }
61 
Add(int8_t aRss)62 Error RssAverager::Add(int8_t aRss)
63 {
64     Error    error = kErrorNone;
65     uint16_t newValue;
66 
67     VerifyOrExit(aRss != Radio::kInvalidRssi, error = kErrorInvalidArgs);
68 
69     // Restrict the RSS value to the closed range [-128, 0]
70     // so the RSS times precision multiple can fit in 11 bits.
71     aRss = Min<int8_t>(aRss, 0);
72 
73     // Multiply the RSS value by a precision multiple (currently -8).
74 
75     newValue = static_cast<uint16_t>(-aRss);
76     newValue <<= kPrecisionBitShift;
77 
78     mCount += (mCount < (1 << kCoeffBitShift));
79     // Maintain arithmetic mean.
80     // newAverage = newValue * (1/mCount) + oldAverage * ((mCount -1)/mCount)
81     mAverage = static_cast<uint16_t>(((mAverage * (mCount - 1)) + newValue) / mCount);
82 
83 exit:
84     return error;
85 }
86 
GetAverage(void) const87 int8_t RssAverager::GetAverage(void) const
88 {
89     int8_t average;
90 
91     VerifyOrExit(mCount != 0, average = Radio::kInvalidRssi);
92 
93     average = -static_cast<int8_t>(mAverage >> kPrecisionBitShift);
94 
95     // Check for possible round up (e.g., average of -71.5 --> -72)
96 
97     if ((mAverage & kPrecisionBitMask) >= (kPrecision >> 1))
98     {
99         average--;
100     }
101 
102 exit:
103     return average;
104 }
105 
ToString(void) const106 RssAverager::InfoString RssAverager::ToString(void) const
107 {
108     InfoString string;
109 
110     VerifyOrExit(mCount != 0);
111     string.Append("%d.%s", -(mAverage >> kPrecisionBitShift), kDigitsString[mAverage & kPrecisionBitMask]);
112 
113 exit:
114     return string;
115 }
116 
Add(uint8_t aLqi)117 void LqiAverager::Add(uint8_t aLqi)
118 {
119     uint8_t count;
120 
121     if (mCount < UINT8_MAX)
122     {
123         mCount++;
124     }
125 
126     count = Min(static_cast<uint8_t>(1 << kCoeffBitShift), mCount);
127 
128     mAverage = static_cast<uint8_t>(((mAverage * (count - 1)) + aLqi) / count);
129 }
130 
Clear(void)131 void LinkQualityInfo::Clear(void)
132 {
133     mRssAverager.Clear();
134     SetLinkQuality(kLinkQuality0);
135     mLastRss = Radio::kInvalidRssi;
136 
137     mFrameErrorRate.Clear();
138     mMessageErrorRate.Clear();
139 }
140 
AddRss(int8_t aRss)141 void LinkQualityInfo::AddRss(int8_t aRss)
142 {
143     uint8_t oldLinkQuality = kNoLinkQuality;
144 
145     VerifyOrExit(aRss != Radio::kInvalidRssi);
146 
147     mLastRss = aRss;
148 
149     if (mRssAverager.HasAverage())
150     {
151         oldLinkQuality = GetLinkQuality();
152     }
153 
154     SuccessOrExit(mRssAverager.Add(aRss));
155 
156     SetLinkQuality(CalculateLinkQuality(GetLinkMargin(), oldLinkQuality));
157 
158 exit:
159     return;
160 }
161 
GetLinkMargin(void) const162 uint8_t LinkQualityInfo::GetLinkMargin(void) const
163 {
164     return ComputeLinkMargin(Get<Mac::SubMac>().GetNoiseFloor(), GetAverageRss());
165 }
166 
ToInfoString(void) const167 LinkQualityInfo::InfoString LinkQualityInfo::ToInfoString(void) const
168 {
169     InfoString string;
170 
171     string.Append("aveRss:%s, lastRss:%d, linkQuality:%d", mRssAverager.ToString().AsCString(), GetLastRss(),
172                   GetLinkQuality());
173 
174     return string;
175 }
176 
ComputeLinkMargin(int8_t aNoiseFloor,int8_t aRss)177 uint8_t ComputeLinkMargin(int8_t aNoiseFloor, int8_t aRss)
178 {
179     int8_t linkMargin = aRss - aNoiseFloor;
180 
181     if (linkMargin < 0 || aRss == Radio::kInvalidRssi)
182     {
183         linkMargin = 0;
184     }
185 
186     return static_cast<uint8_t>(linkMargin);
187 }
188 
LinkQualityForLinkMargin(uint8_t aLinkMargin)189 LinkQuality LinkQualityForLinkMargin(uint8_t aLinkMargin)
190 {
191     return LinkQualityInfo::CalculateLinkQuality(aLinkMargin, LinkQualityInfo::kNoLinkQuality);
192 }
193 
GetTypicalRssForLinkQuality(int8_t aNoiseFloor,LinkQuality aLinkQuality)194 int8_t GetTypicalRssForLinkQuality(int8_t aNoiseFloor, LinkQuality aLinkQuality)
195 {
196     int8_t linkMargin = 0;
197 
198     switch (aLinkQuality)
199     {
200     case kLinkQuality3:
201         linkMargin = LinkQualityInfo::kLinkQuality3LinkMargin;
202         break;
203 
204     case kLinkQuality2:
205         linkMargin = LinkQualityInfo::kLinkQuality2LinkMargin;
206         break;
207 
208     case kLinkQuality1:
209         linkMargin = LinkQualityInfo::kLinkQuality1LinkMargin;
210         break;
211 
212     default:
213         linkMargin = LinkQualityInfo::kLinkQuality0LinkMargin;
214         break;
215     }
216 
217     return linkMargin + aNoiseFloor;
218 }
219 
CostForLinkQuality(LinkQuality aLinkQuality)220 uint8_t CostForLinkQuality(LinkQuality aLinkQuality)
221 {
222     static const uint8_t kCostsForLinkQuality[] = {
223         kCostForLinkQuality0, // Link cost for `kLinkQuality0` (0).
224         kCostForLinkQuality1, // Link cost for `kLinkQuality1` (1).
225         kCostForLinkQuality2, // Link cost for `kLinkQuality2` (2).
226         kCostForLinkQuality3, // Link cost for `kLinkQuality3` (3).
227     };
228 
229     static_assert(kLinkQuality0 == 0, "kLinkQuality0 is invalid");
230     static_assert(kLinkQuality1 == 1, "kLinkQuality1 is invalid");
231     static_assert(kLinkQuality2 == 2, "kLinkQuality2 is invalid");
232     static_assert(kLinkQuality3 == 3, "kLinkQuality3 is invalid");
233 
234     uint8_t cost = Mle::kMaxRouteCost;
235 
236     VerifyOrExit(aLinkQuality <= kLinkQuality3);
237     cost = kCostsForLinkQuality[aLinkQuality];
238 
239 exit:
240     return cost;
241 }
242 
CalculateLinkQuality(uint8_t aLinkMargin,uint8_t aLastLinkQuality)243 LinkQuality LinkQualityInfo::CalculateLinkQuality(uint8_t aLinkMargin, uint8_t aLastLinkQuality)
244 {
245     // Static private method to calculate the link quality from a given
246     // link margin while taking into account the last link quality
247     // value and adding the hysteresis value to the thresholds. If
248     // there is no previous value for link quality, the constant
249     // kNoLinkQuality should be passed as the second argument.
250 
251     uint8_t     threshold1, threshold2, threshold3;
252     LinkQuality linkQuality = kLinkQuality0;
253 
254     threshold1 = kThreshold1;
255     threshold2 = kThreshold2;
256     threshold3 = kThreshold3;
257 
258     // Apply the hysteresis threshold based on the last link quality value.
259 
260     switch (aLastLinkQuality)
261     {
262     case 0:
263         threshold1 += kHysteresisThreshold;
264 
265         OT_FALL_THROUGH;
266 
267     case 1:
268         threshold2 += kHysteresisThreshold;
269 
270         OT_FALL_THROUGH;
271 
272     case 2:
273         threshold3 += kHysteresisThreshold;
274 
275         OT_FALL_THROUGH;
276 
277     default:
278         break;
279     }
280 
281     if (aLinkMargin > threshold3)
282     {
283         linkQuality = kLinkQuality3;
284     }
285     else if (aLinkMargin > threshold2)
286     {
287         linkQuality = kLinkQuality2;
288     }
289     else if (aLinkMargin > threshold1)
290     {
291         linkQuality = kLinkQuality1;
292     }
293 
294     return linkQuality;
295 }
296 
297 } // namespace ot
298