forked from victronenergy/dbus-modbus-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
89 lines (64 loc) · 2.14 KB
/
utils.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# miscellaneous utilities
import dbus
import ipaddress
import os
def private_bus():
'''Return a private D-Bus connection
If DBUS_SESSION_BUS_ADDRESS exists in the environment, the session
bus is used, the system bus otherwise.
'''
if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
return dbus.SessionBus(private=True)
return dbus.SystemBus(private=True)
class timeout:
'''Temporarily set the `timeout` attribute of an object
To be used in a `with` statement. Example:
with timeout(obj, 10):
line = obj.read()
This calls `obj.read()` with `obj.timeout` set to 10, then
restores the original value.
'''
def __init__(self, obj, timeout):
self.obj = obj
self.timeout = timeout
def __enter__(self):
self.orig_timeout = self.obj.timeout
self.obj.timeout = self.timeout
def __exit__(self, exc_type, exc_value, traceback):
self.obj.timeout = self.orig_timeout
def get_networks(blacklist):
'''Get IPv4 networks of host
Return a list of IPv4Interface objects corresponding to active
network interfaces with a global scope address.
:param blacklist: list of interface names to ignore
:returns: list of IPv4Interface objects
'''
nets = []
try:
with os.popen('ip -br -4 addr show scope global up') as ip:
for line in ip:
v = line.split()
if v[0] in blacklist:
continue
net = ipaddress.IPv4Interface(u'' + v[2])
nets.append(net)
except:
pass
return nets
def get_enum(enum, val, default=None):
'''Get enum for value
Return the enum matching a given value or a default.
:param enum: the enum class
:param val: the value to match
:param default: default value
:returns: enum value matching supplied value, if any, else default
'''
if any(val == m.value for m in enum):
return enum(val)
elif default != None:
return default
return val
def get_super(base, t):
if not isinstance(t, type):
t = type(t)
return t.__mro__[t.__mro__.index(base) + 1]