forked from Bouni/python-luxtronik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_vector.py
68 lines (55 loc) · 2.03 KB
/
data_vector.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
"""Provides a base class for parameters, calculations, visibilities."""
import logging
from luxtronik.datatypes import Unknown
class DataVector:
"""Class that holds a vector of data entries."""
logger = logging.getLogger("Luxtronik.DataVector")
name = "DataVector"
def __init__(self):
"""Initialize DataVector class."""
self._data = {}
def __iter__(self):
"""Iterator for the data entries."""
return iter(self._data.items())
def parse(self, raw_data):
"""Parse raw data."""
for index, data in enumerate(raw_data):
entry = self._data.get(index, None)
if entry is not None:
entry.raw = data
else:
# self.logger.warning(f"Entry '%d' not in list of {self.name}", index)
entry = Unknown(f"Unknown_{self.name}_{index}")
entry.raw = data
self._data[index] = entry
def _lookup(self, target, with_index=False):
"""
Lookup an entry
"target" could either be its id or its name.
In case "with_index" is set, also the index is returned.
"""
if isinstance(target, str):
try:
# Try to get entry by id
target_index = int(target)
except ValueError:
# Get entry by name
target_index = None
for index, entry in self._data.items():
if entry.name == target:
target_index = index
elif isinstance(target, int):
# Get entry by id
target_index = target
else:
target_index = None
target_entry = self._data.get(target_index, None)
if target_entry is None:
self.logger.warning("entry '%s' not found", target)
if with_index:
return target_index, target_entry
return target_entry
def get(self, target):
"""Get entry by id or name."""
entry = self._lookup(target)
return entry