Test Failed
Push — develop ( 504450...f0e8ef )
by Nicolas
03:16
created

GlancesGrabBat.update()   A

Complexity

Conditions 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nop 1
dl 0
loc 20
rs 9.75
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""Battery plugin."""
21
22
import psutil
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
introduced by
Unable to import 'psutil'
Loading history...
23
24
from glances.logger import logger
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
25
from glances.plugins.glances_plugin import GlancesPlugin
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
26
27
# Batinfo library (optional; Linux-only)
28
batinfo_tag = True
0 ignored issues
show
Coding Style Naming introduced by
The name batinfo_tag does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
29
try:
30
    import batinfo
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
31
except ImportError:
32
    logger.debug("batinfo library not found. Fallback to psutil.")
33
    batinfo_tag = False
0 ignored issues
show
Coding Style Naming introduced by
The name batinfo_tag does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
34
35
# Availability:
36
# Linux, Windows, FreeBSD (psutil>=5.1.0)
37
# macOS (psutil>=5.4.2)
38
psutil_tag = True
0 ignored issues
show
Coding Style Naming introduced by
The name psutil_tag does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
39
try:
40
    psutil.sensors_battery()
41
except Exception as e:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
42
    logger.error("Cannot grab battery status {}.".format(e))
0 ignored issues
show
introduced by
Use formatting in logging functions and pass the parameters as arguments
Loading history...
43
    psutil_tag = False
0 ignored issues
show
Coding Style Naming introduced by
The name psutil_tag does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
44
45
46
class Plugin(GlancesPlugin):
47
    """Glances battery capacity plugin.
48
49
    stats is a list
50
    """
51
52
    def __init__(self, args=None, config=None):
53
        """Init the plugin."""
54
        super(Plugin, self).__init__(args=args,
55
                                     config=config,
56
                                     stats_init_value=[])
57
58
        # Init the sensor class
59
        self.glancesgrabbat = GlancesGrabBat()
60
61
        # We do not want to display the stat in a dedicated area
62
        # The HDD temp is displayed within the sensors plugin
63
        self.display_curse = False
64
65
    @GlancesPlugin._check_decorator
66
    @GlancesPlugin._log_result_decorator
67
    def update(self):
68
        """Update battery capacity stats using the input method."""
69
        # Init new stats
70
        stats = self.get_init_value()
71
72
        if self.input_method == 'local':
73
            # Update stats
74
            self.glancesgrabbat.update()
75
            stats = self.glancesgrabbat.get()
76
77
        elif self.input_method == 'snmp':
78
            # Update stats using SNMP
79
            # Not avalaible
80
            pass
81
82
        # Update the stats
83
        self.stats = stats
84
85
        return self.stats
86
87
88
class GlancesGrabBat(object):
89
    """Get batteries stats using the batinfo library."""
90
91
    def __init__(self):
92
        """Init batteries stats."""
93
        self.bat_list = []
94
95
        if batinfo_tag:
96
            self.bat = batinfo.batteries()
97
        elif psutil_tag:
98
            self.bat = psutil
99
        else:
100
            self.bat = None
101
102
    def update(self):
103
        """Update the stats."""
104
        if batinfo_tag:
105
            # Use the batinfo lib to grab the stats
106
            # Compatible with multiple batteries
107
            self.bat.update()
108
            self.bat_list = [{
109
                'label': 'Battery',
110
                'value': self.battery_percent,
111
                'unit': '%'}]
112
        elif psutil_tag and hasattr(self.bat.sensors_battery(), 'percent'):
113
            # Use psutil to grab the stats
114
            # Give directly the battery percent
115
            self.bat_list = [{
116
                'label': 'Battery',
117
                'value': int(self.bat.sensors_battery().percent),
118
                'unit': '%'}]
119
        else:
120
            # No stats...
121
            self.bat_list = []
122
123
    def get(self):
124
        """Get the stats."""
125
        return self.bat_list
126
127
    @property
128
    def battery_percent(self):
129
        """Get batteries capacity percent."""
130
        if not batinfo_tag or not self.bat.stat:
131
            return []
132
133
        # Init the bsum (sum of percent)
134
        # and Loop over batteries (yes a computer could have more than 1 battery)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (81/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
135
        bsum = 0
136
        for b in self.bat.stat:
0 ignored issues
show
Coding Style Naming introduced by
The name b does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
137
            try:
138
                bsum += int(b.capacity)
139
            except ValueError:
140
                return []
141
142
        # Return the global percent
143
        return int(bsum / len(self.bat.stat))
0 ignored issues
show
introduced by
division w/o __future__ statement
Loading history...
144