1 /******************************************************************************
2  *
3  *  Copyright 2016 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include "metrics.h"
20 
21 #include <base/base64.h>
22 #include <bluetooth/log.h>
23 #include <frameworks/proto_logging/stats/enums/bluetooth/le/enums.pb.h>
24 #include <include/hardware/bt_av.h>
25 #include <statslog_bt.h>
26 #include <unistd.h>
27 
28 #include <algorithm>
29 #include <array>
30 #include <cerrno>
31 #include <cstdint>
32 #include <cstring>
33 #include <memory>
34 #include <mutex>
35 
36 #include "address_obfuscator.h"
37 #include "bluetooth/metrics/bluetooth.pb.h"
38 #include "hci/address.h"
39 #include "internal_include/bt_trace.h"
40 #include "leaky_bonded_queue.h"
41 #include "metric_id_allocator.h"
42 #include "metrics/metrics_state.h"
43 #include "os/metrics.h"
44 #include "osi/include/osi.h"
45 #include "time_util.h"
46 #include "types/raw_address.h"
47 #include "main/shim/metric_id_api.h"
48 
49 namespace fmt {
50 template <>
51 struct formatter<android::bluetooth::DirectionEnum>
52     : enum_formatter<android::bluetooth::DirectionEnum> {};
53 template <>
54 struct formatter<android::bluetooth::SocketConnectionstateEnum>
55     : enum_formatter<android::bluetooth::SocketConnectionstateEnum> {};
56 template <>
57 struct formatter<android::bluetooth::SocketRoleEnum>
58     : enum_formatter<android::bluetooth::SocketRoleEnum> {};
59 template <>
60 struct formatter<android::bluetooth::AddressTypeEnum>
61     : enum_formatter<android::bluetooth::AddressTypeEnum> {};
62 template <>
63 struct formatter<android::bluetooth::DeviceInfoSrcEnum>
64     : enum_formatter<android::bluetooth::DeviceInfoSrcEnum> {};
65 }  // namespace fmt
66 
67 namespace bluetooth {
68 namespace common {
69 
70 using bluetooth::metrics::BluetoothMetricsProto::A2DPSession;
71 using bluetooth::metrics::BluetoothMetricsProto::A2dpSourceCodec;
72 using bluetooth::metrics::BluetoothMetricsProto::BluetoothLog;
73 using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession;
74 using bluetooth::metrics::BluetoothMetricsProto::
75     BluetoothSession_ConnectionTechnologyType;
76 using bluetooth::metrics::BluetoothMetricsProto::
77     BluetoothSession_DisconnectReasonType;
78 using bluetooth::metrics::BluetoothMetricsProto::DeviceInfo;
79 using bluetooth::metrics::BluetoothMetricsProto::DeviceInfo_DeviceType;
80 using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileConnectionStats;
81 using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileType;
82 using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileType_ARRAYSIZE;
83 using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileType_IsValid;
84 using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileType_MAX;
85 using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileType_MIN;
86 using bluetooth::metrics::BluetoothMetricsProto::PairEvent;
87 using bluetooth::metrics::BluetoothMetricsProto::ScanEvent;
88 using bluetooth::metrics::BluetoothMetricsProto::ScanEvent_ScanEventType;
89 using bluetooth::metrics::BluetoothMetricsProto::ScanEvent_ScanTechnologyType;
90 using bluetooth::metrics::BluetoothMetricsProto::WakeEvent;
91 using bluetooth::metrics::BluetoothMetricsProto::WakeEvent_WakeEventType;
92 using bluetooth::hci::Address;
93 
combine_averages(float avg_a,int64_t ct_a,float avg_b,int64_t ct_b)94 static float combine_averages(float avg_a, int64_t ct_a, float avg_b,
95                               int64_t ct_b) {
96   if (ct_a > 0 && ct_b > 0) {
97     return (avg_a * ct_a + avg_b * ct_b) / (ct_a + ct_b);
98   } else if (ct_b > 0) {
99     return avg_b;
100   } else {
101     return avg_a;
102   }
103 }
104 
combine_averages(int32_t avg_a,int64_t ct_a,int32_t avg_b,int64_t ct_b)105 static int32_t combine_averages(int32_t avg_a, int64_t ct_a, int32_t avg_b,
106                                 int64_t ct_b) {
107   if (ct_a > 0 && ct_b > 0) {
108     return (avg_a * ct_a + avg_b * ct_b) / (ct_a + ct_b);
109   } else if (ct_b > 0) {
110     return avg_b;
111   } else {
112     return avg_a;
113   }
114 }
115 
Update(const A2dpSessionMetrics & metrics)116 void A2dpSessionMetrics::Update(const A2dpSessionMetrics& metrics) {
117   if (metrics.audio_duration_ms >= 0) {
118     audio_duration_ms = std::max(static_cast<int64_t>(0), audio_duration_ms);
119     audio_duration_ms += metrics.audio_duration_ms;
120   }
121   if (metrics.media_timer_min_ms >= 0) {
122     if (media_timer_min_ms < 0) {
123       media_timer_min_ms = metrics.media_timer_min_ms;
124     } else {
125       media_timer_min_ms =
126           std::min(media_timer_min_ms, metrics.media_timer_min_ms);
127     }
128   }
129   if (metrics.media_timer_max_ms >= 0) {
130     media_timer_max_ms =
131         std::max(media_timer_max_ms, metrics.media_timer_max_ms);
132   }
133   if (metrics.media_timer_avg_ms >= 0 && metrics.total_scheduling_count >= 0) {
134     if (media_timer_avg_ms < 0 || total_scheduling_count < 0) {
135       media_timer_avg_ms = metrics.media_timer_avg_ms;
136       total_scheduling_count = metrics.total_scheduling_count;
137     } else {
138       media_timer_avg_ms = combine_averages(
139           media_timer_avg_ms, total_scheduling_count,
140           metrics.media_timer_avg_ms, metrics.total_scheduling_count);
141       total_scheduling_count += metrics.total_scheduling_count;
142     }
143   }
144   if (metrics.buffer_overruns_max_count >= 0) {
145     buffer_overruns_max_count =
146         std::max(buffer_overruns_max_count, metrics.buffer_overruns_max_count);
147   }
148   if (metrics.buffer_overruns_total >= 0) {
149     buffer_overruns_total =
150         std::max(static_cast<int32_t>(0), buffer_overruns_total);
151     buffer_overruns_total += metrics.buffer_overruns_total;
152   }
153   if (metrics.buffer_underruns_average >= 0 &&
154       metrics.buffer_underruns_count >= 0) {
155     if (buffer_underruns_average < 0 || buffer_underruns_count < 0) {
156       buffer_underruns_average = metrics.buffer_underruns_average;
157       buffer_underruns_count = metrics.buffer_underruns_count;
158     } else {
159       buffer_underruns_average = combine_averages(
160           buffer_underruns_average, buffer_underruns_count,
161           metrics.buffer_underruns_average, metrics.buffer_underruns_count);
162       buffer_underruns_count += metrics.buffer_underruns_count;
163     }
164   }
165   if (codec_index < 0) {
166     codec_index = metrics.codec_index;
167   }
168   if (!is_a2dp_offload) {
169     is_a2dp_offload = metrics.is_a2dp_offload;
170   }
171 }
172 
operator ==(const A2dpSessionMetrics & rhs) const173 bool A2dpSessionMetrics::operator==(const A2dpSessionMetrics& rhs) const {
174   return audio_duration_ms == rhs.audio_duration_ms &&
175          media_timer_min_ms == rhs.media_timer_min_ms &&
176          media_timer_max_ms == rhs.media_timer_max_ms &&
177          media_timer_avg_ms == rhs.media_timer_avg_ms &&
178          total_scheduling_count == rhs.total_scheduling_count &&
179          buffer_overruns_max_count == rhs.buffer_overruns_max_count &&
180          buffer_overruns_total == rhs.buffer_overruns_total &&
181          buffer_underruns_average == rhs.buffer_underruns_average &&
182          buffer_underruns_count == rhs.buffer_underruns_count &&
183          codec_index == rhs.codec_index &&
184          is_a2dp_offload == rhs.is_a2dp_offload;
185 }
186 
get_device_type(device_type_t type)187 static DeviceInfo_DeviceType get_device_type(device_type_t type) {
188   switch (type) {
189     case DEVICE_TYPE_BREDR:
190       return DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR;
191     case DEVICE_TYPE_LE:
192       return DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_LE;
193     case DEVICE_TYPE_DUMO:
194       return DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_DUMO;
195     case DEVICE_TYPE_UNKNOWN:
196     default:
197       return DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_UNKNOWN;
198   }
199 }
200 
get_connection_tech_type(connection_tech_t type)201 static BluetoothSession_ConnectionTechnologyType get_connection_tech_type(
202     connection_tech_t type) {
203   switch (type) {
204     case CONNECTION_TECHNOLOGY_TYPE_LE:
205       return BluetoothSession_ConnectionTechnologyType::
206           BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE;
207     case CONNECTION_TECHNOLOGY_TYPE_BREDR:
208       return BluetoothSession_ConnectionTechnologyType::
209           BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR;
210     case CONNECTION_TECHNOLOGY_TYPE_UNKNOWN:
211     default:
212       return BluetoothSession_ConnectionTechnologyType::
213           BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_UNKNOWN;
214   }
215 }
216 
get_scan_tech_type(scan_tech_t type)217 static ScanEvent_ScanTechnologyType get_scan_tech_type(scan_tech_t type) {
218   switch (type) {
219     case SCAN_TECH_TYPE_LE:
220       return ScanEvent_ScanTechnologyType::
221           ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_LE;
222     case SCAN_TECH_TYPE_BREDR:
223       return ScanEvent_ScanTechnologyType::
224           ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BREDR;
225     case SCAN_TECH_TYPE_BOTH:
226       return ScanEvent_ScanTechnologyType::
227           ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BOTH;
228     case SCAN_TYPE_UNKNOWN:
229     default:
230       return ScanEvent_ScanTechnologyType::
231           ScanEvent_ScanTechnologyType_SCAN_TYPE_UNKNOWN;
232   }
233 }
234 
get_wake_event_type(wake_event_type_t type)235 static WakeEvent_WakeEventType get_wake_event_type(wake_event_type_t type) {
236   switch (type) {
237     case WAKE_EVENT_ACQUIRED:
238       return WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED;
239     case WAKE_EVENT_RELEASED:
240       return WakeEvent_WakeEventType::WakeEvent_WakeEventType_RELEASED;
241     case WAKE_EVENT_UNKNOWN:
242     default:
243       return WakeEvent_WakeEventType::WakeEvent_WakeEventType_UNKNOWN;
244   }
245 }
246 
get_disconnect_reason_type(disconnect_reason_t type)247 static BluetoothSession_DisconnectReasonType get_disconnect_reason_type(
248     disconnect_reason_t type) {
249   switch (type) {
250     case DISCONNECT_REASON_METRICS_DUMP:
251       return BluetoothSession_DisconnectReasonType::
252           BluetoothSession_DisconnectReasonType_METRICS_DUMP;
253     case DISCONNECT_REASON_NEXT_START_WITHOUT_END_PREVIOUS:
254       return BluetoothSession_DisconnectReasonType::
255           BluetoothSession_DisconnectReasonType_NEXT_START_WITHOUT_END_PREVIOUS;
256     case DISCONNECT_REASON_UNKNOWN:
257     default:
258       return BluetoothSession_DisconnectReasonType::
259           BluetoothSession_DisconnectReasonType_UNKNOWN;
260   }
261 }
262 
get_a2dp_source_codec(int64_t codec_index)263 static A2dpSourceCodec get_a2dp_source_codec(int64_t codec_index) {
264   switch (codec_index) {
265     case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC:
266       return A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC;
267     case BTAV_A2DP_CODEC_INDEX_SOURCE_AAC:
268       return A2dpSourceCodec::A2DP_SOURCE_CODEC_AAC;
269     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX:
270       return A2dpSourceCodec::A2DP_SOURCE_CODEC_APTX;
271     case BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD:
272       return A2dpSourceCodec::A2DP_SOURCE_CODEC_APTX_HD;
273     case BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC:
274       return A2dpSourceCodec::A2DP_SOURCE_CODEC_LDAC;
275     default:
276       return A2dpSourceCodec::A2DP_SOURCE_CODEC_UNKNOWN;
277   }
278 }
279 
280 struct BluetoothMetricsLogger::impl {
implbluetooth::common::BluetoothMetricsLogger::impl281   impl(size_t max_bluetooth_session, size_t max_pair_event,
282        size_t max_wake_event, size_t max_scan_event)
283       : bt_session_queue_(
284             new LeakyBondedQueue<BluetoothSession>(max_bluetooth_session)),
285         pair_event_queue_(new LeakyBondedQueue<PairEvent>(max_pair_event)),
286         wake_event_queue_(new LeakyBondedQueue<WakeEvent>(max_wake_event)),
287         scan_event_queue_(new LeakyBondedQueue<ScanEvent>(max_scan_event)) {
288     bluetooth_log_ = BluetoothLog::default_instance().New();
289     headset_profile_connection_counts_.fill(0);
290     bluetooth_session_ = nullptr;
291     bluetooth_session_start_time_ms_ = 0;
292     a2dp_session_metrics_ = A2dpSessionMetrics();
293   }
294 
295   /* Bluetooth log lock protected */
296   BluetoothLog* bluetooth_log_;
297   std::array<int, HeadsetProfileType_ARRAYSIZE>
298       headset_profile_connection_counts_;
299   std::recursive_mutex bluetooth_log_lock_;
300   /* End Bluetooth log lock protected */
301   /* Bluetooth session lock protected */
302   BluetoothSession* bluetooth_session_;
303   uint64_t bluetooth_session_start_time_ms_;
304   A2dpSessionMetrics a2dp_session_metrics_;
305   std::recursive_mutex bluetooth_session_lock_;
306   /* End bluetooth session lock protected */
307   std::unique_ptr<LeakyBondedQueue<BluetoothSession>> bt_session_queue_;
308   std::unique_ptr<LeakyBondedQueue<PairEvent>> pair_event_queue_;
309   std::unique_ptr<LeakyBondedQueue<WakeEvent>> wake_event_queue_;
310   std::unique_ptr<LeakyBondedQueue<ScanEvent>> scan_event_queue_;
311 };
312 
BluetoothMetricsLogger()313 BluetoothMetricsLogger::BluetoothMetricsLogger()
314     : pimpl_(new impl(kMaxNumBluetoothSession, kMaxNumPairEvent,
315                       kMaxNumWakeEvent, kMaxNumScanEvent)) {}
316 
LogPairEvent(uint32_t disconnect_reason,uint64_t timestamp_ms,uint32_t device_class,device_type_t device_type)317 void BluetoothMetricsLogger::LogPairEvent(uint32_t disconnect_reason,
318                                           uint64_t timestamp_ms,
319                                           uint32_t device_class,
320                                           device_type_t device_type) {
321   PairEvent* event = new PairEvent();
322   DeviceInfo* info = event->mutable_device_paired_with();
323   info->set_device_class(device_class);
324   info->set_device_type(get_device_type(device_type));
325   event->set_disconnect_reason(disconnect_reason);
326   event->set_event_time_millis(timestamp_ms);
327   pimpl_->pair_event_queue_->Enqueue(event);
328   {
329     std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
330     pimpl_->bluetooth_log_->set_num_pair_event(
331         pimpl_->bluetooth_log_->num_pair_event() + 1);
332   }
333 }
334 
LogWakeEvent(wake_event_type_t type,const std::string & requestor,const std::string & name,uint64_t timestamp_ms)335 void BluetoothMetricsLogger::LogWakeEvent(wake_event_type_t type,
336                                           const std::string& requestor,
337                                           const std::string& name,
338                                           uint64_t timestamp_ms) {
339   WakeEvent* event = new WakeEvent();
340   event->set_wake_event_type(get_wake_event_type(type));
341   event->set_requestor(requestor);
342   event->set_name(name);
343   event->set_event_time_millis(timestamp_ms);
344   pimpl_->wake_event_queue_->Enqueue(event);
345   {
346     std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
347     pimpl_->bluetooth_log_->set_num_wake_event(
348         pimpl_->bluetooth_log_->num_wake_event() + 1);
349   }
350 }
351 
LogScanEvent(bool start,const std::string & initator,scan_tech_t type,uint32_t results,uint64_t timestamp_ms)352 void BluetoothMetricsLogger::LogScanEvent(bool start,
353                                           const std::string& initator,
354                                           scan_tech_t type, uint32_t results,
355                                           uint64_t timestamp_ms) {
356   ScanEvent* event = new ScanEvent();
357   if (start) {
358     event->set_scan_event_type(ScanEvent::SCAN_EVENT_START);
359   } else {
360     event->set_scan_event_type(ScanEvent::SCAN_EVENT_STOP);
361   }
362   event->set_initiator(initator);
363   event->set_scan_technology_type(get_scan_tech_type(type));
364   event->set_number_results(results);
365   event->set_event_time_millis(timestamp_ms);
366   pimpl_->scan_event_queue_->Enqueue(event);
367   {
368     std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
369     pimpl_->bluetooth_log_->set_num_scan_event(
370         pimpl_->bluetooth_log_->num_scan_event() + 1);
371   }
372 }
373 
LogBluetoothSessionStart(connection_tech_t connection_tech_type,uint64_t timestamp_ms)374 void BluetoothMetricsLogger::LogBluetoothSessionStart(
375     connection_tech_t connection_tech_type, uint64_t timestamp_ms) {
376   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_session_lock_);
377   if (pimpl_->bluetooth_session_ != nullptr) {
378     LogBluetoothSessionEnd(DISCONNECT_REASON_NEXT_START_WITHOUT_END_PREVIOUS,
379                            0);
380   }
381   if (timestamp_ms == 0) {
382     timestamp_ms = bluetooth::common::time_get_os_boottime_ms();
383   }
384   pimpl_->bluetooth_session_start_time_ms_ = timestamp_ms;
385   pimpl_->bluetooth_session_ = new BluetoothSession();
386   pimpl_->bluetooth_session_->set_connection_technology_type(
387       get_connection_tech_type(connection_tech_type));
388 }
389 
LogBluetoothSessionEnd(disconnect_reason_t disconnect_reason,uint64_t timestamp_ms)390 void BluetoothMetricsLogger::LogBluetoothSessionEnd(
391     disconnect_reason_t disconnect_reason, uint64_t timestamp_ms) {
392   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_session_lock_);
393   if (pimpl_->bluetooth_session_ == nullptr) {
394     return;
395   }
396   if (timestamp_ms == 0) {
397     timestamp_ms = bluetooth::common::time_get_os_boottime_ms();
398   }
399   int64_t session_duration_sec =
400       (timestamp_ms - pimpl_->bluetooth_session_start_time_ms_) / 1000;
401   pimpl_->bluetooth_session_->set_session_duration_sec(session_duration_sec);
402   pimpl_->bluetooth_session_->set_disconnect_reason_type(
403       get_disconnect_reason_type(disconnect_reason));
404   pimpl_->bt_session_queue_->Enqueue(pimpl_->bluetooth_session_);
405   pimpl_->bluetooth_session_ = nullptr;
406   pimpl_->a2dp_session_metrics_ = A2dpSessionMetrics();
407   {
408     std::lock_guard<std::recursive_mutex> log_lock(pimpl_->bluetooth_log_lock_);
409     pimpl_->bluetooth_log_->set_num_bluetooth_session(
410         pimpl_->bluetooth_log_->num_bluetooth_session() + 1);
411   }
412 }
413 
LogBluetoothSessionDeviceInfo(uint32_t device_class,device_type_t device_type)414 void BluetoothMetricsLogger::LogBluetoothSessionDeviceInfo(
415     uint32_t device_class, device_type_t device_type) {
416   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_session_lock_);
417   if (pimpl_->bluetooth_session_ == nullptr) {
418     LogBluetoothSessionStart(CONNECTION_TECHNOLOGY_TYPE_UNKNOWN, 0);
419   }
420   DeviceInfo* info = pimpl_->bluetooth_session_->mutable_device_connected_to();
421   info->set_device_class(device_class);
422   info->set_device_type(DeviceInfo::DEVICE_TYPE_BREDR);
423 }
424 
LogA2dpSession(const A2dpSessionMetrics & a2dp_session_metrics)425 void BluetoothMetricsLogger::LogA2dpSession(
426     const A2dpSessionMetrics& a2dp_session_metrics) {
427   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_session_lock_);
428   if (pimpl_->bluetooth_session_ == nullptr) {
429     // When no bluetooth session exist, create one on system's behalf
430     // Set connection type: for A2DP it is always BR/EDR
431     LogBluetoothSessionStart(CONNECTION_TECHNOLOGY_TYPE_BREDR, 0);
432     LogBluetoothSessionDeviceInfo(BTM_COD_MAJOR_AUDIO, DEVICE_TYPE_BREDR);
433   }
434   // Accumulate metrics
435   pimpl_->a2dp_session_metrics_.Update(a2dp_session_metrics);
436   // Get or allocate new A2DP session object
437   A2DPSession* a2dp_session =
438       pimpl_->bluetooth_session_->mutable_a2dp_session();
439   a2dp_session->set_audio_duration_millis(
440       pimpl_->a2dp_session_metrics_.audio_duration_ms);
441   a2dp_session->set_media_timer_min_millis(
442       pimpl_->a2dp_session_metrics_.media_timer_min_ms);
443   a2dp_session->set_media_timer_max_millis(
444       pimpl_->a2dp_session_metrics_.media_timer_max_ms);
445   a2dp_session->set_media_timer_avg_millis(
446       pimpl_->a2dp_session_metrics_.media_timer_avg_ms);
447   a2dp_session->set_buffer_overruns_max_count(
448       pimpl_->a2dp_session_metrics_.buffer_overruns_max_count);
449   a2dp_session->set_buffer_overruns_total(
450       pimpl_->a2dp_session_metrics_.buffer_overruns_total);
451   a2dp_session->set_buffer_underruns_average(
452       pimpl_->a2dp_session_metrics_.buffer_underruns_average);
453   a2dp_session->set_buffer_underruns_count(
454       pimpl_->a2dp_session_metrics_.buffer_underruns_count);
455   a2dp_session->set_source_codec(
456       get_a2dp_source_codec(pimpl_->a2dp_session_metrics_.codec_index));
457   a2dp_session->set_is_a2dp_offload(
458       pimpl_->a2dp_session_metrics_.is_a2dp_offload);
459 }
460 
LogHeadsetProfileRfcConnection(tBTA_SERVICE_ID service_id)461 void BluetoothMetricsLogger::LogHeadsetProfileRfcConnection(
462     tBTA_SERVICE_ID service_id) {
463   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
464   switch (service_id) {
465     case BTA_HSP_SERVICE_ID:
466       pimpl_->headset_profile_connection_counts_[HeadsetProfileType::HSP]++;
467       break;
468     case BTA_HFP_SERVICE_ID:
469       pimpl_->headset_profile_connection_counts_[HeadsetProfileType::HFP]++;
470       break;
471     default:
472       pimpl_->headset_profile_connection_counts_
473           [HeadsetProfileType::HEADSET_PROFILE_UNKNOWN]++;
474       break;
475   }
476   return;
477 }
478 
WriteString(std::string * serialized)479 void BluetoothMetricsLogger::WriteString(std::string* serialized) {
480   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
481   log::info("building metrics");
482   Build();
483   log::info("serializing metrics");
484   if (!pimpl_->bluetooth_log_->SerializeToString(serialized)) {
485     log::error("error serializing metrics");
486   }
487   // Always clean up log objects
488   pimpl_->bluetooth_log_->Clear();
489 }
490 
WriteBase64String(std::string * serialized)491 void BluetoothMetricsLogger::WriteBase64String(std::string* serialized) {
492   this->WriteString(serialized);
493   base::Base64Encode(*serialized, serialized);
494 }
495 
WriteBase64(int fd)496 void BluetoothMetricsLogger::WriteBase64(int fd) {
497   std::string protoBase64;
498   this->WriteBase64String(&protoBase64);
499   ssize_t ret;
500   OSI_NO_INTR(ret = write(fd, protoBase64.c_str(), protoBase64.size()));
501   if (ret == -1) {
502     log::error("error writing to dumpsys fd: {} ({})", strerror(errno), errno);
503   }
504 }
505 
CutoffSession()506 void BluetoothMetricsLogger::CutoffSession() {
507   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_session_lock_);
508   if (pimpl_->bluetooth_session_ != nullptr) {
509     BluetoothSession* new_bt_session =
510         new BluetoothSession(*pimpl_->bluetooth_session_);
511     new_bt_session->clear_a2dp_session();
512     new_bt_session->clear_rfcomm_session();
513     LogBluetoothSessionEnd(DISCONNECT_REASON_METRICS_DUMP, 0);
514     pimpl_->bluetooth_session_ = new_bt_session;
515     pimpl_->bluetooth_session_start_time_ms_ =
516         bluetooth::common::time_get_os_boottime_ms();
517     pimpl_->a2dp_session_metrics_ = A2dpSessionMetrics();
518   }
519 }
520 
Build()521 void BluetoothMetricsLogger::Build() {
522   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
523   CutoffSession();
524   BluetoothLog* bluetooth_log = pimpl_->bluetooth_log_;
525   while (!pimpl_->bt_session_queue_->Empty() &&
526          static_cast<size_t>(bluetooth_log->session_size()) <=
527              pimpl_->bt_session_queue_->Capacity()) {
528     bluetooth_log->mutable_session()->AddAllocated(
529         pimpl_->bt_session_queue_->Dequeue());
530   }
531   while (!pimpl_->pair_event_queue_->Empty() &&
532          static_cast<size_t>(bluetooth_log->pair_event_size()) <=
533              pimpl_->pair_event_queue_->Capacity()) {
534     bluetooth_log->mutable_pair_event()->AddAllocated(
535         pimpl_->pair_event_queue_->Dequeue());
536   }
537   while (!pimpl_->scan_event_queue_->Empty() &&
538          static_cast<size_t>(bluetooth_log->scan_event_size()) <=
539              pimpl_->scan_event_queue_->Capacity()) {
540     bluetooth_log->mutable_scan_event()->AddAllocated(
541         pimpl_->scan_event_queue_->Dequeue());
542   }
543   while (!pimpl_->wake_event_queue_->Empty() &&
544          static_cast<size_t>(bluetooth_log->wake_event_size()) <=
545              pimpl_->wake_event_queue_->Capacity()) {
546     bluetooth_log->mutable_wake_event()->AddAllocated(
547         pimpl_->wake_event_queue_->Dequeue());
548   }
549   while (!pimpl_->bt_session_queue_->Empty() &&
550          static_cast<size_t>(bluetooth_log->wake_event_size()) <=
551              pimpl_->wake_event_queue_->Capacity()) {
552     bluetooth_log->mutable_wake_event()->AddAllocated(
553         pimpl_->wake_event_queue_->Dequeue());
554   }
555   for (size_t i = 0; i < HeadsetProfileType_ARRAYSIZE; ++i) {
556     int num_times_connected = pimpl_->headset_profile_connection_counts_[i];
557     if (HeadsetProfileType_IsValid(i) && num_times_connected > 0) {
558       HeadsetProfileConnectionStats* headset_profile_connection_stats =
559           bluetooth_log->add_headset_profile_connection_stats();
560       // Able to static_cast because HeadsetProfileType_IsValid(i) is true
561       headset_profile_connection_stats->set_headset_profile_type(
562           static_cast<HeadsetProfileType>(i));
563       headset_profile_connection_stats->set_num_times_connected(
564           num_times_connected);
565     }
566   }
567   pimpl_->headset_profile_connection_counts_.fill(0);
568 }
569 
ResetSession()570 void BluetoothMetricsLogger::ResetSession() {
571   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_session_lock_);
572   if (pimpl_->bluetooth_session_ != nullptr) {
573     delete pimpl_->bluetooth_session_;
574     pimpl_->bluetooth_session_ = nullptr;
575   }
576   pimpl_->bluetooth_session_start_time_ms_ = 0;
577   pimpl_->a2dp_session_metrics_ = A2dpSessionMetrics();
578 }
579 
ResetLog()580 void BluetoothMetricsLogger::ResetLog() {
581   std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
582   pimpl_->bluetooth_log_->Clear();
583 }
584 
Reset()585 void BluetoothMetricsLogger::Reset() {
586   ResetSession();
587   ResetLog();
588   pimpl_->bt_session_queue_->Clear();
589   pimpl_->pair_event_queue_->Clear();
590   pimpl_->wake_event_queue_->Clear();
591   pimpl_->scan_event_queue_->Clear();
592 }
593 
LogLinkLayerConnectionEvent(const RawAddress * address,uint32_t connection_handle,android::bluetooth::DirectionEnum direction,uint16_t link_type,uint32_t hci_cmd,uint16_t hci_event,uint16_t hci_ble_event,uint16_t cmd_status,uint16_t reason_code)594 void LogLinkLayerConnectionEvent(const RawAddress* address,
595                                  uint32_t connection_handle,
596                                  android::bluetooth::DirectionEnum direction,
597                                  uint16_t link_type, uint32_t hci_cmd,
598                                  uint16_t hci_event, uint16_t hci_ble_event,
599                                  uint16_t cmd_status, uint16_t reason_code) {
600   std::string obfuscated_id;
601   int metric_id = 0;
602   if (address != nullptr) {
603     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(*address);
604     metric_id = MetricIdAllocator::GetInstance().AllocateId(*address);
605   }
606   // nullptr and size 0 represent missing value for obfuscated_id
607   BytesField bytes_field(address != nullptr ? obfuscated_id.c_str() : nullptr,
608                          address != nullptr ? obfuscated_id.size() : 0);
609   int ret =
610       stats_write(BLUETOOTH_LINK_LAYER_CONNECTION_EVENT, bytes_field,
611                   connection_handle, direction, link_type, hci_cmd, hci_event,
612                   hci_ble_event, cmd_status, reason_code, metric_id);
613   if (ret < 0) {
614     log::warn(
615         "failed to log status 0x{:x}, reason 0x{:x} from cmd 0x{:x}, event "
616         "0x{:x}, ble_event 0x{:x} for {}, handle {}, type 0x{:x}, error {}",
617         cmd_status, reason_code, hci_cmd, hci_event, hci_ble_event, *address,
618         connection_handle, link_type, ret);
619   }
620 }
621 
LogHciTimeoutEvent(uint32_t hci_cmd)622 void LogHciTimeoutEvent(uint32_t hci_cmd) {
623   int ret = stats_write(BLUETOOTH_HCI_TIMEOUT_REPORTED,
624                         static_cast<int64_t>(hci_cmd));
625   if (ret < 0) {
626     log::warn("failed for opcode 0x{:x}, error {}", hci_cmd, ret);
627   }
628 }
629 
LogRemoteVersionInfo(uint16_t handle,uint8_t status,uint8_t version,uint16_t manufacturer_name,uint16_t subversion)630 void LogRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version,
631                           uint16_t manufacturer_name, uint16_t subversion) {
632   int ret = stats_write(BLUETOOTH_REMOTE_VERSION_INFO_REPORTED, handle, status,
633                         version, manufacturer_name, subversion);
634   if (ret < 0) {
635     log::warn(
636         "failed for handle {}, status 0x{:x}, version 0x{:x}, "
637         "manufacturer_name 0x{:x}, subversion 0x{:x}, error {}",
638         handle, status, version, manufacturer_name, subversion, ret);
639   }
640 }
641 
LogA2dpAudioUnderrunEvent(const RawAddress & address,uint64_t encoding_interval_millis,int num_missing_pcm_bytes)642 void LogA2dpAudioUnderrunEvent(const RawAddress& address,
643                                uint64_t encoding_interval_millis,
644                                int num_missing_pcm_bytes) {
645   std::string obfuscated_id;
646   int metric_id = 0;
647   if (!address.IsEmpty()) {
648     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
649     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
650   }
651   // nullptr and size 0 represent missing value for obfuscated_id
652   BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
653                          address.IsEmpty() ? 0 : obfuscated_id.size());
654   int64_t encoding_interval_nanos = encoding_interval_millis * 1000000;
655   int ret =
656       stats_write(BLUETOOTH_A2DP_AUDIO_UNDERRUN_REPORTED, bytes_field,
657                   encoding_interval_nanos, num_missing_pcm_bytes, metric_id);
658   if (ret < 0) {
659     log::warn(
660         "failed for {}, encoding_interval_nanos {}, num_missing_pcm_bytes {}, "
661         "error {}",
662         address, encoding_interval_nanos, num_missing_pcm_bytes, ret);
663   }
664 }
665 
LogA2dpAudioOverrunEvent(const RawAddress & address,uint64_t encoding_interval_millis,int num_dropped_buffers,int num_dropped_encoded_frames,int num_dropped_encoded_bytes)666 void LogA2dpAudioOverrunEvent(const RawAddress& address,
667                               uint64_t encoding_interval_millis,
668                               int num_dropped_buffers,
669                               int num_dropped_encoded_frames,
670                               int num_dropped_encoded_bytes) {
671   std::string obfuscated_id;
672   int metric_id = 0;
673   if (!address.IsEmpty()) {
674     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
675     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
676   }
677   // nullptr and size 0 represent missing value for obfuscated_id
678   BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
679                          address.IsEmpty() ? 0 : obfuscated_id.size());
680   int64_t encoding_interval_nanos = encoding_interval_millis * 1000000;
681   int ret = stats_write(BLUETOOTH_A2DP_AUDIO_OVERRUN_REPORTED, bytes_field,
682                         encoding_interval_nanos, num_dropped_buffers,
683                         num_dropped_encoded_frames, num_dropped_encoded_bytes,
684                         metric_id);
685   if (ret < 0) {
686     log::warn(
687         "failed to log for {}, encoding_interval_nanos {}, num_dropped_buffers "
688         "{}, num_dropped_encoded_frames {}, num_dropped_encoded_bytes {}, "
689         "error {}",
690         address, encoding_interval_nanos, num_dropped_buffers,
691         num_dropped_encoded_frames, num_dropped_encoded_bytes, ret);
692   }
693 }
694 
LogA2dpPlaybackEvent(const RawAddress & address,int playback_state,int audio_coding_mode)695 void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state,
696                           int audio_coding_mode) {
697   std::string obfuscated_id;
698   int metric_id = 0;
699   if (!address.IsEmpty()) {
700     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
701     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
702   }
703   // nullptr and size 0 represent missing value for obfuscated_id
704   BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
705                          address.IsEmpty() ? 0 : obfuscated_id.size());
706   int ret = stats_write(BLUETOOTH_A2DP_PLAYBACK_STATE_CHANGED, bytes_field,
707                         playback_state, audio_coding_mode, metric_id);
708   if (ret < 0) {
709     log::warn(
710         "failed to log for {}, playback_state {}, audio_coding_mode {}, error "
711         "{}",
712         address, playback_state, audio_coding_mode, ret);
713   }
714 }
715 
LogReadRssiResult(const RawAddress & address,uint16_t handle,uint32_t cmd_status,int8_t rssi)716 void LogReadRssiResult(const RawAddress& address, uint16_t handle,
717                        uint32_t cmd_status, int8_t rssi) {
718   std::string obfuscated_id;
719   int metric_id = 0;
720   if (!address.IsEmpty()) {
721     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
722     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
723   }
724   // nullptr and size 0 represent missing value for obfuscated_id
725   BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
726                          address.IsEmpty() ? 0 : obfuscated_id.size());
727   int ret = stats_write(BLUETOOTH_DEVICE_RSSI_REPORTED, bytes_field, handle,
728                         cmd_status, rssi, metric_id);
729   if (ret < 0) {
730     log::warn("failed for {}, handle {}, status 0x{:x}, rssi {} dBm, error {}",
731               address, handle, cmd_status, rssi, ret);
732   }
733 }
734 
LogReadFailedContactCounterResult(const RawAddress & address,uint16_t handle,uint32_t cmd_status,int32_t failed_contact_counter)735 void LogReadFailedContactCounterResult(const RawAddress& address,
736                                        uint16_t handle, uint32_t cmd_status,
737                                        int32_t failed_contact_counter) {
738   std::string obfuscated_id;
739   int metric_id = 0;
740   if (!address.IsEmpty()) {
741     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
742     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
743   }
744   // nullptr and size 0 represent missing value for obfuscated_id
745   BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
746                          address.IsEmpty() ? 0 : obfuscated_id.size());
747   int ret =
748       stats_write(BLUETOOTH_DEVICE_FAILED_CONTACT_COUNTER_REPORTED, bytes_field,
749                   handle, cmd_status, failed_contact_counter, metric_id);
750   if (ret < 0) {
751     log::warn(
752         "failed for {}, handle {}, status 0x{:x}, failed_contact_counter {} "
753         "packets, error {}",
754         address, handle, cmd_status, failed_contact_counter, ret);
755   }
756 }
757 
LogReadTxPowerLevelResult(const RawAddress & address,uint16_t handle,uint32_t cmd_status,int32_t transmit_power_level)758 void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle,
759                                uint32_t cmd_status,
760                                int32_t transmit_power_level) {
761   std::string obfuscated_id;
762   int metric_id = 0;
763   if (!address.IsEmpty()) {
764     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
765     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
766   }
767   // nullptr and size 0 represent missing value for obfuscated_id
768   BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
769                          address.IsEmpty() ? 0 : obfuscated_id.size());
770   int ret = stats_write(BLUETOOTH_DEVICE_TX_POWER_LEVEL_REPORTED, bytes_field,
771                         handle, cmd_status, transmit_power_level, metric_id);
772   if (ret < 0) {
773     log::warn(
774         "failed for {}, handle {}, status 0x{:x}, transmit_power_level {} "
775         "packets, error {}",
776         address, handle, cmd_status, transmit_power_level, ret);
777   }
778 }
779 
LogSmpPairingEvent(const RawAddress & address,uint8_t smp_cmd,android::bluetooth::DirectionEnum direction,uint8_t smp_fail_reason)780 void LogSmpPairingEvent(const RawAddress& address, uint8_t smp_cmd,
781                         android::bluetooth::DirectionEnum direction,
782                         uint8_t smp_fail_reason) {
783   std::string obfuscated_id;
784   int metric_id = 0;
785   if (!address.IsEmpty()) {
786     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
787     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
788   }
789   // nullptr and size 0 represent missing value for obfuscated_id
790   BytesField obfuscated_id_field(
791       address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
792       address.IsEmpty() ? 0 : obfuscated_id.size());
793   int ret =
794       stats_write(BLUETOOTH_SMP_PAIRING_EVENT_REPORTED, obfuscated_id_field,
795                   smp_cmd, direction, smp_fail_reason, metric_id);
796   if (ret < 0) {
797     log::warn(
798         "failed for {}, smp_cmd 0x{:x}, direction {}, smp_fail_reason 0x{:x}, "
799         "error {}",
800         address, smp_cmd, direction, smp_fail_reason, ret);
801   }
802 }
803 
LogClassicPairingEvent(const RawAddress & address,uint16_t handle,uint32_t hci_cmd,uint16_t hci_event,uint16_t cmd_status,uint16_t reason_code,int64_t event_value)804 void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, uint16_t hci_event,
805                             uint16_t cmd_status, uint16_t reason_code, int64_t event_value) {
806   std::string obfuscated_id;
807   int metric_id = 0;
808   if (!address.IsEmpty()) {
809     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
810     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
811   }
812   // nullptr and size 0 represent missing value for obfuscated_id
813   BytesField obfuscated_id_field(
814       address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
815       address.IsEmpty() ? 0 : obfuscated_id.size());
816   int ret = stats_write(BLUETOOTH_CLASSIC_PAIRING_EVENT_REPORTED,
817                         obfuscated_id_field, handle, hci_cmd, hci_event,
818                         cmd_status, reason_code, event_value, metric_id);
819   if (ret < 0) {
820     log::warn(
821         "failed for {}, handle {}, hci_cmd 0x{:x}, hci_event 0x{:x}, "
822         "cmd_status 0x{:x}, reason 0x{:x}, event_value {}, error {}",
823         address, handle, hci_cmd, hci_event, cmd_status, reason_code,
824         event_value, ret);
825   }
826 }
827 
LogSdpAttribute(const RawAddress & address,uint16_t protocol_uuid,uint16_t attribute_id,size_t attribute_size,const char * attribute_value)828 void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid,
829                      uint16_t attribute_id, size_t attribute_size,
830                      const char* attribute_value) {
831   std::string obfuscated_id;
832   int metric_id = 0;
833   if (!address.IsEmpty()) {
834     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
835     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
836   }
837   // nullptr and size 0 represent missing value for obfuscated_id
838   BytesField obfuscated_id_field(
839       address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
840       address.IsEmpty() ? 0 : obfuscated_id.size());
841   BytesField attribute_field(attribute_value, attribute_size);
842   int ret =
843       stats_write(BLUETOOTH_SDP_ATTRIBUTE_REPORTED, obfuscated_id_field,
844                   protocol_uuid, attribute_id, attribute_field, metric_id);
845   if (ret < 0) {
846     log::warn(
847         "failed for {}, protocol_uuid 0x{:x}, attribute_id 0x{:x}, error {}",
848         address, protocol_uuid, attribute_id, ret);
849   }
850 }
851 
LogSocketConnectionState(const RawAddress & address,int port,int type,android::bluetooth::SocketConnectionstateEnum connection_state,int64_t tx_bytes,int64_t rx_bytes,int uid,int server_port,android::bluetooth::SocketRoleEnum socket_role)852 void LogSocketConnectionState(
853     const RawAddress& address, int port, int type,
854     android::bluetooth::SocketConnectionstateEnum connection_state,
855     int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port,
856     android::bluetooth::SocketRoleEnum socket_role) {
857   std::string obfuscated_id;
858   int metric_id = 0;
859   if (!address.IsEmpty()) {
860     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
861     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
862   }
863   // nullptr and size 0 represent missing value for obfuscated_id
864   BytesField obfuscated_id_field(
865       address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
866       address.IsEmpty() ? 0 : obfuscated_id.size());
867   int ret =
868       stats_write(BLUETOOTH_SOCKET_CONNECTION_STATE_CHANGED,
869                   obfuscated_id_field, port, type, connection_state, tx_bytes,
870                   rx_bytes, uid, server_port, socket_role, metric_id);
871   if (ret < 0) {
872     log::warn(
873         "failed for {}, port {}, type {}, state {}, tx_bytes {}, rx_bytes {}, "
874         "uid {}, server_port {}, socket_role {}, error {}",
875         address, port, type, connection_state, tx_bytes, rx_bytes, uid,
876         server_port, socket_role, ret);
877   }
878 }
879 
LogManufacturerInfo(const RawAddress & address,android::bluetooth::AddressTypeEnum address_type,android::bluetooth::DeviceInfoSrcEnum source_type,const std::string & source_name,const std::string & manufacturer,const std::string & model,const std::string & hardware_version,const std::string & software_version)880 void LogManufacturerInfo(const RawAddress& address,
881                          android::bluetooth::AddressTypeEnum address_type,
882                          android::bluetooth::DeviceInfoSrcEnum source_type,
883                          const std::string& source_name,
884                          const std::string& manufacturer,
885                          const std::string& model,
886                          const std::string& hardware_version,
887                          const std::string& software_version) {
888   std::string obfuscated_id;
889   int metric_id = 0;
890   if (!address.IsEmpty()) {
891     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
892     metric_id = MetricIdAllocator::GetInstance().AllocateId(address);
893   }
894   // nullptr and size 0 represent missing value for obfuscated_id
895   BytesField obfuscated_id_field(
896       address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
897       address.IsEmpty() ? 0 : obfuscated_id.size());
898   int ret = stats_write(
899       BLUETOOTH_DEVICE_INFO_REPORTED, obfuscated_id_field, source_type,
900       source_name.c_str(), manufacturer.c_str(), model.c_str(),
901       hardware_version.c_str(), software_version.c_str(), metric_id,
902       address_type, address.address[5], address.address[4], address.address[3]);
903   if (ret < 0) {
904     log::warn(
905         "failed for {}, source_type {}, source_name {}, manufacturer {}, model "
906         "{}, hardware_version {}, software_version {} MAC address type {} MAC "
907         "address prefix {} {} {}, error {}",
908         address, source_type, source_name, manufacturer, model,
909         hardware_version, software_version, address_type, address.address[5],
910         address.address[4], address.address[3], ret);
911   }
912 }
913 
LogBluetoothHalCrashReason(const RawAddress & address,uint32_t error_code,uint32_t vendor_error_code)914 void LogBluetoothHalCrashReason(const RawAddress& address, uint32_t error_code,
915                                 uint32_t vendor_error_code) {
916   std::string obfuscated_id;
917   if (!address.IsEmpty()) {
918     obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address);
919   }
920   // nullptr and size 0 represent missing value for obfuscated_id
921   BytesField obfuscated_id_field(
922       address.IsEmpty() ? nullptr : obfuscated_id.c_str(),
923       address.IsEmpty() ? 0 : obfuscated_id.size());
924   int ret = stats_write(BLUETOOTH_HAL_CRASH_REASON_REPORTED, 0,
925                         obfuscated_id_field, error_code, vendor_error_code);
926   if (ret < 0) {
927     log::warn(
928         "failed for {}, error_code 0x{:x}, vendor_error_code 0x{:x}, error {}",
929         address, error_code, vendor_error_code, ret);
930   }
931 }
932 
LogLeAudioConnectionSessionReported(int32_t group_size,int32_t group_metric_id,int64_t connection_duration_nanos,std::vector<int64_t> & device_connecting_offset_nanos,std::vector<int64_t> & device_connected_offset_nanos,std::vector<int64_t> & device_connection_duration_nanos,std::vector<int32_t> & device_connection_status,std::vector<int32_t> & device_disconnection_status,std::vector<RawAddress> & device_address,std::vector<int64_t> & streaming_offset_nanos,std::vector<int64_t> & streaming_duration_nanos,std::vector<int32_t> & streaming_context_type)933 void LogLeAudioConnectionSessionReported(
934     int32_t group_size, int32_t group_metric_id,
935     int64_t connection_duration_nanos,
936     std::vector<int64_t>& device_connecting_offset_nanos,
937     std::vector<int64_t>& device_connected_offset_nanos,
938     std::vector<int64_t>& device_connection_duration_nanos,
939     std::vector<int32_t>& device_connection_status,
940     std::vector<int32_t>& device_disconnection_status,
941     std::vector<RawAddress>& device_address,
942     std::vector<int64_t>& streaming_offset_nanos,
943     std::vector<int64_t>& streaming_duration_nanos,
944     std::vector<int32_t>& streaming_context_type) {
945   std::vector<int32_t> device_metric_id(device_address.size());
946   for (uint64_t i = 0; i < device_address.size(); i++) {
947     if (!device_address[i].IsEmpty()) {
948       device_metric_id[i] =
949           bluetooth::shim::AllocateIdFromMetricIdAllocator(device_address[i]);
950     } else {
951       device_metric_id[i] = 0;
952     }
953   }
954   int ret = stats_write(
955       LE_AUDIO_CONNECTION_SESSION_REPORTED, group_size, group_metric_id,
956       connection_duration_nanos, device_connecting_offset_nanos,
957       device_connected_offset_nanos, device_connection_duration_nanos,
958       device_connection_status, device_disconnection_status, device_metric_id,
959       streaming_offset_nanos, streaming_duration_nanos, streaming_context_type);
960   if (ret < 0) {
961     log::warn(
962         "failed for group {}device_connecting_offset_nanos[{}], "
963         "device_connected_offset_nanos[{}], "
964         "device_connection_duration_nanos[{}], device_connection_status[{}], "
965         "device_disconnection_status[{}], device_metric_id[{}], "
966         "streaming_offset_nanos[{}], streaming_duration_nanos[{}], "
967         "streaming_context_type[{}]",
968         group_metric_id, device_connecting_offset_nanos.size(),
969         device_connected_offset_nanos.size(),
970         device_connection_duration_nanos.size(),
971         device_connection_status.size(), device_disconnection_status.size(),
972         device_metric_id.size(), streaming_offset_nanos.size(),
973         streaming_duration_nanos.size(), streaming_context_type.size());
974   }
975 }
976 
LogLeAudioBroadcastSessionReported(int64_t duration_nanos)977 void LogLeAudioBroadcastSessionReported(int64_t duration_nanos) {
978   int ret = stats_write(LE_AUDIO_BROADCAST_SESSION_REPORTED, duration_nanos);
979   if (ret < 0) {
980     log::warn("failed for duration={}", duration_nanos);
981   }
982 }
983 
LogLeBluetoothConnectionMetricEventReported(const Address & address,android::bluetooth::le::LeConnectionOriginType origin_type,android::bluetooth::le::LeConnectionType connection_type,android::bluetooth::le::LeConnectionState transaction_state,std::vector<std::pair<os::ArgumentType,int>> argument_list)984 void LogLeBluetoothConnectionMetricEventReported(
985     const Address& address,
986     android::bluetooth::le::LeConnectionOriginType origin_type,
987     android::bluetooth::le::LeConnectionType connection_type,
988     android::bluetooth::le::LeConnectionState transaction_state,
989     std::vector<std::pair<os::ArgumentType, int>>
990         argument_list) {
991   // Log the events for the State Management
992   metrics::MetricsCollector::GetLEConnectionMetricsCollector()
993       ->AddStateChangedEvent(address, origin_type, connection_type,
994                              transaction_state, argument_list);
995 }
996 
997 }  // namespace common
998 
999 }  // namespace bluetooth
1000