summaryrefslogtreecommitdiff
path: root/util/battery_temp
blob: c69e3d4778e346c11a3c3a2fbcf2cac203031b34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/bin/bash
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Description: Read and output temperature of device's primary battery in
# degrees Celsius.
#
# TODO(tbroch) revisit for detachables with multiple batteries.

# Read battery temperature from sysfs power_supply and return in degC.
batt_temp_sysfs() {
    local temp=""

    for psdir in /sys/class/power_supply/* ; do
        if [[ -e "${psdir}/temp" ]] ; then
            pstype=$(cat $psdir/type)
            if [[ "${pstype}" -eq "Battery" ]] ; then
                temp=$(bc <<< "scale=2; $(cat ${psdir}/temp)/10")
                break
            fi
        fi
    done
    echo ${temp}
}

# Read battery temperature from EC and return in degC.
batt_temp_ec() {
    local temp=""

    local sensor_str=$(ectool tempsinfo all 2>/dev/null | grep Battery)
    if [[ $? -eq 0 ]] && [[ ! -z "${sensor_str}" ]] ; then
        local idx=$(echo ${sensor_str} | cut -d: -f1)
        # ectool temps <idx> looks like 'Reading temperature...298 K'
        temp_str=$(ectool temps ${idx})
        temp="${temp_str//[!0-9]/}"
        if [[ -z "${temp}" ]] ; then
            temp="error"
        else
            temp=$(bc <<< "scale=2; ${temp} - 273.15")
        fi
    fi
    echo $temp
}

# Main
TEMP_DEGC=$(batt_temp_sysfs)
if [[ -z "${TEMP_DEGC}" ]] ; then
    TEMP_DEGC=$(batt_temp_ec)
fi

if [[ -z "${TEMP_DEGC}" ]] ; then
    echo "unknown"
else
    echo ${TEMP_DEGC}
fi