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(
37            "Cannot find Protobuf compiler (>=3.0.0), please install"
38            "protobuf-compiler package. Prefer copying from <top>/prebuilts/tools"
39        )
40        logging.error("    prebuilts/tools/linux-x86_64/protoc/bin/protoc")
41        logging.error("If prebuilts are not available, use apt-get:")
42        logging.error("    sudo apt-get install protobuf-compiler")
43        return None
44    # Validate input proto path
45    if not os.path.exists(proto_path):
46        logging.error('Can\'t find required file: %s\n' % proto_path)
47        return None
48    # Validate output py-proto path
49    if not os.path.exists(output_dir):
50        os.mkdirs(output_dir)
51    elif not os.path.isdir(output_dir):
52        logging.error("Output path is not a valid directory: %s" % (output_dir))
53        return None
54    input_dir = os.path.dirname(proto_path)
55    output_filename = os.path.basename(proto_path).replace('.proto', '_pb2.py')
56    output_path = os.path.join(output_dir, output_filename)
57    protoc_command = [
58        protoc,
59        '-I=%s' % (input_dir),
60        '--python_out=%s' % (output_dir), proto_path
61    ]
62    if subprocess.call(protoc_command, stderr=subprocess.STDOUT) != 0:
63        logging.error("Fail to compile proto")
64        return None
65    output_module_name = os.path.splitext(output_filename)[0]
66    return output_module_name
67
68
69def compile_import_proto(output_dir, proto_path):
70    """
71    Compile protobuf from PROTO_PATH and put the result in OUTPUT_DIR.
72    Return the imported module to caller.
73    :param output_dir: To store generated python proto library
74    :param proto_path: Path to the .proto file that needs to be compiled
75    :return: python proto module
76    """
77    output_module_name = compile_proto(proto_path, output_dir)
78    if not output_module_name:
79        return None
80    sys.path.append(output_dir)
81    output_module = None
82    try:
83        output_module = import_module(output_module_name)
84    except ImportError:
85        logging.error(
86            "Cannot import generated py-proto %s" % (output_module_name))
87    return output_module
88
89
90def parse_proto_to_ascii(binary_proto_msg):
91    """
92    Parse binary protobuf message to human readable ascii string
93    :param binary_proto_msg:
94    :return: ascii string of the message
95    """
96    return text_format.MessageToString(binary_proto_msg)
97
98
99def dump_metrics():
100    os.system('adb wait-for-device')
101    p = subprocess.Popen(
102        "adb shell dumpsys bluetooth_manager --proto-bin",
103        shell=True,
104        stdout=subprocess.PIPE,
105        stderr=subprocess.PIPE,
106        stdin=subprocess.PIPE)
107    return p.communicate()
108
109
110def get_bluetooth_metrics(proto_native_str_64, bluetooth_proto_module):
111    bluetooth_log = bluetooth_proto_module.BluetoothLog()
112    proto_native_str = base64.b64decode(proto_native_str_64)
113    bluetooth_log.MergeFromString(proto_native_str)
114    return bluetooth_log
115
116
117def main():
118    root = logging.getLogger()
119    root.setLevel(logging.DEBUG)
120    log_handler = logging.StreamHandler(sys.stderr)
121    log_handler.setLevel(logging.DEBUG)
122    formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
123    log_handler.setFormatter(formatter)
124    root.addHandler(log_handler)
125    if len(sys.argv) < 2:
126        logging.error("Not enough arguments. Need at least 2")
127        logging.error("Usage: " + sys.argv[0] + " <path_to_metric_proto>")
128        sys.exit(1)
129    if sys.argv[1] == "-h":
130        logging.info("Usage: " + sys.argv[0] + " <path_to_metric_proto>")
131        logging.info("Requires Protobuf compiler, protoc, version >=3.0.0")
132        sys.exit(0)
133    bluetooth_proto_module = compile_import_proto(tempfile.gettempdir(),
134                                                  sys.argv[1])
135    if not bluetooth_proto_module:
136        logging.error("Cannot compile " + sys.argv[1])
137        sys.exit(1)
138    stdout, stderr = dump_metrics()
139    stdout = stdout.strip()
140    stderr = stderr.strip()
141    bluetooth_log = get_bluetooth_metrics(stdout, bluetooth_proto_module)
142    bluetooth_log_ascii = parse_proto_to_ascii(bluetooth_log)
143    print(bluetooth_log_ascii)
144
145
146if __name__ == "__main__":
147    main()
148