diff --git a/homeassistant/components/sensor/systemmonitor.py b/homeassistant/components/sensor/systemmonitor.py index 0963786b7d0d1d68fc8f9959c35a4637e2634eb0..14eadb48984ebf8820e82f08728c19d0f1234ec8 100755 --- a/homeassistant/components/sensor/systemmonitor.py +++ b/homeassistant/components/sensor/systemmonitor.py @@ -10,7 +10,7 @@ import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( - CONF_RESOURCES, STATE_OFF, STATE_ON, CONF_TYPE) + CONF_RESOURCES, STATE_OFF, STATE_ON, STATE_UNKNOWN, CONF_TYPE) from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util @@ -49,6 +49,18 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ })]) }) +IO_COUNTER = { + 'network_out': 0, + 'network_in': 1, + 'packets_out': 2, + 'packets_in': 3, +} + +IF_ADDRS = { + 'ipv4_address': 0, + 'ipv6_address': 1, +} + # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): @@ -126,20 +138,25 @@ class SystemMonitorSensor(Entity): self._state = STATE_ON else: self._state = STATE_OFF - elif self.type == 'network_out': - self._state = round(psutil.net_io_counters(pernic=True) - [self.argument][0] / 1024**2, 1) - elif self.type == 'network_in': - self._state = round(psutil.net_io_counters(pernic=True) - [self.argument][1] / 1024**2, 1) - elif self.type == 'packets_out': - self._state = psutil.net_io_counters(pernic=True)[self.argument][2] - elif self.type == 'packets_in': - self._state = psutil.net_io_counters(pernic=True)[self.argument][3] - elif self.type == 'ipv4_address': - self._state = psutil.net_if_addrs()[self.argument][0][1] - elif self.type == 'ipv6_address': - self._state = psutil.net_if_addrs()[self.argument][1][1] + elif self.type == 'network_out' or self.type == 'network_in': + counters = psutil.net_io_counters(pernic=True) + if self.argument in counters: + counter = counters[self.argument][IO_COUNTER[self.type]] + self._state = round(counter / 1024**2, 1) + else: + self._state = STATE_UNKNOWN + elif self.type == 'packets_out' or self.type == 'packets_in': + counters = psutil.net_io_counters(pernic=True) + if self.argument in counters: + self._state = counters[self.argument][IO_COUNTER[self.type]] + else: + self._state = STATE_UNKNOWN + elif self.type == 'ipv4_address' or self.type == 'ipv6_address': + addresses = psutil.net_if_addrs() + if self.argument in addresses: + self._state = addresses[self.argument][IF_ADDRS[self.type]][1] + else: + self._state = STATE_UNKNOWN elif self.type == 'last_boot': self._state = dt_util.as_local( dt_util.utc_from_timestamp(psutil.boot_time())