blob: f236c5e1baeb37e1a5604acd7ee00a693efe79c1 [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]
C Shapiroa3f202d2020-05-19 08:18:45 -0500101 topology = config.hw_design_config.hardware_topology
102 ppi = topology.screen.hardware_feature.screen.panel_properties.pixels_per_in
103 # Only set for high resolution displays
104 if ppi and ppi > 250:
105 result['scale'] = ppi
C Shapiro5bf23a72020-04-24 11:40:17 -0500106 return result
David Burger7fd1dbe2020-03-26 09:26:55 -0600107
C Shapiro90fda252020-04-17 14:34:57 -0500108def _BuildBluetooth(config, bluetooth_files):
109 bt_flags = config.sw_config.bluetooth_config.flags
110 # Convert to native map (from proto wrapper)
111 bt_flags_map = dict(bt_flags)
112 result = {}
113 if bt_flags_map:
114 result['flags'] = bt_flags_map
C Shapiro74da76e2020-05-04 13:02:20 -0500115 bt_comp = config.hw_design_config.hardware_features.bluetooth.component.usb
C Shapiro90fda252020-04-17 14:34:57 -0500116 if bt_comp.vendor_id:
117 bt_id = _BluetoothId(config.hw_design.name.lower(), bt_comp)
118 if bt_id in bluetooth_files:
119 result['config'] = bluetooth_files[bt_id]
120 return result
121
David Burger7fd1dbe2020-03-26 09:26:55 -0600122
123def _BuildFingerprint(hw_topology):
Andrew Lambc2c55462020-04-06 08:43:34 -0600124 if hw_topology.HasField('fingerprint'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600125 fp = hw_topology.fingerprint.hardware_feature.fingerprint
David Burger92609a32020-04-23 10:38:50 -0600126 result = {}
127 if fp.location != topology_pb2.HardwareFeatures.Fingerprint.NOT_PRESENT:
128 location = fp.Location.DESCRIPTOR.values_by_number[fp.location].name
129 result['sensor-location'] = location.lower().replace('_', '-')
130 if fp.board:
131 result['board'] = fp.board
David Burger7fd1dbe2020-03-26 09:26:55 -0600132 return result
133
134
135def _FwBcsPath(payload):
136 if payload and payload.firmware_image_name:
137 return 'bcs://%s.%d.%d.0.tbz2' % (
138 payload.firmware_image_name,
139 payload.version.major,
140 payload.version.minor)
141
142
143def _FwBuildTarget(payload):
144 if payload:
145 return payload.build_target_name
146
147
148def _BuildFirmware(config):
David Burgerb70b6762020-05-21 12:14:59 -0600149 """Returns firmware config, or None if no build targets."""
Andrew Lamb3da156d2020-04-16 16:00:56 -0600150 fw_payload_config = config.sw_config.firmware
151 fw_build_config = config.sw_config.firmware_build_config
152 main_ro = fw_payload_config.main_ro_payload
153 main_rw = fw_payload_config.main_rw_payload
154 ec_ro = fw_payload_config.ec_ro_payload
155 pd_ro = fw_payload_config.pd_ro_payload
David Burger7fd1dbe2020-03-26 09:26:55 -0600156
157 build_targets = {}
Andrew Lamb3da156d2020-04-16 16:00:56 -0600158
Andrew Lambf8954ee2020-04-21 10:24:40 -0600159 _Set(fw_build_config.build_targets.depthcharge, build_targets, 'depthcharge')
160 _Set(fw_build_config.build_targets.coreboot, build_targets, 'coreboot')
161 _Set(fw_build_config.build_targets.ec, build_targets, 'ec')
162 _Set(
163 list(fw_build_config.build_targets.ec_extras), build_targets, 'ec_extras')
164 _Set(fw_build_config.build_targets.libpayload, build_targets, 'libpayload')
David Burger7fd1dbe2020-03-26 09:26:55 -0600165
David Burgerb70b6762020-05-21 12:14:59 -0600166 if not build_targets:
167 return None
168
David Burger7fd1dbe2020-03-26 09:26:55 -0600169 result = {
170 'bcs-overlay': config.build_target.overlay_name,
171 'build-targets': build_targets,
David Burger7fd1dbe2020-03-26 09:26:55 -0600172 }
Andrew Lamb883fa042020-04-06 11:37:22 -0600173
174 _Set(main_ro.firmware_image_name.lower(), result, 'image-name')
175
Andrew Lamb883fa042020-04-06 11:37:22 -0600176 _Set(_FwBcsPath(main_ro), result, 'main-ro-image')
177 _Set(_FwBcsPath(main_rw), result, 'main-rw-image')
178 _Set(_FwBcsPath(ec_ro), result, 'ec-ro-image')
179 _Set(_FwBcsPath(pd_ro), result, 'pd-ro-image')
David Burger7fd1dbe2020-03-26 09:26:55 -0600180
Andrew Lambf39fbe82020-04-13 16:14:33 -0600181 _Set(
182 config.hw_design_config.hardware_features.fw_config.value,
183 result,
184 'firmware-config',
185 )
186
David Burger7fd1dbe2020-03-26 09:26:55 -0600187 return result
188
189
190def _BuildFwSigning(config):
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500191 if config.sw_config.firmware and config.device_signer_config:
David Burger68e0d142020-05-15 17:29:33 -0600192 hw_design = config.hw_design.name.lower()
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500193 return {
194 'key-id': config.device_signer_config.key_id,
C Shapiro10e9a612020-05-19 17:06:43 -0500195 # TODO(shapiroc): Need to fix for whitelabel.
196 # Whitelabel will collide on unique signature-id values.
David Burger68e0d142020-05-15 17:29:33 -0600197 'signature-id': hw_design,
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500198 }
199 return {}
David Burger7fd1dbe2020-03-26 09:26:55 -0600200
201
202def _File(source, destination):
203 return {
204 'destination': destination,
205 'source': source
206 }
207
208
209def _BuildAudio(config):
210 alsa_path = '/usr/share/alsa/ucm'
211 cras_path = '/etc/cras'
212 project_name = config.hw_design.name.lower()
David Burger43250662020-05-07 11:21:50 -0600213 program_name = config.program.name.lower()
Andrew Lamb7d536782020-04-07 10:23:55 -0600214 if not config.sw_config.HasField('audio_config'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600215 return {}
216 audio = config.sw_config.audio_config
217 card = audio.card_name
David Burger599ff7b2020-04-06 16:29:31 -0600218 card_with_suffix = audio.card_name
219 if audio.ucm_suffix:
220 card_with_suffix += '.' + audio.ucm_suffix
David Burger7fd1dbe2020-03-26 09:26:55 -0600221 files = []
222 if audio.ucm_file:
David Burger599ff7b2020-04-06 16:29:31 -0600223 files.append(_File(
224 audio.ucm_file,
225 '%s/%s/HiFi.conf' % (alsa_path, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600226 if audio.ucm_master_file:
227 files.append(_File(
David Burger599ff7b2020-04-06 16:29:31 -0600228 audio.ucm_master_file,
229 '%s/%s/%s.conf' % (alsa_path, card_with_suffix, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600230 if audio.card_config_file:
231 files.append(_File(
232 audio.card_config_file, '%s/%s/%s' % (cras_path, project_name, card)))
233 if audio.dsp_file:
234 files.append(
David Burger2e254902020-04-02 16:56:01 -0600235 _File(audio.dsp_file, '%s/%s/dsp.ini' % (cras_path, project_name)))
David Burgere1a37492020-05-06 09:29:24 -0600236 if audio.module_file:
237 files.append(
David Burger43250662020-05-07 11:21:50 -0600238 _File(audio.module_file, '/etc/modprobe.d/alsa-%s.conf' % program_name))
David Burgere1a37492020-05-06 09:29:24 -0600239 if audio.board_file:
240 files.append(
241 _File(audio.board_file, '%s/%s/board.ini' % (cras_path, project_name)))
David Burger599ff7b2020-04-06 16:29:31 -0600242
243 result = {
David Burger7fd1dbe2020-03-26 09:26:55 -0600244 'main': {
245 'cras-config-dir': project_name,
246 'files': files,
247 }
248 }
David Burger599ff7b2020-04-06 16:29:31 -0600249 if audio.ucm_suffix:
David Burger03cdcbd2020-04-13 13:54:48 -0600250 result['main']['ucm-suffix'] = audio.ucm_suffix
David Burger599ff7b2020-04-06 16:29:31 -0600251
252 return result
David Burger7fd1dbe2020-03-26 09:26:55 -0600253
254
David Burger8aa8fa32020-04-14 08:30:34 -0600255def _BuildCamera(hw_topology):
256 if hw_topology.HasField('camera'):
257 camera = hw_topology.camera.hardware_feature.camera
258 result = {}
259 if camera.count.value:
260 result['count'] = camera.count.value
261 return result
262
263
Andrew Lamb7806ce92020-04-07 10:22:17 -0600264def _BuildIdentity(hw_scan_config, program, brand_scan_config=None):
David Burger7fd1dbe2020-03-26 09:26:55 -0600265 identity = {}
266 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
267 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
Andrew Lamb7806ce92020-04-07 10:22:17 -0600268 # 'platform-name' is needed to support 'mosys platform name'. Clients should
269 # longer require platform name, but set it here for backwards compatibility.
270 _Set(program.name, identity, 'platform-name')
David Burger7fd1dbe2020-03-26 09:26:55 -0600271 # ARM architecture
272 _Set(hw_scan_config.device_tree_compatible_match, identity,
273 'device-tree-compatible-match')
274
275 if brand_scan_config:
276 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
277
278 return identity
279
280
281def _Lookup(id_value, id_map):
282 if id_value.value:
283 key = id_value.value
284 if key in id_map:
285 return id_map[id_value.value]
286 error = 'Failed to lookup %s with value: %s' % (
287 id_value.__class__.__name__.replace('Id', ''), key)
288 print(error)
289 print('Check the config contents provided:')
290 pp = pprint.PrettyPrinter(indent=4)
291 pp.pprint(id_map)
292 raise Exception(error)
293
294
C Shapiro2b6d5332020-05-06 17:51:35 -0500295def _BuildTouchFileConfig(config, project_name):
296 partners = dict([(x.id.value, x) for x in config.partners.value])
297 files = []
298 for comp in config.components:
C Shapiro4813be62020-05-13 17:31:58 -0500299 touch = comp.touchscreen
300 # Everything is the same for Touch screen/pad, except different fields
301 if comp.HasField('touchpad'):
302 touch = comp.touchpad
303 if touch.product_id:
C Shapiro2b6d5332020-05-06 17:51:35 -0500304 vendor = _Lookup(comp.manufacturer_id, partners)
305 if not vendor:
306 raise Exception(
C Shapiro4813be62020-05-13 17:31:58 -0500307 "Manufacturer must be set for touch device %s" % comp.id.value)
C Shapiro2b6d5332020-05-06 17:51:35 -0500308
C Shapiro4813be62020-05-13 17:31:58 -0500309 product_id = touch.product_id
310 fw_version = touch.fw_version
C Shapiro2b6d5332020-05-06 17:51:35 -0500311
C Shapiro5c6fc212020-05-13 16:32:09 -0500312 touch_vendor = vendor.touch_vendor
313 sym_link = touch_vendor.fw_file_format.format(
C Shapiro2b6d5332020-05-06 17:51:35 -0500314 vendor_name = vendor.name,
C Shapiro5c6fc212020-05-13 16:32:09 -0500315 vendor_id = touch_vendor.vendor_id,
C Shapiro2b6d5332020-05-06 17:51:35 -0500316 product_id = product_id,
317 fw_version = fw_version,
C Shapiro4813be62020-05-13 17:31:58 -0500318 product_series = touch.product_series
C Shapiro2b6d5332020-05-06 17:51:35 -0500319 )
320
321 file_name = "%s_%s.bin" % (product_id, fw_version)
322 fw_file_path = os.path.join(TOUCH_PATH, vendor.name, file_name)
323
324 if not os.path.exists(fw_file_path):
325 raise Exception(
326 "Touchscreen fw bin file doesn't exist at: %s" % fw_file_path)
327
328 files.append({
329 "destination": "/opt/google/touch/firmware/%s_%s" % (
330 vendor.name, file_name),
331 "source": os.path.join(project_name, fw_file_path),
332 "symlink": os.path.join("/lib/firmware", sym_link),
333 })
334
335 result = {}
336 _Set(files, result, 'files')
337 return result
338
339
340def _TransformBuildConfigs(config, config_files=ConfigFiles({}, {}, {}, None)):
David Burger7fd1dbe2020-03-26 09:26:55 -0600341 partners = dict([(x.id.value, x) for x in config.partners.value])
342 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600343 sw_configs = list(config.software_configs)
344 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
345
C Shapiroa0b766c2020-03-31 08:35:28 -0500346 if len(config.build_targets) != 1:
347 # Artifact of sharing the config_bundle for analysis and transforms.
348 # Integrated analysis of multiple programs/projects it the only time
349 # having multiple build targets would be valid.
350 raise Exception('Single build_target required for transform')
351
David Burger7fd1dbe2020-03-26 09:26:55 -0600352 results = {}
353 for hw_design in config.designs.value:
354 if config.device_brands.value:
355 device_brands = [x for x in config.device_brands.value
356 if x.design_id.value == hw_design.id.value]
357 else:
358 device_brands = [device_brand_pb2.DeviceBrand()]
359
360 for device_brand in device_brands:
361 # Brand config can be empty since platform JSON config allows it
362 brand_config = brand_config_pb2.BrandConfig()
363 if device_brand.id.value in brand_configs:
364 brand_config = brand_configs[device_brand.id.value]
365
366 for hw_design_config in hw_design.configs:
367 design_id = hw_design_config.id.value
368 sw_config_matches = [x for x in sw_configs
369 if x.design_config_id.value == design_id]
370 if len(sw_config_matches) == 1:
371 sw_config = sw_config_matches[0]
372 elif len(sw_config_matches) > 1:
373 raise Exception('Multiple software configs found for: %s' % design_id)
374 else:
375 raise Exception('Software config is required for: %s' % design_id)
376
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500377 program = _Lookup(hw_design.program_id, programs)
C Shapiroadefd7c2020-05-19 16:37:21 -0500378 signer_configs_by_design = {}
379 signer_configs_by_brand = {}
380 for signer_config in program.device_signer_configs:
381 design_id = signer_config.design_id.value
382 brand_id = signer_config.brand_id.value
383 if design_id:
384 signer_configs_by_design[design_id] = signer_config
385 elif brand_id:
386 signer_configs_by_brand[brand_id] = signer_config
387 else:
388 raise Exception('No ID found for signer config: %s' % signer_config)
389
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500390 device_signer_config = None
C Shapiroadefd7c2020-05-19 16:37:21 -0500391 if signer_configs_by_design or signer_configs_by_brand:
392 design_id = hw_design.id.value
393 brand_id = device_brand.id.value
394 if design_id in signer_configs_by_design:
395 device_signer_config = signer_configs_by_design[design_id]
396 elif brand_id in signer_configs_by_brand:
397 device_signer_config = signer_configs_by_brand[brand_id]
398 else:
399 # Assume that if signer configs are set, every config is setup
400 raise Exception(
401 'Signer config missing for design: %s, brand: %s' % (
402 design_id, brand_id))
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500403
C Shapiro90fda252020-04-17 14:34:57 -0500404 transformed_config = _TransformBuildConfig(
405 Config(
406 program=program,
407 hw_design=hw_design,
408 odm=_Lookup(hw_design.odm_id, partners),
409 hw_design_config=hw_design_config,
410 device_brand=device_brand,
411 device_signer_config=device_signer_config,
412 oem=_Lookup(device_brand.oem_id, partners),
413 sw_config=sw_config,
414 brand_config=brand_config,
415 build_target=config.build_targets[0]),
C Shapiro5bf23a72020-04-24 11:40:17 -0500416 config_files)
David Burger7fd1dbe2020-03-26 09:26:55 -0600417
418 config_json = json.dumps(transformed_config,
419 sort_keys=True,
420 indent=2,
421 separators=(',', ': '))
422
423 if config_json not in results:
424 results[config_json] = transformed_config
425
426 return list(results.values())
427
428
C Shapiro5bf23a72020-04-24 11:40:17 -0500429def _TransformBuildConfig(config, config_files):
David Burger7fd1dbe2020-03-26 09:26:55 -0600430 """Transforms Config instance into target platform JSON schema.
431
432 Args:
433 config: Config namedtuple
C Shapiro5bf23a72020-04-24 11:40:17 -0500434 config_files: Map to look up the generated config files.
David Burger7fd1dbe2020-03-26 09:26:55 -0600435
436 Returns:
437 Unique config payload based on the platform JSON schema.
438 """
439 result = {
440 'identity': _BuildIdentity(
441 config.sw_config.id_scan_config,
Andrew Lamb7806ce92020-04-07 10:22:17 -0600442 config.program,
David Burger7fd1dbe2020-03-26 09:26:55 -0600443 config.brand_config.scan_config),
444 'name': config.hw_design.name.lower(),
445 }
446
C Shapiro5bf23a72020-04-24 11:40:17 -0500447 _Set(_BuildArc(config, config_files), result, 'arc')
David Burger7fd1dbe2020-03-26 09:26:55 -0600448 _Set(_BuildAudio(config), result, 'audio')
C Shapiro5bf23a72020-04-24 11:40:17 -0500449 _Set(_BuildBluetooth(config, config_files.bluetooth), result, 'bluetooth')
David Burger7fd1dbe2020-03-26 09:26:55 -0600450 _Set(config.device_brand.brand_code, result, 'brand-code')
David Burger8aa8fa32020-04-14 08:30:34 -0600451 _Set(_BuildCamera(
452 config.hw_design_config.hardware_topology), result, 'camera')
David Burger7fd1dbe2020-03-26 09:26:55 -0600453 _Set(_BuildFirmware(config), result, 'firmware')
454 _Set(_BuildFwSigning(config), result, 'firmware-signing')
455 _Set(_BuildFingerprint(
456 config.hw_design_config.hardware_topology), result, 'fingerprint')
457 power_prefs = config.sw_config.power_config.preferences
458 power_prefs_map = dict(
459 (x.replace('_', '-'),
460 power_prefs[x]) for x in power_prefs)
461 _Set(power_prefs_map, result, 'power')
C Shapiro6830e6c2020-04-29 13:29:56 -0500462 _Set(config_files.dptf_file, result, 'thermal')
C Shapiro2b6d5332020-05-06 17:51:35 -0500463 _Set(config_files.touch_fw, result, 'touch')
David Burger7fd1dbe2020-03-26 09:26:55 -0600464
465 return result
466
467
468def WriteOutput(configs, output=None):
469 """Writes a list of configs to platform JSON format.
470
471 Args:
472 configs: List of config dicts defined in cros_config_schema.yaml
473 output: Target file output (if None, prints to stdout)
474 """
475 json_output = json.dumps(
476 {'chromeos': {
477 'configs': configs,
478 }},
479 sort_keys=True,
480 indent=2,
481 separators=(',', ': '))
482 if output:
483 with open(output, 'w') as output_stream:
484 # Using print function adds proper trailing newline.
485 print(json_output, file=output_stream)
486 else:
487 print(json_output)
488
489
C Shapiro90fda252020-04-17 14:34:57 -0500490def _BluetoothId(project_name, bt_comp):
491 return '_'.join([project_name,
492 bt_comp.vendor_id,
493 bt_comp.product_id,
494 bt_comp.bcd_device])
495
496
C Shapiro5bf23a72020-04-24 11:40:17 -0500497def _Feature(name, present):
498 attrib = {'name': name}
499 if present:
500 return etree.Element('feature', attrib=attrib)
501 else:
502 return etree.Element('unavailable-feature', attrib=attrib)
503
504
505def _AnyPresent(features):
506 return topology_pb2.HardwareFeatures.PRESENT in features;
507
508
509def _ArcHardwareFeatureId(design_config):
510 return design_config.id.value.lower().replace(':', '_')
511
512
C Shapiroea33cff2020-05-11 13:32:05 -0500513def _WriteArcHardwareFeatureFile(output_dir, file_name, config_content):
David Burger77a1d312020-05-23 16:05:45 -0600514 output_dir += '/arc'
515 os.makedirs(output_dir, exist_ok=True)
516 output = '%s/%s' % (output_dir, file_name)
C Shapiroea33cff2020-05-11 13:32:05 -0500517 file_content = minidom.parseString(
518 config_content).toprettyxml(indent=' ', encoding='utf-8')
519
520 with open(output, 'wb') as f:
521 f.write(file_content)
522
523
C Shapiro5c877992020-04-29 12:11:28 -0500524def WriteArcHardwareFeatureFiles(config, output_dir, build_root_dir):
C Shapiro5bf23a72020-04-24 11:40:17 -0500525 """Writes ARC hardware_feature.xml files for each config
526
527 Args:
528 config: Source ConfigBundle to process.
529 output_dir: Path to the generated output.
C Shapiro5c877992020-04-29 12:11:28 -0500530 build_root_path: Path to the config file from portage's perspective.
C Shapiro5bf23a72020-04-24 11:40:17 -0500531 Returns:
532 dict that maps the design_config_id onto the correct file.
533 """
C Shapiro5bf23a72020-04-24 11:40:17 -0500534 result = {}
C Shapiroea33cff2020-05-11 13:32:05 -0500535 configs_by_design = {}
C Shapiro5bf23a72020-04-24 11:40:17 -0500536 for hw_design in config.designs.value:
537 for design_config in hw_design.configs:
538 hw_features = design_config.hardware_features
539 multi_camera = hw_features.camera.count == 2
540 touchscreen = _AnyPresent([hw_features.screen.touch_support])
541 acc = hw_features.accelerometer
542 gyro = hw_features.gyroscope
543 compass = hw_features.magnetometer
544 ls = hw_features.light_sensor
545 root = etree.Element('permissions')
546 root.extend([
547 _Feature('android.hardware.camera', multi_camera),
548 _Feature('android.hardware.camera.autofocus', multi_camera),
549 _Feature('android.hardware.sensor.accelerometer',
550 _AnyPresent(
551 [acc.lid_accelerometer, acc.base_accelerometer])),
552 _Feature('android.hardware.sensor.gyroscope',
553 _AnyPresent(
554 [gyro.lid_gyroscope, gyro.base_gyroscope])),
555 _Feature('android.hardware.sensor.compass',
556 _AnyPresent(
557 [compass.lid_magnetometer, compass.base_magnetometer])),
558 _Feature('android.hardware.sensor.light',
559 _AnyPresent(
560 [ls.lid_lightsensor, ls.base_lightsensor])),
561 _Feature('android.hardware.touchscreen', touchscreen),
562 _Feature('android.hardware.touchscreen.multitouch', touchscreen),
563 _Feature(
564 'android.hardware.touchscreen.multitouch.distinct', touchscreen),
565 _Feature(
566 'android.hardware.touchscreen.multitouch.jazzhand', touchscreen),
567 ])
568
C Shapiroea33cff2020-05-11 13:32:05 -0500569 design_name = hw_design.name.lower()
C Shapiro5bf23a72020-04-24 11:40:17 -0500570
C Shapiroea33cff2020-05-11 13:32:05 -0500571 # Constructs the following map:
572 # design_name -> config -> design_configs
573 # This allows any of the following file naming schemes:
574 # - All configs within a design share config (design_name prefix only)
575 # - Nobody shares (full design_name and config id prefix needed)
576 #
577 # Having shared configs when possible makes code reviews easier around
578 # the configs and makes debugging easier on the platform side.
579 config_content = etree.tostring(root)
580 arc_configs = configs_by_design.get(design_name, {})
581 design_configs = arc_configs.get(config_content, [])
582 design_configs.append(design_config)
583 arc_configs[config_content] = design_configs
584 configs_by_design[design_name] = arc_configs
C Shapiro9a3ac8c2020-04-25 07:49:21 -0500585
C Shapiroea33cff2020-05-11 13:32:05 -0500586 for design_name, unique_configs in configs_by_design.items():
587 for file_content, design_configs in unique_configs.items():
588 file_name = 'hardware_features_%s.xml' % design_name
589 if len(unique_configs) == 1:
590 _WriteArcHardwareFeatureFile(output_dir, file_name, file_content)
C Shapiro9a3ac8c2020-04-25 07:49:21 -0500591
C Shapiroea33cff2020-05-11 13:32:05 -0500592 for design_config in design_configs:
593 feature_id = _ArcHardwareFeatureId(design_config)
594 if len(unique_configs) > 1:
595 file_name = 'hardware_features_%s.xml' % feature_id
596 _WriteArcHardwareFeatureFile(output_dir, file_name, file_content)
597 result[feature_id] = {
598 'build-path': '%s/arc/%s' % (build_root_dir, file_name),
599 'system-path': '/etc/%s' % file_name,
600 }
C Shapiro5bf23a72020-04-24 11:40:17 -0500601 return result
602
603
C Shapiro5c877992020-04-29 12:11:28 -0500604def WriteBluetoothConfigFiles(config, output_dir, build_root_path):
C Shapiro90fda252020-04-17 14:34:57 -0500605 """Writes bluetooth conf files for every unique bluetooth chip.
606
607 Args:
608 config: Source ConfigBundle to process.
609 output_dir: Path to the generated output.
C Shapiro5c877992020-04-29 12:11:28 -0500610 build_root_path: Path to the config file from portage's perspective.
C Shapiro90fda252020-04-17 14:34:57 -0500611 Returns:
612 dict that maps the bluetooth component id onto the file config.
613 """
David Burger77a1d312020-05-23 16:05:45 -0600614 output_dir += '/bluetooth'
C Shapiro90fda252020-04-17 14:34:57 -0500615 result = {}
616 for hw_design in config.designs.value:
617 project_name = hw_design.name.lower()
618 for design_config in hw_design.configs:
C Shapiro74da76e2020-05-04 13:02:20 -0500619 bt_comp = design_config.hardware_features.bluetooth.component.usb
C Shapiro90fda252020-04-17 14:34:57 -0500620 if bt_comp.vendor_id:
621 bt_id = _BluetoothId(project_name, bt_comp)
622 result[bt_id] = {
C Shapiro5c877992020-04-29 12:11:28 -0500623 'build-path': '%s/bluetooth/%s.conf' % (build_root_path, bt_id),
C Shapiro90fda252020-04-17 14:34:57 -0500624 'system-path': '/etc/bluetooth/%s/main.conf' % bt_id,
625 }
626 bt_content = '''[General]
627DeviceID = bluetooth:%s:%s:%s''' % (bt_comp.vendor_id,
628 bt_comp.product_id,
629 bt_comp.bcd_device)
630
David Burger77a1d312020-05-23 16:05:45 -0600631 os.makedirs(output_dir, exist_ok=True)
632 output = '%s/%s.conf' % (output_dir, bt_id)
C Shapiro90fda252020-04-17 14:34:57 -0500633 with open(output, 'w') as output_stream:
634 # Using print function adds proper trailing newline.
635 print(bt_content, file=output_stream)
636 return result
637
638
David Burger7fd1dbe2020-03-26 09:26:55 -0600639def _ReadConfig(path):
David Burgerd4f32962020-05-02 12:07:40 -0600640 """Reads a ConfigBundle proto from a json pb file.
David Burgere6f76222020-04-27 11:08:01 -0600641
642 Args:
David Burgerd4f32962020-05-02 12:07:40 -0600643 path: Path to the file encoding the json pb proto.
David Burgere6f76222020-04-27 11:08:01 -0600644 """
645 config = config_bundle_pb2.ConfigBundle()
646 with open(path, 'r') as f:
647 return json_format.Parse(f.read(), config)
648
649
David Burger7fd1dbe2020-03-26 09:26:55 -0600650def _MergeConfigs(configs):
651 result = config_bundle_pb2.ConfigBundle()
652 for config in configs:
653 result.MergeFrom(config)
654
655 return result
656
657
658def Main(project_configs,
659 program_config,
660 output):
661 """Transforms source proto config into platform JSON.
662
663 Args:
664 project_configs: List of source project configs to transform.
665 program_config: Program config for the given set of projects.
666 output: Output file that will be generated by the transform.
667 """
C Shapiro90fda252020-04-17 14:34:57 -0500668 configs =_MergeConfigs(
669 [_ReadConfig(program_config)] +
670 [_ReadConfig(config) for config in project_configs])
C Shapiro5bf23a72020-04-24 11:40:17 -0500671 bluetooth_files = {}
672 arc_hw_feature_files = {}
C Shapiro2b6d5332020-05-06 17:51:35 -0500673 touch_fw = {}
C Shapiro6830e6c2020-04-29 13:29:56 -0500674 dptf_file = None
C Shapiro5bf23a72020-04-24 11:40:17 -0500675 output_dir = os.path.dirname(output)
C Shapiro5c877992020-04-29 12:11:28 -0500676 build_root_dir = output_dir
C Shapiro5c877992020-04-29 12:11:28 -0500677 if 'sw_build_config' in output_dir:
678 full_path = os.path.realpath(output)
C Shapiro6438fb32020-05-01 16:43:49 -0500679 project_name = re.match(
680 r'.*/(\w*)/sw_build_config/.*', full_path).groups(1)[0]
C Shapiro5c877992020-04-29 12:11:28 -0500681 # Projects don't know about each other until they are integrated into the
682 # build system. When this happens, the files need to be able to co-exist
683 # without any collisions. This prefixes the project name (which is how
684 # portage maps in the project), so project files co-exist and can be
685 # installed together.
686 # This is necessary to allow projects to share files at the program level
687 # without having portage file installation collisions.
688 build_root_dir = os.path.join(project_name, output_dir)
C Shapiro6830e6c2020-04-29 13:29:56 -0500689
C Shapiro7356bd62020-05-02 05:21:33 -0500690 if os.path.exists(DPTF_PATH):
691 project_dptf_path = os.path.join(project_name, 'dptf.dv')
692 dptf_file = {
693 'dptf-dv': project_dptf_path,
694 'files': [_File(os.path.join(project_name, DPTF_PATH),
695 os.path.join('/etc/dptf', project_dptf_path))]
696 }
C Shapiro2b6d5332020-05-06 17:51:35 -0500697 if os.path.exists(TOUCH_PATH):
698 touch_fw = _BuildTouchFileConfig(configs, project_name)
David Burger77a1d312020-05-23 16:05:45 -0600699 bluetooth_files = WriteBluetoothConfigFiles(
700 configs, output_dir, build_root_dir)
701 arc_hw_feature_files = WriteArcHardwareFeatureFiles(
702 configs, output_dir, build_root_dir)
C Shapiro5bf23a72020-04-24 11:40:17 -0500703 config_files = ConfigFiles(
704 bluetooth=bluetooth_files,
705 arc_hw_features=arc_hw_feature_files,
C Shapiro2b6d5332020-05-06 17:51:35 -0500706 touch_fw=touch_fw,
C Shapiro6830e6c2020-04-29 13:29:56 -0500707 dptf_file=dptf_file
C Shapiro5bf23a72020-04-24 11:40:17 -0500708 )
709 WriteOutput(_TransformBuildConfigs(configs, config_files), output)
David Burger7fd1dbe2020-03-26 09:26:55 -0600710
711
712def main(argv=None):
713 """Main program which parses args and runs
714
715 Args:
716 argv: List of command line arguments, if None uses sys.argv.
717 """
718 if argv is None:
719 argv = sys.argv[1:]
720 opts = ParseArgs(argv)
721 Main(opts.project_configs, opts.program_config, opts.output)
722
723
724if __name__ == '__main__':
725 sys.exit(main(sys.argv[1:]))