blob: 2087a02945d9756f84bef0785ddd6599d6ae1fd2 [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:
183 return {
184 'key-id': config.device_signer_config.key_id,
185 'signature-id': config.hw_design.name.lower(),
186 }
187 return {}
David Burger7fd1dbe2020-03-26 09:26:55 -0600188
189
190def _File(source, destination):
191 return {
192 'destination': destination,
193 'source': source
194 }
195
196
197def _BuildAudio(config):
198 alsa_path = '/usr/share/alsa/ucm'
199 cras_path = '/etc/cras'
200 project_name = config.hw_design.name.lower()
Andrew Lamb7d536782020-04-07 10:23:55 -0600201 if not config.sw_config.HasField('audio_config'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600202 return {}
203 audio = config.sw_config.audio_config
204 card = audio.card_name
David Burger599ff7b2020-04-06 16:29:31 -0600205 card_with_suffix = audio.card_name
206 if audio.ucm_suffix:
207 card_with_suffix += '.' + audio.ucm_suffix
David Burger7fd1dbe2020-03-26 09:26:55 -0600208 files = []
209 if audio.ucm_file:
David Burger599ff7b2020-04-06 16:29:31 -0600210 files.append(_File(
211 audio.ucm_file,
212 '%s/%s/HiFi.conf' % (alsa_path, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600213 if audio.ucm_master_file:
214 files.append(_File(
David Burger599ff7b2020-04-06 16:29:31 -0600215 audio.ucm_master_file,
216 '%s/%s/%s.conf' % (alsa_path, card_with_suffix, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600217 if audio.card_config_file:
218 files.append(_File(
219 audio.card_config_file, '%s/%s/%s' % (cras_path, project_name, card)))
220 if audio.dsp_file:
221 files.append(
David Burger2e254902020-04-02 16:56:01 -0600222 _File(audio.dsp_file, '%s/%s/dsp.ini' % (cras_path, project_name)))
David Burgere1a37492020-05-06 09:29:24 -0600223 if audio.module_file:
224 files.append(
225 _File(audio.module_file, '/etc/modprobe.d/alsa-%s.conf' % project_name))
226 if audio.board_file:
227 files.append(
228 _File(audio.board_file, '%s/%s/board.ini' % (cras_path, project_name)))
David Burger599ff7b2020-04-06 16:29:31 -0600229
230 result = {
David Burger7fd1dbe2020-03-26 09:26:55 -0600231 'main': {
232 'cras-config-dir': project_name,
233 'files': files,
234 }
235 }
David Burger599ff7b2020-04-06 16:29:31 -0600236 if audio.ucm_suffix:
David Burger03cdcbd2020-04-13 13:54:48 -0600237 result['main']['ucm-suffix'] = audio.ucm_suffix
David Burger599ff7b2020-04-06 16:29:31 -0600238
239 return result
David Burger7fd1dbe2020-03-26 09:26:55 -0600240
241
David Burger8aa8fa32020-04-14 08:30:34 -0600242def _BuildCamera(hw_topology):
243 if hw_topology.HasField('camera'):
244 camera = hw_topology.camera.hardware_feature.camera
245 result = {}
246 if camera.count.value:
247 result['count'] = camera.count.value
248 return result
249
250
Andrew Lamb7806ce92020-04-07 10:22:17 -0600251def _BuildIdentity(hw_scan_config, program, brand_scan_config=None):
David Burger7fd1dbe2020-03-26 09:26:55 -0600252 identity = {}
253 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
254 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
Andrew Lamb7806ce92020-04-07 10:22:17 -0600255 # 'platform-name' is needed to support 'mosys platform name'. Clients should
256 # longer require platform name, but set it here for backwards compatibility.
257 _Set(program.name, identity, 'platform-name')
David Burger7fd1dbe2020-03-26 09:26:55 -0600258 # ARM architecture
259 _Set(hw_scan_config.device_tree_compatible_match, identity,
260 'device-tree-compatible-match')
261
262 if brand_scan_config:
263 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
264
265 return identity
266
267
268def _Lookup(id_value, id_map):
269 if id_value.value:
270 key = id_value.value
271 if key in id_map:
272 return id_map[id_value.value]
273 error = 'Failed to lookup %s with value: %s' % (
274 id_value.__class__.__name__.replace('Id', ''), key)
275 print(error)
276 print('Check the config contents provided:')
277 pp = pprint.PrettyPrinter(indent=4)
278 pp.pprint(id_map)
279 raise Exception(error)
280
281
C Shapiro2b6d5332020-05-06 17:51:35 -0500282def _BuildTouchFileConfig(config, project_name):
283 partners = dict([(x.id.value, x) for x in config.partners.value])
284 files = []
285 for comp in config.components:
286 if comp.touchscreen.product_id:
287 vendor = _Lookup(comp.manufacturer_id, partners)
288 if not vendor:
289 raise Exception(
290 "Manufacturer must be set for touchscreen %s" % comp.id.value)
291
292 product_id = comp.touchscreen.product_id
293 fw_version = comp.touchscreen.fw_version
294
295 touchscreen_vendor = vendor.touchscreen_vendor
296 sym_link = touchscreen_vendor.fw_file_format.format(
297 vendor_name = vendor.name,
298 vendor_id = touchscreen_vendor.vendor_id,
299 product_id = product_id,
300 fw_version = fw_version,
301 product_series = comp.touchscreen.product_series
302 )
303
304 file_name = "%s_%s.bin" % (product_id, fw_version)
305 fw_file_path = os.path.join(TOUCH_PATH, vendor.name, file_name)
306
307 if not os.path.exists(fw_file_path):
308 raise Exception(
309 "Touchscreen fw bin file doesn't exist at: %s" % fw_file_path)
310
311 files.append({
312 "destination": "/opt/google/touch/firmware/%s_%s" % (
313 vendor.name, file_name),
314 "source": os.path.join(project_name, fw_file_path),
315 "symlink": os.path.join("/lib/firmware", sym_link),
316 })
317
318 result = {}
319 _Set(files, result, 'files')
320 return result
321
322
323def _TransformBuildConfigs(config, config_files=ConfigFiles({}, {}, {}, None)):
David Burger7fd1dbe2020-03-26 09:26:55 -0600324 partners = dict([(x.id.value, x) for x in config.partners.value])
325 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600326 sw_configs = list(config.software_configs)
327 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
328
C Shapiroa0b766c2020-03-31 08:35:28 -0500329 if len(config.build_targets) != 1:
330 # Artifact of sharing the config_bundle for analysis and transforms.
331 # Integrated analysis of multiple programs/projects it the only time
332 # having multiple build targets would be valid.
333 raise Exception('Single build_target required for transform')
334
David Burger7fd1dbe2020-03-26 09:26:55 -0600335 results = {}
336 for hw_design in config.designs.value:
337 if config.device_brands.value:
338 device_brands = [x for x in config.device_brands.value
339 if x.design_id.value == hw_design.id.value]
340 else:
341 device_brands = [device_brand_pb2.DeviceBrand()]
342
343 for device_brand in device_brands:
344 # Brand config can be empty since platform JSON config allows it
345 brand_config = brand_config_pb2.BrandConfig()
346 if device_brand.id.value in brand_configs:
347 brand_config = brand_configs[device_brand.id.value]
348
349 for hw_design_config in hw_design.configs:
350 design_id = hw_design_config.id.value
351 sw_config_matches = [x for x in sw_configs
352 if x.design_config_id.value == design_id]
353 if len(sw_config_matches) == 1:
354 sw_config = sw_config_matches[0]
355 elif len(sw_config_matches) > 1:
356 raise Exception('Multiple software configs found for: %s' % design_id)
357 else:
358 raise Exception('Software config is required for: %s' % design_id)
359
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500360 program = _Lookup(hw_design.program_id, programs)
361 signer_configs = dict(
362 [(x.brand_id.value, x) for x in program.device_signer_configs])
363 device_signer_config = None
364 if signer_configs:
365 device_signer_config = _Lookup(device_brand.id, signer_configs)
366
C Shapiro90fda252020-04-17 14:34:57 -0500367 transformed_config = _TransformBuildConfig(
368 Config(
369 program=program,
370 hw_design=hw_design,
371 odm=_Lookup(hw_design.odm_id, partners),
372 hw_design_config=hw_design_config,
373 device_brand=device_brand,
374 device_signer_config=device_signer_config,
375 oem=_Lookup(device_brand.oem_id, partners),
376 sw_config=sw_config,
377 brand_config=brand_config,
378 build_target=config.build_targets[0]),
C Shapiro5bf23a72020-04-24 11:40:17 -0500379 config_files)
David Burger7fd1dbe2020-03-26 09:26:55 -0600380
381 config_json = json.dumps(transformed_config,
382 sort_keys=True,
383 indent=2,
384 separators=(',', ': '))
385
386 if config_json not in results:
387 results[config_json] = transformed_config
388
389 return list(results.values())
390
391
C Shapiro5bf23a72020-04-24 11:40:17 -0500392def _TransformBuildConfig(config, config_files):
David Burger7fd1dbe2020-03-26 09:26:55 -0600393 """Transforms Config instance into target platform JSON schema.
394
395 Args:
396 config: Config namedtuple
C Shapiro5bf23a72020-04-24 11:40:17 -0500397 config_files: Map to look up the generated config files.
David Burger7fd1dbe2020-03-26 09:26:55 -0600398
399 Returns:
400 Unique config payload based on the platform JSON schema.
401 """
402 result = {
403 'identity': _BuildIdentity(
404 config.sw_config.id_scan_config,
Andrew Lamb7806ce92020-04-07 10:22:17 -0600405 config.program,
David Burger7fd1dbe2020-03-26 09:26:55 -0600406 config.brand_config.scan_config),
407 'name': config.hw_design.name.lower(),
408 }
409
C Shapiro5bf23a72020-04-24 11:40:17 -0500410 _Set(_BuildArc(config, config_files), result, 'arc')
David Burger7fd1dbe2020-03-26 09:26:55 -0600411 _Set(_BuildAudio(config), result, 'audio')
C Shapiro5bf23a72020-04-24 11:40:17 -0500412 _Set(_BuildBluetooth(config, config_files.bluetooth), result, 'bluetooth')
David Burger7fd1dbe2020-03-26 09:26:55 -0600413 _Set(config.device_brand.brand_code, result, 'brand-code')
David Burger8aa8fa32020-04-14 08:30:34 -0600414 _Set(_BuildCamera(
415 config.hw_design_config.hardware_topology), result, 'camera')
David Burger7fd1dbe2020-03-26 09:26:55 -0600416 _Set(_BuildFirmware(config), result, 'firmware')
417 _Set(_BuildFwSigning(config), result, 'firmware-signing')
418 _Set(_BuildFingerprint(
419 config.hw_design_config.hardware_topology), result, 'fingerprint')
420 power_prefs = config.sw_config.power_config.preferences
421 power_prefs_map = dict(
422 (x.replace('_', '-'),
423 power_prefs[x]) for x in power_prefs)
424 _Set(power_prefs_map, result, 'power')
C Shapiro6830e6c2020-04-29 13:29:56 -0500425 _Set(config_files.dptf_file, result, 'thermal')
C Shapiro2b6d5332020-05-06 17:51:35 -0500426 _Set(config_files.touch_fw, result, 'touch')
David Burger7fd1dbe2020-03-26 09:26:55 -0600427
428 return result
429
430
431def WriteOutput(configs, output=None):
432 """Writes a list of configs to platform JSON format.
433
434 Args:
435 configs: List of config dicts defined in cros_config_schema.yaml
436 output: Target file output (if None, prints to stdout)
437 """
438 json_output = json.dumps(
439 {'chromeos': {
440 'configs': configs,
441 }},
442 sort_keys=True,
443 indent=2,
444 separators=(',', ': '))
445 if output:
446 with open(output, 'w') as output_stream:
447 # Using print function adds proper trailing newline.
448 print(json_output, file=output_stream)
449 else:
450 print(json_output)
451
452
C Shapiro90fda252020-04-17 14:34:57 -0500453def _BluetoothId(project_name, bt_comp):
454 return '_'.join([project_name,
455 bt_comp.vendor_id,
456 bt_comp.product_id,
457 bt_comp.bcd_device])
458
459
C Shapiro5bf23a72020-04-24 11:40:17 -0500460def _Feature(name, present):
461 attrib = {'name': name}
462 if present:
463 return etree.Element('feature', attrib=attrib)
464 else:
465 return etree.Element('unavailable-feature', attrib=attrib)
466
467
468def _AnyPresent(features):
469 return topology_pb2.HardwareFeatures.PRESENT in features;
470
471
472def _ArcHardwareFeatureId(design_config):
473 return design_config.id.value.lower().replace(':', '_')
474
475
C Shapiro5c877992020-04-29 12:11:28 -0500476def WriteArcHardwareFeatureFiles(config, output_dir, build_root_dir):
C Shapiro5bf23a72020-04-24 11:40:17 -0500477 """Writes ARC hardware_feature.xml files for each config
478
479 Args:
480 config: Source ConfigBundle to process.
481 output_dir: Path to the generated output.
C Shapiro5c877992020-04-29 12:11:28 -0500482 build_root_path: Path to the config file from portage's perspective.
C Shapiro5bf23a72020-04-24 11:40:17 -0500483 Returns:
484 dict that maps the design_config_id onto the correct file.
485 """
C Shapiro5bf23a72020-04-24 11:40:17 -0500486 result = {}
487 for hw_design in config.designs.value:
488 for design_config in hw_design.configs:
489 hw_features = design_config.hardware_features
490 multi_camera = hw_features.camera.count == 2
491 touchscreen = _AnyPresent([hw_features.screen.touch_support])
492 acc = hw_features.accelerometer
493 gyro = hw_features.gyroscope
494 compass = hw_features.magnetometer
495 ls = hw_features.light_sensor
496 root = etree.Element('permissions')
497 root.extend([
498 _Feature('android.hardware.camera', multi_camera),
499 _Feature('android.hardware.camera.autofocus', multi_camera),
500 _Feature('android.hardware.sensor.accelerometer',
501 _AnyPresent(
502 [acc.lid_accelerometer, acc.base_accelerometer])),
503 _Feature('android.hardware.sensor.gyroscope',
504 _AnyPresent(
505 [gyro.lid_gyroscope, gyro.base_gyroscope])),
506 _Feature('android.hardware.sensor.compass',
507 _AnyPresent(
508 [compass.lid_magnetometer, compass.base_magnetometer])),
509 _Feature('android.hardware.sensor.light',
510 _AnyPresent(
511 [ls.lid_lightsensor, ls.base_lightsensor])),
512 _Feature('android.hardware.touchscreen', touchscreen),
513 _Feature('android.hardware.touchscreen.multitouch', touchscreen),
514 _Feature(
515 'android.hardware.touchscreen.multitouch.distinct', touchscreen),
516 _Feature(
517 'android.hardware.touchscreen.multitouch.jazzhand', touchscreen),
518 ])
519
520 feature_id = _ArcHardwareFeatureId( design_config)
521
522 file_name = 'hardware_features_%s.xml' % feature_id
523 output = '%s/arc/%s' % (output_dir, file_name)
C Shapiro9a3ac8c2020-04-25 07:49:21 -0500524 file_content = minidom.parseString(
525 etree.tostring(root)).toprettyxml(indent=' ', encoding='utf-8')
526
527 with open(output, 'wb') as f:
528 f.write(file_content)
529
C Shapiro5bf23a72020-04-24 11:40:17 -0500530 result[feature_id] = {
C Shapiro5c877992020-04-29 12:11:28 -0500531 'build-path': '%s/arc/%s' % (build_root_dir, file_name),
C Shapiro5bf23a72020-04-24 11:40:17 -0500532 'system-path': '/etc/%s' % file_name,
533 }
534 return result
535
536
C Shapiro5c877992020-04-29 12:11:28 -0500537def WriteBluetoothConfigFiles(config, output_dir, build_root_path):
C Shapiro90fda252020-04-17 14:34:57 -0500538 """Writes bluetooth conf files for every unique bluetooth chip.
539
540 Args:
541 config: Source ConfigBundle to process.
542 output_dir: Path to the generated output.
C Shapiro5c877992020-04-29 12:11:28 -0500543 build_root_path: Path to the config file from portage's perspective.
C Shapiro90fda252020-04-17 14:34:57 -0500544 Returns:
545 dict that maps the bluetooth component id onto the file config.
546 """
C Shapiro90fda252020-04-17 14:34:57 -0500547 result = {}
548 for hw_design in config.designs.value:
549 project_name = hw_design.name.lower()
550 for design_config in hw_design.configs:
C Shapiro74da76e2020-05-04 13:02:20 -0500551 bt_comp = design_config.hardware_features.bluetooth.component.usb
C Shapiro90fda252020-04-17 14:34:57 -0500552 if bt_comp.vendor_id:
553 bt_id = _BluetoothId(project_name, bt_comp)
554 result[bt_id] = {
C Shapiro5c877992020-04-29 12:11:28 -0500555 'build-path': '%s/bluetooth/%s.conf' % (build_root_path, bt_id),
C Shapiro90fda252020-04-17 14:34:57 -0500556 'system-path': '/etc/bluetooth/%s/main.conf' % bt_id,
557 }
558 bt_content = '''[General]
559DeviceID = bluetooth:%s:%s:%s''' % (bt_comp.vendor_id,
560 bt_comp.product_id,
561 bt_comp.bcd_device)
562
563 output = '%s/bluetooth/%s.conf' % (output_dir, bt_id)
564 with open(output, 'w') as output_stream:
565 # Using print function adds proper trailing newline.
566 print(bt_content, file=output_stream)
567 return result
568
569
David Burger7fd1dbe2020-03-26 09:26:55 -0600570def _ReadConfig(path):
David Burgerd4f32962020-05-02 12:07:40 -0600571 """Reads a ConfigBundle proto from a json pb file.
David Burgere6f76222020-04-27 11:08:01 -0600572
573 Args:
David Burgerd4f32962020-05-02 12:07:40 -0600574 path: Path to the file encoding the json pb proto.
David Burgere6f76222020-04-27 11:08:01 -0600575 """
576 config = config_bundle_pb2.ConfigBundle()
577 with open(path, 'r') as f:
578 return json_format.Parse(f.read(), config)
579
580
David Burger7fd1dbe2020-03-26 09:26:55 -0600581def _MergeConfigs(configs):
582 result = config_bundle_pb2.ConfigBundle()
583 for config in configs:
584 result.MergeFrom(config)
585
586 return result
587
588
589def Main(project_configs,
590 program_config,
591 output):
592 """Transforms source proto config into platform JSON.
593
594 Args:
595 project_configs: List of source project configs to transform.
596 program_config: Program config for the given set of projects.
597 output: Output file that will be generated by the transform.
598 """
C Shapiro90fda252020-04-17 14:34:57 -0500599 configs =_MergeConfigs(
600 [_ReadConfig(program_config)] +
601 [_ReadConfig(config) for config in project_configs])
C Shapiro5bf23a72020-04-24 11:40:17 -0500602 bluetooth_files = {}
603 arc_hw_feature_files = {}
C Shapiro2b6d5332020-05-06 17:51:35 -0500604 touch_fw = {}
C Shapiro6830e6c2020-04-29 13:29:56 -0500605 dptf_file = None
C Shapiro5bf23a72020-04-24 11:40:17 -0500606 output_dir = os.path.dirname(output)
C Shapiro5c877992020-04-29 12:11:28 -0500607 build_root_dir = output_dir
C Shapiro5c877992020-04-29 12:11:28 -0500608 if 'sw_build_config' in output_dir:
609 full_path = os.path.realpath(output)
C Shapiro6438fb32020-05-01 16:43:49 -0500610 project_name = re.match(
611 r'.*/(\w*)/sw_build_config/.*', full_path).groups(1)[0]
C Shapiro5c877992020-04-29 12:11:28 -0500612 # Projects don't know about each other until they are integrated into the
613 # build system. When this happens, the files need to be able to co-exist
614 # without any collisions. This prefixes the project name (which is how
615 # portage maps in the project), so project files co-exist and can be
616 # installed together.
617 # This is necessary to allow projects to share files at the program level
618 # without having portage file installation collisions.
619 build_root_dir = os.path.join(project_name, output_dir)
C Shapiro6830e6c2020-04-29 13:29:56 -0500620
C Shapiro7356bd62020-05-02 05:21:33 -0500621 if os.path.exists(DPTF_PATH):
622 project_dptf_path = os.path.join(project_name, 'dptf.dv')
623 dptf_file = {
624 'dptf-dv': project_dptf_path,
625 'files': [_File(os.path.join(project_name, DPTF_PATH),
626 os.path.join('/etc/dptf', project_dptf_path))]
627 }
C Shapiro2b6d5332020-05-06 17:51:35 -0500628 if os.path.exists(TOUCH_PATH):
629 touch_fw = _BuildTouchFileConfig(configs, project_name)
C Shapiro5bf23a72020-04-24 11:40:17 -0500630 if os.path.exists(os.path.join(output_dir, 'bluetooth')):
C Shapiro5c877992020-04-29 12:11:28 -0500631 bluetooth_files = WriteBluetoothConfigFiles(
632 configs, output_dir, build_root_dir)
C Shapiro5bf23a72020-04-24 11:40:17 -0500633 if os.path.exists(os.path.join(output_dir, 'arc')):
634 arc_hw_feature_files = WriteArcHardwareFeatureFiles(
C Shapiro5c877992020-04-29 12:11:28 -0500635 configs, output_dir, build_root_dir)
C Shapiro5bf23a72020-04-24 11:40:17 -0500636 config_files = ConfigFiles(
637 bluetooth=bluetooth_files,
638 arc_hw_features=arc_hw_feature_files,
C Shapiro2b6d5332020-05-06 17:51:35 -0500639 touch_fw=touch_fw,
C Shapiro6830e6c2020-04-29 13:29:56 -0500640 dptf_file=dptf_file
C Shapiro5bf23a72020-04-24 11:40:17 -0500641 )
642 WriteOutput(_TransformBuildConfigs(configs, config_files), output)
David Burger7fd1dbe2020-03-26 09:26:55 -0600643
644
645def main(argv=None):
646 """Main program which parses args and runs
647
648 Args:
649 argv: List of command line arguments, if None uses sys.argv.
650 """
651 if argv is None:
652 argv = sys.argv[1:]
653 opts = ParseArgs(argv)
654 Main(opts.project_configs, opts.program_config, opts.output)
655
656
657if __name__ == '__main__':
658 sys.exit(main(sys.argv[1:]))