blob: ed5d22df312a4bad08c7c58586d3c31dec8a7a35 [file] [log] [blame]
David Burger7fd1dbe2020-03-26 09:26:55 -06001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Transforms config from /config/proto/api proto format to platform JSON."""
7
8import argparse
9import json
10import pprint
C Shapiro90fda252020-04-17 14:34:57 -050011import os
David Burger7fd1dbe2020-03-26 09:26:55 -060012import sys
C Shapiro90fda252020-04-17 14:34:57 -050013import re
C Shapiro5bf23a72020-04-24 11:40:17 -050014import xml.etree.ElementTree as etree
C Shapiro9a3ac8c2020-04-25 07:49:21 -050015import xml.dom.minidom as minidom
David Burger7fd1dbe2020-03-26 09:26:55 -060016
17from collections import namedtuple
18
Prathmesh Prabhu72f8a002020-04-10 09:57:53 -070019from chromiumos.config.api import device_brand_pb2
David Burger92609a32020-04-23 10:38:50 -060020from chromiumos.config.api import topology_pb2
C Shapiro5bf23a72020-04-24 11:40:17 -050021from chromiumos.config.payload import config_bundle_pb2
Prathmesh Prabhu72f8a002020-04-10 09:57:53 -070022from chromiumos.config.api.software import brand_config_pb2
David Burger7fd1dbe2020-03-26 09:26:55 -060023
David Burgere6f76222020-04-27 11:08:01 -060024from google.protobuf import json_format
25
David Burger7fd1dbe2020-03-26 09:26:55 -060026Config = namedtuple('Config',
27 ['program',
28 'hw_design',
29 'odm',
30 'hw_design_config',
31 'device_brand',
C Shapiro2f0bb5d2020-04-14 10:07:47 -050032 'device_signer_config',
David Burger7fd1dbe2020-03-26 09:26:55 -060033 'oem',
34 'sw_config',
35 'brand_config',
36 'build_target'])
37
C Shapiro5bf23a72020-04-24 11:40:17 -050038ConfigFiles = namedtuple('ConfigFiles',
39 ['bluetooth',
C Shapiro6830e6c2020-04-29 13:29:56 -050040 'arc_hw_features',
C Shapiro2b6d5332020-05-06 17:51:35 -050041 'touch_fw',
C Shapiro6830e6c2020-04-29 13:29:56 -050042 'dptf_file'])
C Shapiro5bf23a72020-04-24 11:40:17 -050043
C Shapiro6830e6c2020-04-29 13:29:56 -050044DPTF_PATH = 'sw_build_config/platform/chromeos-config/thermal/dptf.dv'
C Shapiro2b6d5332020-05-06 17:51:35 -050045TOUCH_PATH = 'sw_build_config/platform/chromeos-config/touch'
David Burger7fd1dbe2020-03-26 09:26:55 -060046
47def ParseArgs(argv):
48 """Parse the available arguments.
49
50 Invalid arguments or -h cause this function to print a message and exit.
51
52 Args:
53 argv: List of string arguments (excluding program name / argv[0])
54
55 Returns:
56 argparse.Namespace object containing the attributes.
57 """
58 parser = argparse.ArgumentParser(
59 description='Converts source proto config into platform JSON config.')
60 parser.add_argument(
61 '-c',
62 '--project_configs',
63 nargs='+',
64 type=str,
65 help='Space delimited list of source protobinary project config files.')
66 parser.add_argument(
67 '-p',
68 '--program_config',
69 type=str,
70 help='Path to the source program-level protobinary file')
71 parser.add_argument(
72 '-o',
73 '--output',
74 type=str,
75 help='Output file that will be generated')
76 return parser.parse_args(argv)
77
78
79def _Set(field, target, target_name):
80 if field:
81 target[target_name] = field
82
83
C Shapiro5bf23a72020-04-24 11:40:17 -050084def _BuildArc(config, config_files):
David Burger7fd1dbe2020-03-26 09:26:55 -060085 if config.build_target.arc:
86 build_properties = {
87 'device': config.build_target.arc.device,
88 'first-api-level': config.build_target.arc.first_api_level,
89 'marketing-name': config.device_brand.brand_name,
90 'metrics-tag': config.hw_design.name.lower(),
Andrew Lambb47b7dc2020-04-07 10:20:32 -060091 'product': config.build_target.id.value,
David Burger7fd1dbe2020-03-26 09:26:55 -060092 }
93 if config.oem:
94 build_properties['oem'] = config.oem.name
C Shapiro5bf23a72020-04-24 11:40:17 -050095 result = {
96 'build-properties': build_properties
97 }
98 feature_id = _ArcHardwareFeatureId(config.hw_design_config)
99 if feature_id in config_files.arc_hw_features:
100 result['hardware-features'] = config_files.arc_hw_features[feature_id]
101 return result
David Burger7fd1dbe2020-03-26 09:26:55 -0600102
C Shapiro90fda252020-04-17 14:34:57 -0500103def _BuildBluetooth(config, bluetooth_files):
104 bt_flags = config.sw_config.bluetooth_config.flags
105 # Convert to native map (from proto wrapper)
106 bt_flags_map = dict(bt_flags)
107 result = {}
108 if bt_flags_map:
109 result['flags'] = bt_flags_map
C Shapiro74da76e2020-05-04 13:02:20 -0500110 bt_comp = config.hw_design_config.hardware_features.bluetooth.component.usb
C Shapiro90fda252020-04-17 14:34:57 -0500111 if bt_comp.vendor_id:
112 bt_id = _BluetoothId(config.hw_design.name.lower(), bt_comp)
113 if bt_id in bluetooth_files:
114 result['config'] = bluetooth_files[bt_id]
115 return result
116
David Burger7fd1dbe2020-03-26 09:26:55 -0600117
118def _BuildFingerprint(hw_topology):
Andrew Lambc2c55462020-04-06 08:43:34 -0600119 if hw_topology.HasField('fingerprint'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600120 fp = hw_topology.fingerprint.hardware_feature.fingerprint
David Burger92609a32020-04-23 10:38:50 -0600121 result = {}
122 if fp.location != topology_pb2.HardwareFeatures.Fingerprint.NOT_PRESENT:
123 location = fp.Location.DESCRIPTOR.values_by_number[fp.location].name
124 result['sensor-location'] = location.lower().replace('_', '-')
125 if fp.board:
126 result['board'] = fp.board
David Burger7fd1dbe2020-03-26 09:26:55 -0600127 return result
128
129
130def _FwBcsPath(payload):
131 if payload and payload.firmware_image_name:
132 return 'bcs://%s.%d.%d.0.tbz2' % (
133 payload.firmware_image_name,
134 payload.version.major,
135 payload.version.minor)
136
137
138def _FwBuildTarget(payload):
139 if payload:
140 return payload.build_target_name
141
142
143def _BuildFirmware(config):
Andrew Lamb3da156d2020-04-16 16:00:56 -0600144 fw_payload_config = config.sw_config.firmware
145 fw_build_config = config.sw_config.firmware_build_config
146 main_ro = fw_payload_config.main_ro_payload
147 main_rw = fw_payload_config.main_rw_payload
148 ec_ro = fw_payload_config.ec_ro_payload
149 pd_ro = fw_payload_config.pd_ro_payload
David Burger7fd1dbe2020-03-26 09:26:55 -0600150
151 build_targets = {}
Andrew Lamb3da156d2020-04-16 16:00:56 -0600152
Andrew Lambf8954ee2020-04-21 10:24:40 -0600153 _Set(fw_build_config.build_targets.depthcharge, build_targets, 'depthcharge')
154 _Set(fw_build_config.build_targets.coreboot, build_targets, 'coreboot')
155 _Set(fw_build_config.build_targets.ec, build_targets, 'ec')
156 _Set(
157 list(fw_build_config.build_targets.ec_extras), build_targets, 'ec_extras')
158 _Set(fw_build_config.build_targets.libpayload, build_targets, 'libpayload')
David Burger7fd1dbe2020-03-26 09:26:55 -0600159
160 result = {
161 'bcs-overlay': config.build_target.overlay_name,
162 'build-targets': build_targets,
David Burger7fd1dbe2020-03-26 09:26:55 -0600163 }
Andrew Lamb883fa042020-04-06 11:37:22 -0600164
165 _Set(main_ro.firmware_image_name.lower(), result, 'image-name')
166
Andrew Lamb883fa042020-04-06 11:37:22 -0600167 _Set(_FwBcsPath(main_ro), result, 'main-ro-image')
168 _Set(_FwBcsPath(main_rw), result, 'main-rw-image')
169 _Set(_FwBcsPath(ec_ro), result, 'ec-ro-image')
170 _Set(_FwBcsPath(pd_ro), result, 'pd-ro-image')
David Burger7fd1dbe2020-03-26 09:26:55 -0600171
Andrew Lambf39fbe82020-04-13 16:14:33 -0600172 _Set(
173 config.hw_design_config.hardware_features.fw_config.value,
174 result,
175 'firmware-config',
176 )
177
David Burger7fd1dbe2020-03-26 09:26:55 -0600178 return result
179
180
181def _BuildFwSigning(config):
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500182 if config.sw_config.firmware and config.device_signer_config:
David Burger68e0d142020-05-15 17:29:33 -0600183 program = config.program.id.value
184 hw_design = config.hw_design.name.lower()
David Burger4a344652020-05-15 19:45:26 -0600185 brand_code = config.device_brand.brand_code
186 if program == 'Zork' and brand_code == 'ZZCR':
187 # TODO(https://crbug.com/1070814): Hack!!!, Zork projects that do not have
188 # their own brand-code do not share signing keys. Thus this hack for now.
David Burgerf762dee2020-05-17 05:58:58 -0600189 # TODO(https://crbug.com/1083770): Also, Berknip signing keys not present
190 # in signing server, special case.
191 key_id = 'TREMBYLE' if hw_design == 'berknip' else hw_design.upper()
David Burger68e0d142020-05-15 17:29:33 -0600192 return {
David Burgerf762dee2020-05-17 05:58:58 -0600193 'key-id': key_id,
David Burger68e0d142020-05-15 17:29:33 -0600194 'signature-id': hw_design,
195 }
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500196 return {
197 'key-id': config.device_signer_config.key_id,
David Burger68e0d142020-05-15 17:29:33 -0600198 'signature-id': hw_design,
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500199 }
200 return {}
David Burger7fd1dbe2020-03-26 09:26:55 -0600201
202
203def _File(source, destination):
204 return {
205 'destination': destination,
206 'source': source
207 }
208
209
210def _BuildAudio(config):
211 alsa_path = '/usr/share/alsa/ucm'
212 cras_path = '/etc/cras'
213 project_name = config.hw_design.name.lower()
David Burger43250662020-05-07 11:21:50 -0600214 program_name = config.program.name.lower()
Andrew Lamb7d536782020-04-07 10:23:55 -0600215 if not config.sw_config.HasField('audio_config'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600216 return {}
217 audio = config.sw_config.audio_config
218 card = audio.card_name
David Burger599ff7b2020-04-06 16:29:31 -0600219 card_with_suffix = audio.card_name
220 if audio.ucm_suffix:
221 card_with_suffix += '.' + audio.ucm_suffix
David Burger7fd1dbe2020-03-26 09:26:55 -0600222 files = []
223 if audio.ucm_file:
David Burger599ff7b2020-04-06 16:29:31 -0600224 files.append(_File(
225 audio.ucm_file,
226 '%s/%s/HiFi.conf' % (alsa_path, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600227 if audio.ucm_master_file:
228 files.append(_File(
David Burger599ff7b2020-04-06 16:29:31 -0600229 audio.ucm_master_file,
230 '%s/%s/%s.conf' % (alsa_path, card_with_suffix, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600231 if audio.card_config_file:
232 files.append(_File(
233 audio.card_config_file, '%s/%s/%s' % (cras_path, project_name, card)))
234 if audio.dsp_file:
235 files.append(
David Burger2e254902020-04-02 16:56:01 -0600236 _File(audio.dsp_file, '%s/%s/dsp.ini' % (cras_path, project_name)))
David Burgere1a37492020-05-06 09:29:24 -0600237 if audio.module_file:
238 files.append(
David Burger43250662020-05-07 11:21:50 -0600239 _File(audio.module_file, '/etc/modprobe.d/alsa-%s.conf' % program_name))
David Burgere1a37492020-05-06 09:29:24 -0600240 if audio.board_file:
241 files.append(
242 _File(audio.board_file, '%s/%s/board.ini' % (cras_path, project_name)))
David Burger599ff7b2020-04-06 16:29:31 -0600243
244 result = {
David Burger7fd1dbe2020-03-26 09:26:55 -0600245 'main': {
246 'cras-config-dir': project_name,
247 'files': files,
248 }
249 }
David Burger599ff7b2020-04-06 16:29:31 -0600250 if audio.ucm_suffix:
David Burger03cdcbd2020-04-13 13:54:48 -0600251 result['main']['ucm-suffix'] = audio.ucm_suffix
David Burger599ff7b2020-04-06 16:29:31 -0600252
253 return result
David Burger7fd1dbe2020-03-26 09:26:55 -0600254
255
David Burger8aa8fa32020-04-14 08:30:34 -0600256def _BuildCamera(hw_topology):
257 if hw_topology.HasField('camera'):
258 camera = hw_topology.camera.hardware_feature.camera
259 result = {}
260 if camera.count.value:
261 result['count'] = camera.count.value
262 return result
263
264
Andrew Lamb7806ce92020-04-07 10:22:17 -0600265def _BuildIdentity(hw_scan_config, program, brand_scan_config=None):
David Burger7fd1dbe2020-03-26 09:26:55 -0600266 identity = {}
267 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
268 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
Andrew Lamb7806ce92020-04-07 10:22:17 -0600269 # 'platform-name' is needed to support 'mosys platform name'. Clients should
270 # longer require platform name, but set it here for backwards compatibility.
271 _Set(program.name, identity, 'platform-name')
David Burger7fd1dbe2020-03-26 09:26:55 -0600272 # ARM architecture
273 _Set(hw_scan_config.device_tree_compatible_match, identity,
274 'device-tree-compatible-match')
275
276 if brand_scan_config:
277 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
278
279 return identity
280
281
282def _Lookup(id_value, id_map):
283 if id_value.value:
284 key = id_value.value
285 if key in id_map:
286 return id_map[id_value.value]
287 error = 'Failed to lookup %s with value: %s' % (
288 id_value.__class__.__name__.replace('Id', ''), key)
289 print(error)
290 print('Check the config contents provided:')
291 pp = pprint.PrettyPrinter(indent=4)
292 pp.pprint(id_map)
293 raise Exception(error)
294
295
C Shapiro2b6d5332020-05-06 17:51:35 -0500296def _BuildTouchFileConfig(config, project_name):
297 partners = dict([(x.id.value, x) for x in config.partners.value])
298 files = []
299 for comp in config.components:
C Shapiro4813be62020-05-13 17:31:58 -0500300 touch = comp.touchscreen
301 # Everything is the same for Touch screen/pad, except different fields
302 if comp.HasField('touchpad'):
303 touch = comp.touchpad
304 if touch.product_id:
C Shapiro2b6d5332020-05-06 17:51:35 -0500305 vendor = _Lookup(comp.manufacturer_id, partners)
306 if not vendor:
307 raise Exception(
C Shapiro4813be62020-05-13 17:31:58 -0500308 "Manufacturer must be set for touch device %s" % comp.id.value)
C Shapiro2b6d5332020-05-06 17:51:35 -0500309
C Shapiro4813be62020-05-13 17:31:58 -0500310 product_id = touch.product_id
311 fw_version = touch.fw_version
C Shapiro2b6d5332020-05-06 17:51:35 -0500312
C Shapiro5c6fc212020-05-13 16:32:09 -0500313 touch_vendor = vendor.touch_vendor
314 sym_link = touch_vendor.fw_file_format.format(
C Shapiro2b6d5332020-05-06 17:51:35 -0500315 vendor_name = vendor.name,
C Shapiro5c6fc212020-05-13 16:32:09 -0500316 vendor_id = touch_vendor.vendor_id,
C Shapiro2b6d5332020-05-06 17:51:35 -0500317 product_id = product_id,
318 fw_version = fw_version,
C Shapiro4813be62020-05-13 17:31:58 -0500319 product_series = touch.product_series
C Shapiro2b6d5332020-05-06 17:51:35 -0500320 )
321
322 file_name = "%s_%s.bin" % (product_id, fw_version)
323 fw_file_path = os.path.join(TOUCH_PATH, vendor.name, file_name)
324
325 if not os.path.exists(fw_file_path):
326 raise Exception(
327 "Touchscreen fw bin file doesn't exist at: %s" % fw_file_path)
328
329 files.append({
330 "destination": "/opt/google/touch/firmware/%s_%s" % (
331 vendor.name, file_name),
332 "source": os.path.join(project_name, fw_file_path),
333 "symlink": os.path.join("/lib/firmware", sym_link),
334 })
335
336 result = {}
337 _Set(files, result, 'files')
338 return result
339
340
341def _TransformBuildConfigs(config, config_files=ConfigFiles({}, {}, {}, None)):
David Burger7fd1dbe2020-03-26 09:26:55 -0600342 partners = dict([(x.id.value, x) for x in config.partners.value])
343 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600344 sw_configs = list(config.software_configs)
345 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
346
C Shapiroa0b766c2020-03-31 08:35:28 -0500347 if len(config.build_targets) != 1:
348 # Artifact of sharing the config_bundle for analysis and transforms.
349 # Integrated analysis of multiple programs/projects it the only time
350 # having multiple build targets would be valid.
351 raise Exception('Single build_target required for transform')
352
David Burger7fd1dbe2020-03-26 09:26:55 -0600353 results = {}
354 for hw_design in config.designs.value:
355 if config.device_brands.value:
356 device_brands = [x for x in config.device_brands.value
357 if x.design_id.value == hw_design.id.value]
358 else:
359 device_brands = [device_brand_pb2.DeviceBrand()]
360
361 for device_brand in device_brands:
362 # Brand config can be empty since platform JSON config allows it
363 brand_config = brand_config_pb2.BrandConfig()
364 if device_brand.id.value in brand_configs:
365 brand_config = brand_configs[device_brand.id.value]
366
367 for hw_design_config in hw_design.configs:
368 design_id = hw_design_config.id.value
369 sw_config_matches = [x for x in sw_configs
370 if x.design_config_id.value == design_id]
371 if len(sw_config_matches) == 1:
372 sw_config = sw_config_matches[0]
373 elif len(sw_config_matches) > 1:
374 raise Exception('Multiple software configs found for: %s' % design_id)
375 else:
376 raise Exception('Software config is required for: %s' % design_id)
377
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500378 program = _Lookup(hw_design.program_id, programs)
379 signer_configs = dict(
380 [(x.brand_id.value, x) for x in program.device_signer_configs])
381 device_signer_config = None
382 if signer_configs:
383 device_signer_config = _Lookup(device_brand.id, signer_configs)
384
C Shapiro90fda252020-04-17 14:34:57 -0500385 transformed_config = _TransformBuildConfig(
386 Config(
387 program=program,
388 hw_design=hw_design,
389 odm=_Lookup(hw_design.odm_id, partners),
390 hw_design_config=hw_design_config,
391 device_brand=device_brand,
392 device_signer_config=device_signer_config,
393 oem=_Lookup(device_brand.oem_id, partners),
394 sw_config=sw_config,
395 brand_config=brand_config,
396 build_target=config.build_targets[0]),
C Shapiro5bf23a72020-04-24 11:40:17 -0500397 config_files)
David Burger7fd1dbe2020-03-26 09:26:55 -0600398
399 config_json = json.dumps(transformed_config,
400 sort_keys=True,
401 indent=2,
402 separators=(',', ': '))
403
404 if config_json not in results:
405 results[config_json] = transformed_config
406
407 return list(results.values())
408
409
C Shapiro5bf23a72020-04-24 11:40:17 -0500410def _TransformBuildConfig(config, config_files):
David Burger7fd1dbe2020-03-26 09:26:55 -0600411 """Transforms Config instance into target platform JSON schema.
412
413 Args:
414 config: Config namedtuple
C Shapiro5bf23a72020-04-24 11:40:17 -0500415 config_files: Map to look up the generated config files.
David Burger7fd1dbe2020-03-26 09:26:55 -0600416
417 Returns:
418 Unique config payload based on the platform JSON schema.
419 """
420 result = {
421 'identity': _BuildIdentity(
422 config.sw_config.id_scan_config,
Andrew Lamb7806ce92020-04-07 10:22:17 -0600423 config.program,
David Burger7fd1dbe2020-03-26 09:26:55 -0600424 config.brand_config.scan_config),
425 'name': config.hw_design.name.lower(),
426 }
427
C Shapiro5bf23a72020-04-24 11:40:17 -0500428 _Set(_BuildArc(config, config_files), result, 'arc')
David Burger7fd1dbe2020-03-26 09:26:55 -0600429 _Set(_BuildAudio(config), result, 'audio')
C Shapiro5bf23a72020-04-24 11:40:17 -0500430 _Set(_BuildBluetooth(config, config_files.bluetooth), result, 'bluetooth')
David Burger7fd1dbe2020-03-26 09:26:55 -0600431 _Set(config.device_brand.brand_code, result, 'brand-code')
David Burger8aa8fa32020-04-14 08:30:34 -0600432 _Set(_BuildCamera(
433 config.hw_design_config.hardware_topology), result, 'camera')
David Burger7fd1dbe2020-03-26 09:26:55 -0600434 _Set(_BuildFirmware(config), result, 'firmware')
435 _Set(_BuildFwSigning(config), result, 'firmware-signing')
436 _Set(_BuildFingerprint(
437 config.hw_design_config.hardware_topology), result, 'fingerprint')
438 power_prefs = config.sw_config.power_config.preferences
439 power_prefs_map = dict(
440 (x.replace('_', '-'),
441 power_prefs[x]) for x in power_prefs)
442 _Set(power_prefs_map, result, 'power')
C Shapiro6830e6c2020-04-29 13:29:56 -0500443 _Set(config_files.dptf_file, result, 'thermal')
C Shapiro2b6d5332020-05-06 17:51:35 -0500444 _Set(config_files.touch_fw, result, 'touch')
David Burger7fd1dbe2020-03-26 09:26:55 -0600445
446 return result
447
448
449def WriteOutput(configs, output=None):
450 """Writes a list of configs to platform JSON format.
451
452 Args:
453 configs: List of config dicts defined in cros_config_schema.yaml
454 output: Target file output (if None, prints to stdout)
455 """
456 json_output = json.dumps(
457 {'chromeos': {
458 'configs': configs,
459 }},
460 sort_keys=True,
461 indent=2,
462 separators=(',', ': '))
463 if output:
464 with open(output, 'w') as output_stream:
465 # Using print function adds proper trailing newline.
466 print(json_output, file=output_stream)
467 else:
468 print(json_output)
469
470
C Shapiro90fda252020-04-17 14:34:57 -0500471def _BluetoothId(project_name, bt_comp):
472 return '_'.join([project_name,
473 bt_comp.vendor_id,
474 bt_comp.product_id,
475 bt_comp.bcd_device])
476
477
C Shapiro5bf23a72020-04-24 11:40:17 -0500478def _Feature(name, present):
479 attrib = {'name': name}
480 if present:
481 return etree.Element('feature', attrib=attrib)
482 else:
483 return etree.Element('unavailable-feature', attrib=attrib)
484
485
486def _AnyPresent(features):
487 return topology_pb2.HardwareFeatures.PRESENT in features;
488
489
490def _ArcHardwareFeatureId(design_config):
491 return design_config.id.value.lower().replace(':', '_')
492
493
C Shapiroea33cff2020-05-11 13:32:05 -0500494def _WriteArcHardwareFeatureFile(output_dir, file_name, config_content):
495 output = '%s/arc/%s' % (output_dir, file_name)
496 file_content = minidom.parseString(
497 config_content).toprettyxml(indent=' ', encoding='utf-8')
498
499 with open(output, 'wb') as f:
500 f.write(file_content)
501
502
C Shapiro5c877992020-04-29 12:11:28 -0500503def WriteArcHardwareFeatureFiles(config, output_dir, build_root_dir):
C Shapiro5bf23a72020-04-24 11:40:17 -0500504 """Writes ARC hardware_feature.xml files for each config
505
506 Args:
507 config: Source ConfigBundle to process.
508 output_dir: Path to the generated output.
C Shapiro5c877992020-04-29 12:11:28 -0500509 build_root_path: Path to the config file from portage's perspective.
C Shapiro5bf23a72020-04-24 11:40:17 -0500510 Returns:
511 dict that maps the design_config_id onto the correct file.
512 """
C Shapiro5bf23a72020-04-24 11:40:17 -0500513 result = {}
C Shapiroea33cff2020-05-11 13:32:05 -0500514 configs_by_design = {}
C Shapiro5bf23a72020-04-24 11:40:17 -0500515 for hw_design in config.designs.value:
516 for design_config in hw_design.configs:
517 hw_features = design_config.hardware_features
518 multi_camera = hw_features.camera.count == 2
519 touchscreen = _AnyPresent([hw_features.screen.touch_support])
520 acc = hw_features.accelerometer
521 gyro = hw_features.gyroscope
522 compass = hw_features.magnetometer
523 ls = hw_features.light_sensor
524 root = etree.Element('permissions')
525 root.extend([
526 _Feature('android.hardware.camera', multi_camera),
527 _Feature('android.hardware.camera.autofocus', multi_camera),
528 _Feature('android.hardware.sensor.accelerometer',
529 _AnyPresent(
530 [acc.lid_accelerometer, acc.base_accelerometer])),
531 _Feature('android.hardware.sensor.gyroscope',
532 _AnyPresent(
533 [gyro.lid_gyroscope, gyro.base_gyroscope])),
534 _Feature('android.hardware.sensor.compass',
535 _AnyPresent(
536 [compass.lid_magnetometer, compass.base_magnetometer])),
537 _Feature('android.hardware.sensor.light',
538 _AnyPresent(
539 [ls.lid_lightsensor, ls.base_lightsensor])),
540 _Feature('android.hardware.touchscreen', touchscreen),
541 _Feature('android.hardware.touchscreen.multitouch', touchscreen),
542 _Feature(
543 'android.hardware.touchscreen.multitouch.distinct', touchscreen),
544 _Feature(
545 'android.hardware.touchscreen.multitouch.jazzhand', touchscreen),
546 ])
547
C Shapiroea33cff2020-05-11 13:32:05 -0500548 design_name = hw_design.name.lower()
C Shapiro5bf23a72020-04-24 11:40:17 -0500549
C Shapiroea33cff2020-05-11 13:32:05 -0500550 # Constructs the following map:
551 # design_name -> config -> design_configs
552 # This allows any of the following file naming schemes:
553 # - All configs within a design share config (design_name prefix only)
554 # - Nobody shares (full design_name and config id prefix needed)
555 #
556 # Having shared configs when possible makes code reviews easier around
557 # the configs and makes debugging easier on the platform side.
558 config_content = etree.tostring(root)
559 arc_configs = configs_by_design.get(design_name, {})
560 design_configs = arc_configs.get(config_content, [])
561 design_configs.append(design_config)
562 arc_configs[config_content] = design_configs
563 configs_by_design[design_name] = arc_configs
C Shapiro9a3ac8c2020-04-25 07:49:21 -0500564
C Shapiroea33cff2020-05-11 13:32:05 -0500565 for design_name, unique_configs in configs_by_design.items():
566 for file_content, design_configs in unique_configs.items():
567 file_name = 'hardware_features_%s.xml' % design_name
568 if len(unique_configs) == 1:
569 _WriteArcHardwareFeatureFile(output_dir, file_name, file_content)
C Shapiro9a3ac8c2020-04-25 07:49:21 -0500570
C Shapiroea33cff2020-05-11 13:32:05 -0500571 for design_config in design_configs:
572 feature_id = _ArcHardwareFeatureId(design_config)
573 if len(unique_configs) > 1:
574 file_name = 'hardware_features_%s.xml' % feature_id
575 _WriteArcHardwareFeatureFile(output_dir, file_name, file_content)
576 result[feature_id] = {
577 'build-path': '%s/arc/%s' % (build_root_dir, file_name),
578 'system-path': '/etc/%s' % file_name,
579 }
C Shapiro5bf23a72020-04-24 11:40:17 -0500580 return result
581
582
C Shapiro5c877992020-04-29 12:11:28 -0500583def WriteBluetoothConfigFiles(config, output_dir, build_root_path):
C Shapiro90fda252020-04-17 14:34:57 -0500584 """Writes bluetooth conf files for every unique bluetooth chip.
585
586 Args:
587 config: Source ConfigBundle to process.
588 output_dir: Path to the generated output.
C Shapiro5c877992020-04-29 12:11:28 -0500589 build_root_path: Path to the config file from portage's perspective.
C Shapiro90fda252020-04-17 14:34:57 -0500590 Returns:
591 dict that maps the bluetooth component id onto the file config.
592 """
C Shapiro90fda252020-04-17 14:34:57 -0500593 result = {}
594 for hw_design in config.designs.value:
595 project_name = hw_design.name.lower()
596 for design_config in hw_design.configs:
C Shapiro74da76e2020-05-04 13:02:20 -0500597 bt_comp = design_config.hardware_features.bluetooth.component.usb
C Shapiro90fda252020-04-17 14:34:57 -0500598 if bt_comp.vendor_id:
599 bt_id = _BluetoothId(project_name, bt_comp)
600 result[bt_id] = {
C Shapiro5c877992020-04-29 12:11:28 -0500601 'build-path': '%s/bluetooth/%s.conf' % (build_root_path, bt_id),
C Shapiro90fda252020-04-17 14:34:57 -0500602 'system-path': '/etc/bluetooth/%s/main.conf' % bt_id,
603 }
604 bt_content = '''[General]
605DeviceID = bluetooth:%s:%s:%s''' % (bt_comp.vendor_id,
606 bt_comp.product_id,
607 bt_comp.bcd_device)
608
609 output = '%s/bluetooth/%s.conf' % (output_dir, bt_id)
610 with open(output, 'w') as output_stream:
611 # Using print function adds proper trailing newline.
612 print(bt_content, file=output_stream)
613 return result
614
615
David Burger7fd1dbe2020-03-26 09:26:55 -0600616def _ReadConfig(path):
David Burgerd4f32962020-05-02 12:07:40 -0600617 """Reads a ConfigBundle proto from a json pb file.
David Burgere6f76222020-04-27 11:08:01 -0600618
619 Args:
David Burgerd4f32962020-05-02 12:07:40 -0600620 path: Path to the file encoding the json pb proto.
David Burgere6f76222020-04-27 11:08:01 -0600621 """
622 config = config_bundle_pb2.ConfigBundle()
623 with open(path, 'r') as f:
624 return json_format.Parse(f.read(), config)
625
626
David Burger7fd1dbe2020-03-26 09:26:55 -0600627def _MergeConfigs(configs):
628 result = config_bundle_pb2.ConfigBundle()
629 for config in configs:
630 result.MergeFrom(config)
631
632 return result
633
634
635def Main(project_configs,
636 program_config,
637 output):
638 """Transforms source proto config into platform JSON.
639
640 Args:
641 project_configs: List of source project configs to transform.
642 program_config: Program config for the given set of projects.
643 output: Output file that will be generated by the transform.
644 """
C Shapiro90fda252020-04-17 14:34:57 -0500645 configs =_MergeConfigs(
646 [_ReadConfig(program_config)] +
647 [_ReadConfig(config) for config in project_configs])
C Shapiro5bf23a72020-04-24 11:40:17 -0500648 bluetooth_files = {}
649 arc_hw_feature_files = {}
C Shapiro2b6d5332020-05-06 17:51:35 -0500650 touch_fw = {}
C Shapiro6830e6c2020-04-29 13:29:56 -0500651 dptf_file = None
C Shapiro5bf23a72020-04-24 11:40:17 -0500652 output_dir = os.path.dirname(output)
C Shapiro5c877992020-04-29 12:11:28 -0500653 build_root_dir = output_dir
C Shapiro5c877992020-04-29 12:11:28 -0500654 if 'sw_build_config' in output_dir:
655 full_path = os.path.realpath(output)
C Shapiro6438fb32020-05-01 16:43:49 -0500656 project_name = re.match(
657 r'.*/(\w*)/sw_build_config/.*', full_path).groups(1)[0]
C Shapiro5c877992020-04-29 12:11:28 -0500658 # Projects don't know about each other until they are integrated into the
659 # build system. When this happens, the files need to be able to co-exist
660 # without any collisions. This prefixes the project name (which is how
661 # portage maps in the project), so project files co-exist and can be
662 # installed together.
663 # This is necessary to allow projects to share files at the program level
664 # without having portage file installation collisions.
665 build_root_dir = os.path.join(project_name, output_dir)
C Shapiro6830e6c2020-04-29 13:29:56 -0500666
C Shapiro7356bd62020-05-02 05:21:33 -0500667 if os.path.exists(DPTF_PATH):
668 project_dptf_path = os.path.join(project_name, 'dptf.dv')
669 dptf_file = {
670 'dptf-dv': project_dptf_path,
671 'files': [_File(os.path.join(project_name, DPTF_PATH),
672 os.path.join('/etc/dptf', project_dptf_path))]
673 }
C Shapiro2b6d5332020-05-06 17:51:35 -0500674 if os.path.exists(TOUCH_PATH):
675 touch_fw = _BuildTouchFileConfig(configs, project_name)
C Shapiro5bf23a72020-04-24 11:40:17 -0500676 if os.path.exists(os.path.join(output_dir, 'bluetooth')):
C Shapiro5c877992020-04-29 12:11:28 -0500677 bluetooth_files = WriteBluetoothConfigFiles(
678 configs, output_dir, build_root_dir)
C Shapiro5bf23a72020-04-24 11:40:17 -0500679 if os.path.exists(os.path.join(output_dir, 'arc')):
680 arc_hw_feature_files = WriteArcHardwareFeatureFiles(
C Shapiro5c877992020-04-29 12:11:28 -0500681 configs, output_dir, build_root_dir)
C Shapiro5bf23a72020-04-24 11:40:17 -0500682 config_files = ConfigFiles(
683 bluetooth=bluetooth_files,
684 arc_hw_features=arc_hw_feature_files,
C Shapiro2b6d5332020-05-06 17:51:35 -0500685 touch_fw=touch_fw,
C Shapiro6830e6c2020-04-29 13:29:56 -0500686 dptf_file=dptf_file
C Shapiro5bf23a72020-04-24 11:40:17 -0500687 )
688 WriteOutput(_TransformBuildConfigs(configs, config_files), output)
David Burger7fd1dbe2020-03-26 09:26:55 -0600689
690
691def main(argv=None):
692 """Main program which parses args and runs
693
694 Args:
695 argv: List of command line arguments, if None uses sys.argv.
696 """
697 if argv is None:
698 argv = sys.argv[1:]
699 opts = ParseArgs(argv)
700 Main(opts.project_configs, opts.program_config, opts.output)
701
702
703if __name__ == '__main__':
704 sys.exit(main(sys.argv[1:]))