[modules/traffic] Refactor code for simplicity

Try to reduce code duplication by having a helper function that creates
the traffic widgets and do widget generation more generically.
This commit is contained in:
Tobias Witek 2017-05-05 20:58:15 +02:00
parent ea7227dc53
commit f52702fbb5

View file

@ -33,45 +33,40 @@ class Module(bumblebee.engine.Module):
def update(self, widgets): def update(self, widgets):
self._update_widgets(widgets) self._update_widgets(widgets)
def create_widget(self, widgets, name, txt=None, attributes={}):
widget = self.widget(name)
if widget: return widget
widget = bumblebee.output.Widget(name=name)
widget.full_text(txt)
widgets.append(widget)
for key in attributes:
widget.set(key, attributes[key])
return widget
def _update_widgets(self, widgets): def _update_widgets(self, widgets):
interfaces = [ i for i in netifaces.interfaces() if not i.startswith(self._exclude) ] interfaces = [ i for i in netifaces.interfaces() if not i.startswith(self._exclude) ]
counters = psutil.net_io_counters(pernic=True) counters = psutil.net_io_counters(pernic=True)
for interface in interfaces: for interface in interfaces:
if not interface: interface = "lo" if not interface: interface = "lo"
rx = counters[interface].bytes_recv data = {
tx = counters[interface].bytes_sent "rx": counters[interface].bytes_recv,
"tx": counters[interface].bytes_sent,
}
name = "traffic-{}".format(interface) name = "traffic-{}".format(interface)
txname = "traffic.tx-{}".format(interface)
rxname = "traffic.rx-{}".format(interface)
widget = self.widget(name) self.create_widget(widgets, name, interface)
if not widget:
widget = bumblebee.output.Widget(name=name)
widgets.append(widget)
widget.full_text(interface)
widget_rx = self.widget(rxname) for direction in ["rx", "tx"]:
widget_tx = self.widget(txname) name = "traffic.{}-{}".format(direction, interface)
if not widget_rx: widget = self.create_widget(widgets, name, attributes={"theme.minwidth": "1000.00MB"})
widget_rx = bumblebee.output.Widget(name=rxname) prev = widget.get(direction, 0)
widget_rx.set("theme.minwidth", "1000.00MB") speed = bumblebee.util.bytefmt(int(data[direction]) - int(prev))
widgets.append(widget_rx) widget.full_text(speed)
if not widget_tx: widget.set(direction, data[direction])
widget_tx = bumblebee.output.Widget(name=txname)
widget_tx.set("theme.minwidth", "1000.00MB")
widgets.append(widget_tx)
prev_rx = widget_rx.get("rx", 0)
prev_tx = widget_tx.get("tx", 0)
rxspeed = bumblebee.util.bytefmt(int(rx) - int(prev_rx))
txspeed = bumblebee.util.bytefmt(int(tx) - int(prev_tx))
widget_rx.full_text(rxspeed)
widget_tx.full_text(txspeed)
widget_rx.set("rx", rx)
widget_tx.set("tx", tx)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4