1#!/usr/bin/env python3
2#
3#   Copyright 2017 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16
17from acts import utils
18from acts.libs.ota.ota_runners import ota_runner_factory
19
20"""Maps AndroidDevices to OtaRunners."""
21ota_runners = {}
22
23
24def initialize(user_params, android_devices):
25    """Initialize OtaRunners for each device.
26
27    Args:
28        user_params: The user_params from the ACTS config.
29        android_devices: The android_devices in the test.
30    """
31    for ad in android_devices:
32        ota_runners[ad] = ota_runner_factory.create_from_configs(
33            user_params, ad)
34
35
36def _check_initialization(android_device):
37    """Check if a given device was initialized."""
38    if android_device not in ota_runners:
39        raise KeyError('Android Device with serial "%s" has not been '
40                       'initialized for OTA Updates. Did you forget to call'
41                       'ota_updater.initialize()?' % android_device.serial)
42
43
44def update(android_device, ignore_update_errors=False):
45    """Update a given AndroidDevice.
46
47    Args:
48        android_device: The device to update
49        ignore_update_errors: Whether or not to ignore update errors such as
50           no more updates available for a given device. Default is false.
51    Throws:
52        OtaError if ignore_update_errors is false and the OtaRunner has run out
53        of packages to update the phone with.
54    """
55    _check_initialization(android_device)
56    ota_runners[android_device].validate_update()
57    try:
58        ota_runners[android_device].update()
59    except Exception as e:
60        if ignore_update_errors:
61            return
62        android_device.log.error(e)
63        android_device.take_bug_report('ota_update',
64                                       utils.get_current_epoch_time())
65        raise e
66
67
68def can_update(android_device):
69    """Whether or not a device can be updated."""
70    _check_initialization(android_device)
71    return ota_runners[android_device].can_update()
72