1# Copyright 2014 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
6
7from telemetry.internal.platform import power_monitor
8
9try:
10  from devil.android import device_errors  # pylint: disable=import-error
11except ImportError:
12  device_errors = None
13
14
15_TEMPERATURE_FILE = '/sys/class/thermal/thermal_zone0/temp'
16
17
18class AndroidTemperatureMonitor(power_monitor.PowerMonitor):
19  """
20  Returns temperature results in power monitor dictionary format.
21  """
22  def __init__(self, device):
23    super(AndroidTemperatureMonitor, self).__init__()
24    self._device = device
25
26  def CanMonitorPower(self):
27    return self._GetBoardTemperatureCelsius() is not None
28
29  def StartMonitoringPower(self, browser):
30    # don't call _CheckStart() because this is temperature, not power
31    # therefore, StartMonitoringPower and StopMonitoringPower
32    # do not need to be paired
33    pass
34
35  def StopMonitoringPower(self):
36    avg_temp = self._GetBoardTemperatureCelsius()
37    if avg_temp is None:
38      return {'identifier': 'android_temperature_monitor'}
39    else:
40      return {'identifier': 'android_temperature_monitor',
41              'platform_info': {'average_temperature_c': avg_temp}}
42
43  def _GetBoardTemperatureCelsius(self):
44    try:
45      contents = self._device.ReadFile(_TEMPERATURE_FILE)
46      return float(contents) if contents else None
47    except ValueError:
48      logging.warning('String returned from device.ReadFile(_TEMPERATURE_FILE) '
49                      'in invalid format.')
50      return None
51    except device_errors.CommandFailedError:
52      return None
53