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