1#!/usr/bin/env python3 2# Copyright 2018 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); you may not 5# use this file except in compliance with the License. You may obtain a copy of 6# the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13# License for the specific language governing permissions and limitations under 14# the License. 15 16import base64 17import logging 18import os 19import subprocess 20import sys 21import tempfile 22from distutils.spawn import find_executable 23import google.protobuf.text_format as text_format 24from importlib import import_module 25 26 27def compile_proto(proto_path, output_dir): 28 """Invoke Protocol Compiler to generate python from given source .proto.""" 29 # Find compiler path 30 protoc = None 31 if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']): 32 protoc = os.environ['PROTOC'] 33 if not protoc: 34 protoc = find_executable('protoc') 35 if not protoc: 36 logging.error("Cannot find Protobuf compiler (>=3.0.0), please install" 37 "protobuf-compiler package. Prefer copying from <top>/prebuilts/tools") 38 logging.error(" prebuilts/tools/linux-x86_64/protoc/bin/protoc") 39 logging.error("If prebuilts are not available, use apt-get:") 40 logging.error(" sudo apt-get install protobuf-compiler") 41 return None 42 # Validate input proto path 43 if not os.path.exists(proto_path): 44 logging.error('Can\'t find required file: %s\n' % proto_path) 45 return None 46 # Validate output py-proto path 47 if not os.path.exists(output_dir): 48 os.mkdirs(output_dir) 49 elif not os.path.isdir(output_dir): 50 logging.error("Output path is not a valid directory: %s" % (output_dir)) 51 return None 52 input_dir = os.path.dirname(proto_path) 53 output_filename = os.path.basename(proto_path).replace('.proto', '_pb2.py') 54 output_path = os.path.join(output_dir, output_filename) 55 protoc_command = [protoc, '-I=%s' % (input_dir), '--python_out=%s' % (output_dir), proto_path] 56 if subprocess.call(protoc_command, stderr=subprocess.STDOUT) != 0: 57 logging.error("Fail to compile proto") 58 return None 59 output_module_name = os.path.splitext(output_filename)[0] 60 return output_module_name 61 62 63def compile_import_proto(output_dir, proto_path): 64 """ 65 Compile protobuf from PROTO_PATH and put the result in OUTPUT_DIR. 66 Return the imported module to caller. 67 :param output_dir: To store generated python proto library 68 :param proto_path: Path to the .proto file that needs to be compiled 69 :return: python proto module 70 """ 71 output_module_name = compile_proto(proto_path, output_dir) 72 if not output_module_name: 73 return None 74 sys.path.append(output_dir) 75 output_module = None 76 try: 77 output_module = import_module(output_module_name) 78 except ImportError: 79 logging.error("Cannot import generated py-proto %s" % (output_module_name)) 80 return output_module 81 82 83def parse_proto_to_ascii(binary_proto_msg): 84 """ 85 Parse binary protobuf message to human readable ascii string 86 :param binary_proto_msg: 87 :return: ascii string of the message 88 """ 89 return text_format.MessageToString(binary_proto_msg) 90 91 92def dump_metrics(): 93 os.system('adb wait-for-device') 94 p = subprocess.Popen( 95 "adb shell dumpsys bluetooth_manager --proto-bin", 96 shell=True, 97 stdout=subprocess.PIPE, 98 stderr=subprocess.PIPE, 99 stdin=subprocess.PIPE) 100 return p.communicate() 101 102 103def get_bluetooth_metrics(proto_native_str_64, bluetooth_proto_module): 104 bluetooth_log = bluetooth_proto_module.BluetoothLog() 105 proto_native_str = base64.b64decode(proto_native_str_64) 106 bluetooth_log.MergeFromString(proto_native_str) 107 return bluetooth_log 108 109 110def main(): 111 root = logging.getLogger() 112 root.setLevel(logging.DEBUG) 113 log_handler = logging.StreamHandler(sys.stderr) 114 log_handler.setLevel(logging.DEBUG) 115 formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") 116 log_handler.setFormatter(formatter) 117 root.addHandler(log_handler) 118 if len(sys.argv) < 2: 119 logging.error("Not enough arguments. Need at least 2") 120 logging.error("Usage: " + sys.argv[0] + " <path_to_metric_proto>") 121 sys.exit(1) 122 if sys.argv[1] == "-h": 123 logging.info("Usage: " + sys.argv[0] + " <path_to_metric_proto>") 124 logging.info("Requires Protobuf compiler, protoc, version >=3.0.0") 125 sys.exit(0) 126 bluetooth_proto_module = compile_import_proto(tempfile.gettempdir(), sys.argv[1]) 127 if not bluetooth_proto_module: 128 logging.error("Cannot compile " + sys.argv[1]) 129 sys.exit(1) 130 stdout, stderr = dump_metrics() 131 stdout = stdout.strip() 132 stderr = stderr.strip() 133 bluetooth_log = get_bluetooth_metrics(stdout, bluetooth_proto_module) 134 bluetooth_log_ascii = parse_proto_to_ascii(bluetooth_log) 135 print(bluetooth_log_ascii) 136 137 138if __name__ == "__main__": 139 main() 140