1 /*
2  *  Copyright (c) 2020, 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 for Thread Link Metrics.
32  */
33 
34 #include "link_metrics.hpp"
35 
36 #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE || OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE
37 
38 #include "common/code_utils.hpp"
39 #include "common/encoding.hpp"
40 #include "common/instance.hpp"
41 #include "common/locator_getters.hpp"
42 #include "common/log.hpp"
43 #include "common/num_utils.hpp"
44 #include "common/numeric_limits.hpp"
45 #include "mac/mac.hpp"
46 #include "thread/link_metrics_tlvs.hpp"
47 #include "thread/neighbor_table.hpp"
48 
49 namespace ot {
50 namespace LinkMetrics {
51 
52 RegisterLogModule("LinkMetrics");
53 
54 static constexpr uint8_t kQueryIdSingleProbe = 0;   // This query ID represents Single Probe.
55 static constexpr uint8_t kSeriesIdAllSeries  = 255; // This series ID represents all series.
56 
57 // Constants for scaling Link Margin and RSSI to raw value
58 static constexpr uint8_t kMaxLinkMargin = 130;
59 static constexpr int32_t kMinRssi       = -130;
60 static constexpr int32_t kMaxRssi       = 0;
61 
62 #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE
63 
Initiator(Instance & aInstance)64 Initiator::Initiator(Instance &aInstance)
65     : InstanceLocator(aInstance)
66 {
67 }
68 
Query(const Ip6::Address & aDestination,uint8_t aSeriesId,const Metrics * aMetrics)69 Error Initiator::Query(const Ip6::Address &aDestination, uint8_t aSeriesId, const Metrics *aMetrics)
70 {
71     Error     error;
72     Neighbor *neighbor;
73     QueryInfo info;
74 
75     SuccessOrExit(error = FindNeighbor(aDestination, neighbor));
76 
77     info.Clear();
78     info.mSeriesId = aSeriesId;
79 
80     if (aMetrics != nullptr)
81     {
82         info.mTypeIdCount = aMetrics->ConvertToTypeIds(info.mTypeIds);
83     }
84 
85     if (aSeriesId != 0)
86     {
87         VerifyOrExit(info.mTypeIdCount == 0, error = kErrorInvalidArgs);
88     }
89 
90     error = Get<Mle::Mle>().SendDataRequestForLinkMetricsReport(aDestination, info);
91 
92 exit:
93     return error;
94 }
95 
AppendLinkMetricsQueryTlv(Message & aMessage,const QueryInfo & aInfo)96 Error Initiator::AppendLinkMetricsQueryTlv(Message &aMessage, const QueryInfo &aInfo)
97 {
98     Error error = kErrorNone;
99     Tlv   tlv;
100 
101     // The MLE Link Metrics Query TLV has two sub-TLVs:
102     // - Query ID sub-TLV with series ID as value.
103     // - Query Options sub-TLV with Type IDs as value.
104 
105     tlv.SetType(Mle::Tlv::kLinkMetricsQuery);
106     tlv.SetLength(sizeof(Tlv) + sizeof(uint8_t) + ((aInfo.mTypeIdCount == 0) ? 0 : (sizeof(Tlv) + aInfo.mTypeIdCount)));
107 
108     SuccessOrExit(error = aMessage.Append(tlv));
109 
110     SuccessOrExit(error = Tlv::Append<QueryIdSubTlv>(aMessage, aInfo.mSeriesId));
111 
112     if (aInfo.mTypeIdCount != 0)
113     {
114         QueryOptionsSubTlv queryOptionsTlv;
115 
116         queryOptionsTlv.Init();
117         queryOptionsTlv.SetLength(aInfo.mTypeIdCount);
118         SuccessOrExit(error = aMessage.Append(queryOptionsTlv));
119         SuccessOrExit(error = aMessage.AppendBytes(aInfo.mTypeIds, aInfo.mTypeIdCount));
120     }
121 
122 exit:
123     return error;
124 }
125 
HandleReport(const Message & aMessage,uint16_t aOffset,uint16_t aLength,const Ip6::Address & aAddress)126 void Initiator::HandleReport(const Message &aMessage, uint16_t aOffset, uint16_t aLength, const Ip6::Address &aAddress)
127 {
128     Error         error     = kErrorNone;
129     uint16_t      offset    = aOffset;
130     uint16_t      endOffset = aOffset + aLength;
131     bool          hasStatus = false;
132     bool          hasReport = false;
133     Tlv           tlv;
134     ReportSubTlv  reportTlv;
135     MetricsValues values;
136     uint8_t       status;
137     uint8_t       typeId;
138 
139     OT_UNUSED_VARIABLE(error);
140 
141     VerifyOrExit(mReportCallback.IsSet());
142 
143     values.Clear();
144 
145     while (offset < endOffset)
146     {
147         SuccessOrExit(error = aMessage.Read(offset, tlv));
148 
149         VerifyOrExit(offset + sizeof(Tlv) + tlv.GetLength() <= endOffset, error = kErrorParse);
150 
151         // The report must contain either:
152         // - One or more Report Sub-TLVs (in case of success), or
153         // - A single Status Sub-TLV (in case of failure).
154 
155         switch (tlv.GetType())
156         {
157         case StatusSubTlv::kType:
158             VerifyOrExit(!hasStatus && !hasReport, error = kErrorDrop);
159             SuccessOrExit(error = Tlv::Read<StatusSubTlv>(aMessage, offset, status));
160             hasStatus = true;
161             break;
162 
163         case ReportSubTlv::kType:
164             VerifyOrExit(!hasStatus, error = kErrorDrop);
165 
166             // Read the report sub-TLV assuming minimum length
167             SuccessOrExit(error = aMessage.Read(offset, &reportTlv, sizeof(Tlv) + ReportSubTlv::kMinLength));
168             VerifyOrExit(reportTlv.IsValid(), error = kErrorParse);
169             hasReport = true;
170 
171             typeId = reportTlv.GetMetricsTypeId();
172 
173             if (TypeId::IsExtended(typeId))
174             {
175                 // Skip the sub-TLV if `E` flag is set.
176                 break;
177             }
178 
179             if (TypeId::GetValueLength(typeId) > sizeof(uint8_t))
180             {
181                 // If Type ID indicates metric value has 4 bytes length, we
182                 // read the full `reportTlv`.
183                 SuccessOrExit(error = aMessage.Read(offset, reportTlv));
184             }
185 
186             switch (typeId)
187             {
188             case TypeId::kPdu:
189                 values.mMetrics.mPduCount = true;
190                 values.mPduCountValue     = reportTlv.GetMetricsValue32();
191                 LogDebg(" - PDU Counter: %lu (Count/Summation)", ToUlong(values.mPduCountValue));
192                 break;
193 
194             case TypeId::kLqi:
195                 values.mMetrics.mLqi = true;
196                 values.mLqiValue     = reportTlv.GetMetricsValue8();
197                 LogDebg(" - LQI: %u (Exponential Moving Average)", values.mLqiValue);
198                 break;
199 
200             case TypeId::kLinkMargin:
201                 values.mMetrics.mLinkMargin = true;
202                 values.mLinkMarginValue     = ScaleRawValueToLinkMargin(reportTlv.GetMetricsValue8());
203                 LogDebg(" - Margin: %u (dB) (Exponential Moving Average)", values.mLinkMarginValue);
204                 break;
205 
206             case TypeId::kRssi:
207                 values.mMetrics.mRssi = true;
208                 values.mRssiValue     = ScaleRawValueToRssi(reportTlv.GetMetricsValue8());
209                 LogDebg(" - RSSI: %u (dBm) (Exponential Moving Average)", values.mRssiValue);
210                 break;
211             }
212 
213             break;
214         }
215 
216         offset += sizeof(Tlv) + tlv.GetLength();
217     }
218 
219     VerifyOrExit(hasStatus || hasReport);
220 
221     mReportCallback.Invoke(&aAddress, hasStatus ? nullptr : &values,
222                            hasStatus ? MapEnum(static_cast<Status>(status)) : MapEnum(kStatusSuccess));
223 
224 exit:
225     LogDebg("HandleReport, error:%s", ErrorToString(error));
226 }
227 
SendMgmtRequestForwardTrackingSeries(const Ip6::Address & aDestination,uint8_t aSeriesId,const SeriesFlags & aSeriesFlags,const Metrics * aMetrics)228 Error Initiator::SendMgmtRequestForwardTrackingSeries(const Ip6::Address &aDestination,
229                                                       uint8_t             aSeriesId,
230                                                       const SeriesFlags  &aSeriesFlags,
231                                                       const Metrics      *aMetrics)
232 {
233     Error               error;
234     Neighbor           *neighbor;
235     uint8_t             typeIdCount = 0;
236     FwdProbingRegSubTlv fwdProbingSubTlv;
237 
238     SuccessOrExit(error = FindNeighbor(aDestination, neighbor));
239 
240     VerifyOrExit(aSeriesId > kQueryIdSingleProbe, error = kErrorInvalidArgs);
241 
242     fwdProbingSubTlv.Init();
243     fwdProbingSubTlv.SetSeriesId(aSeriesId);
244     fwdProbingSubTlv.SetSeriesFlagsMask(aSeriesFlags.ConvertToMask());
245 
246     if (aMetrics != nullptr)
247     {
248         typeIdCount = aMetrics->ConvertToTypeIds(fwdProbingSubTlv.GetTypeIds());
249     }
250 
251     fwdProbingSubTlv.SetLength(sizeof(aSeriesId) + sizeof(uint8_t) + typeIdCount);
252 
253     error = Get<Mle::Mle>().SendLinkMetricsManagementRequest(aDestination, fwdProbingSubTlv);
254 
255 exit:
256     LogDebg("SendMgmtRequestForwardTrackingSeries, error:%s, Series ID:%u", ErrorToString(error), aSeriesId);
257     return error;
258 }
259 
SendMgmtRequestEnhAckProbing(const Ip6::Address & aDestination,EnhAckFlags aEnhAckFlags,const Metrics * aMetrics)260 Error Initiator::SendMgmtRequestEnhAckProbing(const Ip6::Address &aDestination,
261                                               EnhAckFlags         aEnhAckFlags,
262                                               const Metrics      *aMetrics)
263 {
264     Error              error;
265     Neighbor          *neighbor;
266     uint8_t            typeIdCount = 0;
267     EnhAckConfigSubTlv enhAckConfigSubTlv;
268 
269     SuccessOrExit(error = FindNeighbor(aDestination, neighbor));
270 
271     if (aEnhAckFlags == kEnhAckClear)
272     {
273         VerifyOrExit(aMetrics == nullptr, error = kErrorInvalidArgs);
274     }
275 
276     enhAckConfigSubTlv.Init();
277     enhAckConfigSubTlv.SetEnhAckFlags(aEnhAckFlags);
278 
279     if (aMetrics != nullptr)
280     {
281         typeIdCount = aMetrics->ConvertToTypeIds(enhAckConfigSubTlv.GetTypeIds());
282     }
283 
284     enhAckConfigSubTlv.SetLength(EnhAckConfigSubTlv::kMinLength + typeIdCount);
285 
286     error = Get<Mle::Mle>().SendLinkMetricsManagementRequest(aDestination, enhAckConfigSubTlv);
287 
288     if (aMetrics != nullptr)
289     {
290         neighbor->SetEnhAckProbingMetrics(*aMetrics);
291     }
292     else
293     {
294         Metrics metrics;
295 
296         metrics.Clear();
297         neighbor->SetEnhAckProbingMetrics(metrics);
298     }
299 
300 exit:
301     return error;
302 }
303 
HandleManagementResponse(const Message & aMessage,const Ip6::Address & aAddress)304 Error Initiator::HandleManagementResponse(const Message &aMessage, const Ip6::Address &aAddress)
305 {
306     Error    error = kErrorNone;
307     uint16_t offset;
308     uint16_t endOffset;
309     uint8_t  status;
310     bool     hasStatus = false;
311 
312     VerifyOrExit(mMgmtResponseCallback.IsSet());
313 
314     SuccessOrExit(
315         error = Tlv::FindTlvValueStartEndOffsets(aMessage, Mle::Tlv::Type::kLinkMetricsManagement, offset, endOffset));
316 
317     while (offset < endOffset)
318     {
319         Tlv tlv;
320 
321         SuccessOrExit(error = aMessage.Read(offset, tlv));
322 
323         switch (tlv.GetType())
324         {
325         case StatusSubTlv::kType:
326             VerifyOrExit(!hasStatus, error = kErrorParse);
327             SuccessOrExit(error = Tlv::Read<StatusSubTlv>(aMessage, offset, status));
328             hasStatus = true;
329             break;
330 
331         default:
332             break;
333         }
334 
335         offset += sizeof(Tlv) + tlv.GetLength();
336     }
337 
338     VerifyOrExit(hasStatus, error = kErrorParse);
339 
340     mMgmtResponseCallback.Invoke(&aAddress, MapEnum(static_cast<Status>(status)));
341 
342 exit:
343     return error;
344 }
345 
SendLinkProbe(const Ip6::Address & aDestination,uint8_t aSeriesId,uint8_t aLength)346 Error Initiator::SendLinkProbe(const Ip6::Address &aDestination, uint8_t aSeriesId, uint8_t aLength)
347 {
348     Error     error;
349     uint8_t   buf[kLinkProbeMaxLen];
350     Neighbor *neighbor;
351 
352     SuccessOrExit(error = FindNeighbor(aDestination, neighbor));
353 
354     VerifyOrExit(aLength <= kLinkProbeMaxLen && aSeriesId != kQueryIdSingleProbe && aSeriesId != kSeriesIdAllSeries,
355                  error = kErrorInvalidArgs);
356 
357     error = Get<Mle::Mle>().SendLinkProbe(aDestination, aSeriesId, buf, aLength);
358 exit:
359     LogDebg("SendLinkProbe, error:%s, Series ID:%u", ErrorToString(error), aSeriesId);
360     return error;
361 }
362 
ProcessEnhAckIeData(const uint8_t * aData,uint8_t aLength,const Neighbor & aNeighbor)363 void Initiator::ProcessEnhAckIeData(const uint8_t *aData, uint8_t aLength, const Neighbor &aNeighbor)
364 {
365     MetricsValues values;
366     uint8_t       idx = 0;
367 
368     VerifyOrExit(mEnhAckProbingIeReportCallback.IsSet());
369 
370     values.SetMetrics(aNeighbor.GetEnhAckProbingMetrics());
371 
372     if (values.GetMetrics().mLqi && idx < aLength)
373     {
374         values.mLqiValue = aData[idx++];
375     }
376     if (values.GetMetrics().mLinkMargin && idx < aLength)
377     {
378         values.mLinkMarginValue = ScaleRawValueToLinkMargin(aData[idx++]);
379     }
380     if (values.GetMetrics().mRssi && idx < aLength)
381     {
382         values.mRssiValue = ScaleRawValueToRssi(aData[idx++]);
383     }
384 
385     mEnhAckProbingIeReportCallback.Invoke(aNeighbor.GetRloc16(), &aNeighbor.GetExtAddress(), &values);
386 
387 exit:
388     return;
389 }
390 
FindNeighbor(const Ip6::Address & aDestination,Neighbor * & aNeighbor)391 Error Initiator::FindNeighbor(const Ip6::Address &aDestination, Neighbor *&aNeighbor)
392 {
393     Error        error = kErrorUnknownNeighbor;
394     Mac::Address macAddress;
395 
396     aNeighbor = nullptr;
397 
398     VerifyOrExit(aDestination.IsLinkLocal());
399     aDestination.GetIid().ConvertToMacAddress(macAddress);
400 
401     aNeighbor = Get<NeighborTable>().FindNeighbor(macAddress);
402     VerifyOrExit(aNeighbor != nullptr);
403 
404     VerifyOrExit(aNeighbor->GetVersion() >= kThreadVersion1p2, error = kErrorNotCapable);
405     error = kErrorNone;
406 
407 exit:
408     return error;
409 }
410 
411 #endif // OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE
412 
413 #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE
Subject(Instance & aInstance)414 Subject::Subject(Instance &aInstance)
415     : InstanceLocator(aInstance)
416 {
417 }
418 
AppendReport(Message & aMessage,const Message & aRequestMessage,Neighbor & aNeighbor)419 Error Subject::AppendReport(Message &aMessage, const Message &aRequestMessage, Neighbor &aNeighbor)
420 {
421     Error         error = kErrorNone;
422     Tlv           tlv;
423     uint8_t       queryId;
424     bool          hasQueryId = false;
425     uint16_t      length;
426     uint16_t      offset;
427     uint16_t      endOffset;
428     MetricsValues values;
429 
430     values.Clear();
431 
432     // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
433     // Parse MLE Link Metrics Query TLV and its sub-TLVs from
434     // `aRequestMessage`.
435 
436     SuccessOrExit(error = Tlv::FindTlvValueStartEndOffsets(aRequestMessage, Mle::Tlv::Type::kLinkMetricsQuery, offset,
437                                                            endOffset));
438 
439     while (offset < endOffset)
440     {
441         SuccessOrExit(error = aRequestMessage.Read(offset, tlv));
442 
443         switch (tlv.GetType())
444         {
445         case SubTlv::kQueryId:
446             SuccessOrExit(error = Tlv::Read<QueryIdSubTlv>(aRequestMessage, offset, queryId));
447             hasQueryId = true;
448             break;
449 
450         case SubTlv::kQueryOptions:
451             SuccessOrExit(error = ReadTypeIdsFromMessage(aRequestMessage, offset + sizeof(tlv),
452                                                          static_cast<uint16_t>(offset + tlv.GetSize()),
453                                                          values.GetMetrics()));
454             break;
455 
456         default:
457             break;
458         }
459 
460         offset += static_cast<uint16_t>(tlv.GetSize());
461     }
462 
463     VerifyOrExit(hasQueryId, error = kErrorParse);
464 
465     // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
466     // Append MLE Link Metrics Report TLV and its sub-TLVs to
467     // `aMessage`.
468 
469     offset = aMessage.GetLength();
470     tlv.SetType(Mle::Tlv::kLinkMetricsReport);
471     SuccessOrExit(error = aMessage.Append(tlv));
472 
473     if (queryId == kQueryIdSingleProbe)
474     {
475         values.mPduCountValue   = aRequestMessage.GetPsduCount();
476         values.mLqiValue        = aRequestMessage.GetAverageLqi();
477         values.mLinkMarginValue = Get<Mac::Mac>().ComputeLinkMargin(aRequestMessage.GetAverageRss());
478         values.mRssiValue       = aRequestMessage.GetAverageRss();
479         SuccessOrExit(error = AppendReportSubTlvToMessage(aMessage, values));
480     }
481     else
482     {
483         SeriesInfo *seriesInfo = aNeighbor.GetForwardTrackingSeriesInfo(queryId);
484 
485         if (seriesInfo == nullptr)
486         {
487             SuccessOrExit(error = Tlv::Append<StatusSubTlv>(aMessage, kStatusSeriesIdNotRecognized));
488         }
489         else if (seriesInfo->GetPduCount() == 0)
490         {
491             SuccessOrExit(error = Tlv::Append<StatusSubTlv>(aMessage, kStatusNoMatchingFramesReceived));
492         }
493         else
494         {
495             values.SetMetrics(seriesInfo->GetLinkMetrics());
496             values.mPduCountValue   = seriesInfo->GetPduCount();
497             values.mLqiValue        = seriesInfo->GetAverageLqi();
498             values.mLinkMarginValue = Get<Mac::Mac>().ComputeLinkMargin(seriesInfo->GetAverageRss());
499             values.mRssiValue       = seriesInfo->GetAverageRss();
500             SuccessOrExit(error = AppendReportSubTlvToMessage(aMessage, values));
501         }
502     }
503 
504     // Update the TLV length in message.
505     length = aMessage.GetLength() - offset - sizeof(Tlv);
506     tlv.SetLength(static_cast<uint8_t>(length));
507     aMessage.Write(offset, tlv);
508 
509 exit:
510     LogDebg("AppendReport, error:%s", ErrorToString(error));
511     return error;
512 }
513 
HandleManagementRequest(const Message & aMessage,Neighbor & aNeighbor,Status & aStatus)514 Error Subject::HandleManagementRequest(const Message &aMessage, Neighbor &aNeighbor, Status &aStatus)
515 {
516     Error               error = kErrorNone;
517     uint16_t            offset;
518     uint16_t            endOffset;
519     uint16_t            tlvEndOffset;
520     FwdProbingRegSubTlv fwdProbingSubTlv;
521     EnhAckConfigSubTlv  enhAckConfigSubTlv;
522     Metrics             metrics;
523 
524     SuccessOrExit(
525         error = Tlv::FindTlvValueStartEndOffsets(aMessage, Mle::Tlv::Type::kLinkMetricsManagement, offset, endOffset));
526 
527     // Set sub-TLV lengths to zero to indicate that we have
528     // not yet seen them in the message.
529     fwdProbingSubTlv.SetLength(0);
530     enhAckConfigSubTlv.SetLength(0);
531 
532     for (; offset < endOffset; offset = tlvEndOffset)
533     {
534         Tlv      tlv;
535         uint16_t minTlvSize;
536         Tlv     *subTlv;
537 
538         SuccessOrExit(error = aMessage.Read(offset, tlv));
539 
540         VerifyOrExit(offset + tlv.GetSize() <= endOffset, error = kErrorParse);
541         tlvEndOffset = static_cast<uint16_t>(offset + tlv.GetSize());
542 
543         switch (tlv.GetType())
544         {
545         case SubTlv::kFwdProbingReg:
546             subTlv     = &fwdProbingSubTlv;
547             minTlvSize = sizeof(Tlv) + FwdProbingRegSubTlv::kMinLength;
548             break;
549 
550         case SubTlv::kEnhAckConfig:
551             subTlv     = &enhAckConfigSubTlv;
552             minTlvSize = sizeof(Tlv) + EnhAckConfigSubTlv::kMinLength;
553             break;
554 
555         default:
556             continue;
557         }
558 
559         // Ensure message contains only one sub-TLV.
560         VerifyOrExit(fwdProbingSubTlv.GetLength() == 0, error = kErrorParse);
561         VerifyOrExit(enhAckConfigSubTlv.GetLength() == 0, error = kErrorParse);
562 
563         VerifyOrExit(tlv.GetSize() >= minTlvSize, error = kErrorParse);
564 
565         // Read `subTlv` with its `minTlvSize`, followed by the Type IDs.
566         SuccessOrExit(error = aMessage.Read(offset, subTlv, minTlvSize));
567         SuccessOrExit(error = ReadTypeIdsFromMessage(aMessage, offset + minTlvSize, tlvEndOffset, metrics));
568     }
569 
570     if (fwdProbingSubTlv.GetLength() != 0)
571     {
572         aStatus = ConfigureForwardTrackingSeries(fwdProbingSubTlv.GetSeriesId(), fwdProbingSubTlv.GetSeriesFlagsMask(),
573                                                  metrics, aNeighbor);
574     }
575 
576     if (enhAckConfigSubTlv.GetLength() != 0)
577     {
578         aStatus = ConfigureEnhAckProbing(enhAckConfigSubTlv.GetEnhAckFlags(), metrics, aNeighbor);
579     }
580 
581 exit:
582     return error;
583 }
584 
HandleLinkProbe(const Message & aMessage,uint8_t & aSeriesId)585 Error Subject::HandleLinkProbe(const Message &aMessage, uint8_t &aSeriesId)
586 {
587     Error    error = kErrorNone;
588     uint16_t offset;
589     uint16_t length;
590 
591     SuccessOrExit(error = Tlv::FindTlvValueOffset(aMessage, Mle::Tlv::Type::kLinkProbe, offset, length));
592     VerifyOrExit(length >= sizeof(aSeriesId), error = kErrorParse);
593     error = aMessage.Read(offset, aSeriesId);
594 
595 exit:
596     return error;
597 }
598 
AppendReportSubTlvToMessage(Message & aMessage,const MetricsValues & aValues)599 Error Subject::AppendReportSubTlvToMessage(Message &aMessage, const MetricsValues &aValues)
600 {
601     Error        error = kErrorNone;
602     ReportSubTlv reportTlv;
603 
604     reportTlv.Init();
605 
606     if (aValues.mMetrics.mPduCount)
607     {
608         reportTlv.SetMetricsTypeId(TypeId::kPdu);
609         reportTlv.SetMetricsValue32(aValues.mPduCountValue);
610         SuccessOrExit(error = reportTlv.AppendTo(aMessage));
611     }
612 
613     if (aValues.mMetrics.mLqi)
614     {
615         reportTlv.SetMetricsTypeId(TypeId::kLqi);
616         reportTlv.SetMetricsValue8(aValues.mLqiValue);
617         SuccessOrExit(error = reportTlv.AppendTo(aMessage));
618     }
619 
620     if (aValues.mMetrics.mLinkMargin)
621     {
622         reportTlv.SetMetricsTypeId(TypeId::kLinkMargin);
623         reportTlv.SetMetricsValue8(ScaleLinkMarginToRawValue(aValues.mLinkMarginValue));
624         SuccessOrExit(error = reportTlv.AppendTo(aMessage));
625     }
626 
627     if (aValues.mMetrics.mRssi)
628     {
629         reportTlv.SetMetricsTypeId(TypeId::kRssi);
630         reportTlv.SetMetricsValue8(ScaleRssiToRawValue(aValues.mRssiValue));
631         SuccessOrExit(error = reportTlv.AppendTo(aMessage));
632     }
633 
634 exit:
635     return error;
636 }
637 
Free(SeriesInfo & aSeriesInfo)638 void Subject::Free(SeriesInfo &aSeriesInfo) { mSeriesInfoPool.Free(aSeriesInfo); }
639 
ReadTypeIdsFromMessage(const Message & aMessage,uint16_t aStartOffset,uint16_t aEndOffset,Metrics & aMetrics)640 Error Subject::ReadTypeIdsFromMessage(const Message &aMessage,
641                                       uint16_t       aStartOffset,
642                                       uint16_t       aEndOffset,
643                                       Metrics       &aMetrics)
644 {
645     Error error = kErrorNone;
646 
647     aMetrics.Clear();
648 
649     for (uint16_t offset = aStartOffset; offset < aEndOffset; offset++)
650     {
651         uint8_t typeId;
652 
653         SuccessOrExit(aMessage.Read(offset, typeId));
654 
655         switch (typeId)
656         {
657         case TypeId::kPdu:
658             VerifyOrExit(!aMetrics.mPduCount, error = kErrorParse);
659             aMetrics.mPduCount = true;
660             break;
661 
662         case TypeId::kLqi:
663             VerifyOrExit(!aMetrics.mLqi, error = kErrorParse);
664             aMetrics.mLqi = true;
665             break;
666 
667         case TypeId::kLinkMargin:
668             VerifyOrExit(!aMetrics.mLinkMargin, error = kErrorParse);
669             aMetrics.mLinkMargin = true;
670             break;
671 
672         case TypeId::kRssi:
673             VerifyOrExit(!aMetrics.mRssi, error = kErrorParse);
674             aMetrics.mRssi = true;
675             break;
676 
677         default:
678             if (TypeId::IsExtended(typeId))
679             {
680                 offset += sizeof(uint8_t); // Skip the additional second byte.
681             }
682             else
683             {
684                 aMetrics.mReserved = true;
685             }
686             break;
687         }
688     }
689 
690 exit:
691     return error;
692 }
693 
ConfigureForwardTrackingSeries(uint8_t aSeriesId,uint8_t aSeriesFlagsMask,const Metrics & aMetrics,Neighbor & aNeighbor)694 Status Subject::ConfigureForwardTrackingSeries(uint8_t        aSeriesId,
695                                                uint8_t        aSeriesFlagsMask,
696                                                const Metrics &aMetrics,
697                                                Neighbor      &aNeighbor)
698 {
699     Status status = kStatusSuccess;
700 
701     VerifyOrExit(0 < aSeriesId, status = kStatusOtherError);
702 
703     if (aSeriesFlagsMask == 0) // Remove the series
704     {
705         if (aSeriesId == kSeriesIdAllSeries) // Remove all
706         {
707             aNeighbor.RemoveAllForwardTrackingSeriesInfo();
708         }
709         else
710         {
711             SeriesInfo *seriesInfo = aNeighbor.RemoveForwardTrackingSeriesInfo(aSeriesId);
712             VerifyOrExit(seriesInfo != nullptr, status = kStatusSeriesIdNotRecognized);
713             mSeriesInfoPool.Free(*seriesInfo);
714         }
715     }
716     else // Add a new series
717     {
718         SeriesInfo *seriesInfo = aNeighbor.GetForwardTrackingSeriesInfo(aSeriesId);
719         VerifyOrExit(seriesInfo == nullptr, status = kStatusSeriesIdAlreadyRegistered);
720         seriesInfo = mSeriesInfoPool.Allocate();
721         VerifyOrExit(seriesInfo != nullptr, status = kStatusCannotSupportNewSeries);
722 
723         seriesInfo->Init(aSeriesId, aSeriesFlagsMask, aMetrics);
724 
725         aNeighbor.AddForwardTrackingSeriesInfo(*seriesInfo);
726     }
727 
728 exit:
729     return status;
730 }
731 
ConfigureEnhAckProbing(uint8_t aEnhAckFlags,const Metrics & aMetrics,Neighbor & aNeighbor)732 Status Subject::ConfigureEnhAckProbing(uint8_t aEnhAckFlags, const Metrics &aMetrics, Neighbor &aNeighbor)
733 {
734     Status status = kStatusSuccess;
735     Error  error  = kErrorNone;
736 
737     VerifyOrExit(!aMetrics.mReserved, status = kStatusOtherError);
738 
739     if (aEnhAckFlags == kEnhAckRegister)
740     {
741         VerifyOrExit(!aMetrics.mPduCount, status = kStatusOtherError);
742         VerifyOrExit(aMetrics.mLqi || aMetrics.mLinkMargin || aMetrics.mRssi, status = kStatusOtherError);
743         VerifyOrExit(!(aMetrics.mLqi && aMetrics.mLinkMargin && aMetrics.mRssi), status = kStatusOtherError);
744 
745         error = Get<Radio>().ConfigureEnhAckProbing(aMetrics, aNeighbor.GetRloc16(), aNeighbor.GetExtAddress());
746     }
747     else if (aEnhAckFlags == kEnhAckClear)
748     {
749         VerifyOrExit(!aMetrics.mLqi && !aMetrics.mLinkMargin && !aMetrics.mRssi, status = kStatusOtherError);
750         error = Get<Radio>().ConfigureEnhAckProbing(aMetrics, aNeighbor.GetRloc16(), aNeighbor.GetExtAddress());
751     }
752     else
753     {
754         status = kStatusOtherError;
755     }
756 
757     VerifyOrExit(error == kErrorNone, status = kStatusOtherError);
758 
759 exit:
760     return status;
761 }
762 
763 #endif // OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE
764 
ScaleLinkMarginToRawValue(uint8_t aLinkMargin)765 uint8_t ScaleLinkMarginToRawValue(uint8_t aLinkMargin)
766 {
767     // Linearly scale Link Margin from [0, 130] to [0, 255].
768     // `kMaxLinkMargin = 130`.
769 
770     uint16_t value;
771 
772     value = Min(aLinkMargin, kMaxLinkMargin);
773     value = value * NumericLimits<uint8_t>::kMax;
774     value = DivideAndRoundToClosest<uint16_t>(value, kMaxLinkMargin);
775 
776     return static_cast<uint8_t>(value);
777 }
778 
ScaleRawValueToLinkMargin(uint8_t aRawValue)779 uint8_t ScaleRawValueToLinkMargin(uint8_t aRawValue)
780 {
781     // Scale back raw value of [0, 255] to Link Margin from [0, 130].
782 
783     uint16_t value = aRawValue;
784 
785     value = value * kMaxLinkMargin;
786     value = DivideAndRoundToClosest<uint16_t>(value, NumericLimits<uint8_t>::kMax);
787     return static_cast<uint8_t>(value);
788 }
789 
ScaleRssiToRawValue(int8_t aRssi)790 uint8_t ScaleRssiToRawValue(int8_t aRssi)
791 {
792     // Linearly scale RSSI from [-130, 0] to [0, 255].
793     // `kMinRssi = -130`, `kMaxRssi = 0`.
794 
795     int32_t value = aRssi;
796 
797     value = Clamp(value, kMinRssi, kMaxRssi) - kMinRssi;
798     value = value * NumericLimits<uint8_t>::kMax;
799     value = DivideAndRoundToClosest<int32_t>(value, kMaxRssi - kMinRssi);
800 
801     return static_cast<uint8_t>(value);
802 }
803 
ScaleRawValueToRssi(uint8_t aRawValue)804 int8_t ScaleRawValueToRssi(uint8_t aRawValue)
805 {
806     int32_t value = aRawValue;
807 
808     value = value * (kMaxRssi - kMinRssi);
809     value = DivideAndRoundToClosest<int32_t>(value, NumericLimits<uint8_t>::kMax);
810     value += kMinRssi;
811 
812     return ClampToInt8(value);
813 }
814 
815 } // namespace LinkMetrics
816 } // namespace ot
817 
818 #endif // OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE || OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE
819