thingsboard-endpoint 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. thingsboard/__init__.py +6 -0
  2. thingsboard/endpoint/__init__.py +15 -0
  3. thingsboard/endpoint/attribute/__init__.py +5 -0
  4. thingsboard/endpoint/attribute/attribute.py +274 -0
  5. thingsboard/endpoint/attribute/constraint.py +68 -0
  6. thingsboard/endpoint/attribute/decorator.py +97 -0
  7. thingsboard/endpoint/attribute/type.py +85 -0
  8. thingsboard/endpoint/connector/__init__.py +7 -0
  9. thingsboard/endpoint/connector/model_to_cloud.py +409 -0
  10. thingsboard/endpoint/endpoint.py +635 -0
  11. thingsboard/endpoint/exception/__init__.py +1 -0
  12. thingsboard/endpoint/exception/invalid_attribute_exception.py +13 -0
  13. thingsboard/endpoint/exception/invalid_attribute_type_exception.py +6 -0
  14. thingsboard/endpoint/exception/invalid_property_exception.py +7 -0
  15. thingsboard/endpoint/exception/modification_exception.py +5 -0
  16. thingsboard/endpoint/factory/__init__.py +9 -0
  17. thingsboard/endpoint/factory/xml.py +111 -0
  18. thingsboard/endpoint/interface/__init__.py +16 -0
  19. thingsboard/endpoint/interface/attribute_container.py +60 -0
  20. thingsboard/endpoint/interface/attribute_listener.py +23 -0
  21. thingsboard/endpoint/interface/message_format.py +59 -0
  22. thingsboard/endpoint/interface/named_item.py +29 -0
  23. thingsboard/endpoint/interface/node_container.py +26 -0
  24. thingsboard/endpoint/interface/object_container.py +90 -0
  25. thingsboard/endpoint/interface/unique_identifiable.py +18 -0
  26. thingsboard/endpoint/interface/uuid.py +48 -0
  27. thingsboard/endpoint/message_format/__init__.py +1 -0
  28. thingsboard/endpoint/message_format/factory.py +34 -0
  29. thingsboard/endpoint/message_format/json_format.py +144 -0
  30. thingsboard/endpoint/message_format/jsonzip_format.py +8 -0
  31. thingsboard/endpoint/message_format/thingsboard_format.py +11 -0
  32. thingsboard/endpoint/mqtt/__init__.py +15 -0
  33. thingsboard/endpoint/mqtt/client.py +265 -0
  34. thingsboard/endpoint/mqtt/pending_update.py +21 -0
  35. thingsboard/endpoint/mqtt/persistence.py +232 -0
  36. thingsboard/endpoint/node/__init__.py +3 -0
  37. thingsboard/endpoint/node/node.py +115 -0
  38. thingsboard/endpoint/object/__init__.py +8 -0
  39. thingsboard/endpoint/object/object.py +249 -0
  40. thingsboard/endpoint/properties_endpoint_configuration.py +28 -0
  41. thingsboard/endpoint/runtime/__init__.py +4 -0
  42. thingsboard/endpoint/runtime/node.py +71 -0
  43. thingsboard/endpoint/runtime/object.py +80 -0
  44. thingsboard/endpoint/topicuuid.py +106 -0
  45. thingsboard/endpoint/version.py +14 -0
  46. thingsboard_endpoint-0.1.0.dist-info/METADATA +68 -0
  47. thingsboard_endpoint-0.1.0.dist-info/RECORD +50 -0
  48. thingsboard_endpoint-0.1.0.dist-info/WHEEL +5 -0
  49. thingsboard_endpoint-0.1.0.dist-info/licenses/LICENSE +21 -0
  50. thingsboard_endpoint-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,6 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Tell python that there are more sub-packages present, physically located elsewhere.
4
+ # See: https://stackoverflow.com/questions/8936884/python-import-path-packages-with-the-same-name-in-different-folders
5
+ import pkgutil
6
+ __path__ = pkgutil.extend_path(__path__, __name__)
@@ -0,0 +1,15 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Tell python that there are more sub-packages present, physically located elsewhere.
4
+ # See: https://stackoverflow.com/questions/8936884/python-import-path-packages-with-the-same-name-in-different-folders
5
+ import pkgutil
6
+
7
+ __path__ = pkgutil.extend_path(__path__, __name__)
8
+
9
+ import logging
10
+ from .version import __version__ as version
11
+
12
+ # Do not output logs if logging module is not configured
13
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
14
+
15
+ logging.getLogger(__name__).info('thingsboard-endpoint version: %s' % version)
@@ -0,0 +1,5 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .attribute import Attribute
4
+ from .constraint import AttributeConstraint
5
+ from .type import AttributeType
@@ -0,0 +1,274 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import logging
4
+
5
+ from thingsboard.common.utils import timestamp_helpers
6
+ from thingsboard.endpoint.attribute.constraint import AttributeConstraint as AttributeConstraint
7
+ from thingsboard.endpoint.attribute.type import AttributeType as AttributeType
8
+ from thingsboard.endpoint.exception.modification_exception import ModificationException
9
+ from thingsboard.endpoint.exception.invalid_attribute_exception import InvalidAttributeException
10
+ from thingsboard.endpoint.interface.attribute_listener import AttributeListener
11
+ from thingsboard.endpoint.interface.unique_identifiable import UniqueIdentifiable
12
+ from thingsboard.endpoint.topicuuid import TopicUuid
13
+
14
+
15
+ class Attribute(UniqueIdentifiable):
16
+ """The leaf information in the endpoint data model
17
+ """
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ def __init__(self):
22
+ self._name = None # type: str or None
23
+ self._parent = None
24
+ self._topic_uuid = None # type: TopicUuid or None
25
+ self._constraint = None
26
+ self._type = None # type: AttributeType or None
27
+ self._timestamp = None
28
+ self._value = None # type: bool or int or float or str or None
29
+ self._listeners = None # type: list[AttributeListener] or None
30
+
31
+ def add_listener(self, listener):
32
+ """Adds the given listener to the list of listeners that will get informed about a change of the attribute.
33
+
34
+ :param listener: Reference to the object implementing the AttributeListener interface to add.
35
+ :type listener: AttributeListener
36
+ """
37
+ if listener is not None:
38
+ # Lazy initialization of the listener list
39
+ if self._listeners is None:
40
+ self._listeners = []
41
+
42
+ # Finally add the listener
43
+ self._listeners.append(listener)
44
+
45
+ def remove_listener(self, listener):
46
+ """Removes the given listener from the list of listeners.
47
+
48
+ :param listener: Reference to the object implementing the AttributeListener interface to remove.
49
+ :type listener: AttributeListener
50
+ """
51
+ if listener is not None and self._listeners is not None:
52
+ self._listeners.remove(listener)
53
+
54
+ ######################################################################
55
+ # UniqueIdentifiable implementation
56
+ #
57
+ def get_uuid(self):
58
+ if not self._topic_uuid:
59
+ self._topic_uuid = TopicUuid(self)
60
+
61
+ return self._topic_uuid
62
+
63
+ def set_value(self, value, timestamp=None):
64
+ if not timestamp:
65
+ timestamp = timestamp_helpers.get_time_in_milliseconds()
66
+
67
+ # TODO Check constraint.
68
+
69
+ # Update value
70
+ self._timestamp = timestamp
71
+ self._set_value_with_type_check(value)
72
+
73
+ # Send change to cloud.
74
+ if self.get_parent():
75
+ self.get_parent().attribute_has_changed_by_endpoint(self)
76
+
77
+ def set_value_from_cloud(self, value, timestamp):
78
+ """Updates the value from the cloud.
79
+
80
+ Note that this method should not be used by endpoints, as it guarantees
81
+ that only attributes with semantics compatible with cloud updates can be updated.
82
+
83
+ :param value: New value to set from cloud.
84
+ :param timestamp: Timestamp of the value from the cloud.
85
+ :return: True if the value was updated, false if not.
86
+ """
87
+
88
+ # TODO: Check if the cloud can change the attribute.
89
+ # self.constraint.cloudWillChange()
90
+
91
+ # Check if the value from the cloud is older than the actual one and do nothing if that is the case.
92
+ if self._timestamp is not None and self._timestamp >= timestamp:
93
+ print('Warning: Ignoring new value from cloud. Not valid timestamp!')
94
+ return False
95
+
96
+ # Update the value
97
+ self._timestamp = timestamp
98
+ self._set_value_with_type_check(value)
99
+
100
+ # Notify the cloud.
101
+ if self._parent is not None:
102
+ self._parent.attribute_has_changed_by_cloud(self)
103
+
104
+ # Notify all listeners.
105
+ if self._listeners:
106
+ for listener in self._listeners:
107
+ # noinspection unchecked
108
+ listener.attribute_has_changed(self, from_cloud=True)
109
+ else:
110
+ self.log.warning('No listeners connected to attribute \"' + self.get_name() + '\"!')
111
+
112
+ return True
113
+
114
+ def _set_value_with_type_check(self, value):
115
+ """Assigns a new value and checks the rvalue type.
116
+ """
117
+ if self._type == AttributeType.Boolean:
118
+ self._value = bool(value)
119
+ elif self._type == AttributeType.Integer:
120
+ self._value = int(value)
121
+ elif self._type == AttributeType.Number:
122
+ self._value = float(value)
123
+ elif self._type == AttributeType.String:
124
+ assert isinstance(value, str)
125
+ self._value = value
126
+ else:
127
+ self.log.warning('Need to assign value which has unsupported type!')
128
+ self.set_type(type(value)) # Try to set the type
129
+ self._value = value
130
+
131
+ def get_type(self):
132
+ """Returns the actual type of the attribute."""
133
+ if self._type is not None:
134
+ return self._type.type
135
+ else:
136
+ self.log.warning('Deprecated call to get_type()!')
137
+ return AttributeType.from_raw_type(type(self._value))
138
+
139
+ def get_type_as_string(self):
140
+ """Returns the actual type of the attribute as a string."""
141
+ if self._type is not None:
142
+ return self._type.to_string()
143
+ else:
144
+ self.log.warning('Deprecated call to get_type_as_string()!')
145
+ AttributeType.from_raw_type_to_string(type(self._value))
146
+
147
+ ######################################################################
148
+ # Named item implementation
149
+ #
150
+ def get_name(self):
151
+ return self._name if self._name else 'unknown'
152
+
153
+ def set_name(self, name):
154
+ """
155
+ :type name: str
156
+ """
157
+ # If the attribute already has a name (we are renaming the attribute) then fail with a runtime exception.
158
+ if self._name is not None:
159
+ raise ModificationException('The Attribute has already a name (Renaming attributes is forbidden)!')
160
+
161
+ assert name and name != '', 'Name not valid!'
162
+ self._name = name
163
+
164
+ def get_value(self):
165
+ """Returns the current value of the attribute.
166
+ :return: Attributes current value.
167
+ """
168
+ return self._value
169
+
170
+ def set_type(self, the_type: [bool, int, float, str]):
171
+ """Sets the type of the attribute.
172
+
173
+ Note that the type of an attribute is not allowed to change over time, so if
174
+ the attribute already has a type, the method fails with an runtime exception.
175
+
176
+ :param the_type Python type like bool, int, float and str
177
+ :type [bool, int, float, str]
178
+ """
179
+ if self._value:
180
+ raise ModificationException('The Attribute has already a type (Changing the type is not allowed)!')
181
+
182
+ if the_type in (bool, int, float, bytes, str):
183
+ self._value = the_type()
184
+
185
+ # Init to invalid
186
+ self._type = AttributeType(AttributeType.Invalid)
187
+
188
+ # Set attribute type accordingly
189
+ if the_type in (bool,):
190
+ self._type = AttributeType(AttributeType.Boolean)
191
+ elif the_type in (int,):
192
+ self._type = AttributeType(AttributeType.Integer)
193
+ elif the_type in (float,):
194
+ self._type = AttributeType(AttributeType.Number)
195
+ else:
196
+ assert the_type in (bytes, str), 'Seems we got a new type!'
197
+ self._type = AttributeType(AttributeType.String)
198
+ else:
199
+ raise InvalidAttributeException(the_type)
200
+
201
+ ######################################################################
202
+ # Public API
203
+ #
204
+ def get_timestamp(self):
205
+ return self._timestamp
206
+
207
+ def set_static_value(self, value):
208
+ """Initializes the static value
209
+
210
+ This can be only done using static attributes (@StaticAttribute or @Static).
211
+ The value of a static attribute can be changed as often as wanted, the only constraint is that the node
212
+ containing the static attribute has not been registered within the endpoint.
213
+
214
+ :param value: The initial value to set
215
+ :return:
216
+ """
217
+ # TODO Check constraint
218
+ # self._constraint.endpointWillChangeStatic()
219
+
220
+ self._set_value_with_type_check(value)
221
+
222
+ def get_parent(self):
223
+ return self._parent
224
+
225
+ def set_parent(self, parent):
226
+ """Sets the parent of the attribute. Note that attributes can not be moved, so this method throws a runtime
227
+ exception if someone tries to move the attribute to a new parent.
228
+ """
229
+ # If the attribute already has a parent (we are moving the attribute) then fail with a runtime exception.
230
+ if self._parent:
231
+ raise ModificationException('The parent of an Attribute can never be changed ' +
232
+ '(Attributes can not be moved)!')
233
+ # assert isinstance(parent, AttributeContainer), 'Wrong type for parent attribute!'
234
+ self._parent = parent
235
+
236
+ def get_constraint(self):
237
+ return self._constraint
238
+
239
+ def set_constraint(self, constraint):
240
+ """
241
+
242
+ :param constraint:
243
+ :type constraint: AttributeConstraint
244
+ :return:
245
+ """
246
+
247
+ # Convert to AttributeConstraint if 'constraint' parameter is a string
248
+ if isinstance(constraint, str):
249
+ constraint = AttributeConstraint(constraint)
250
+
251
+ assert isinstance(constraint, AttributeConstraint), 'Wrong type'
252
+
253
+ if self._constraint:
254
+ raise ModificationException('The Attribute has already a constraint ' +
255
+ '(Changing constraints is not allowed)!')
256
+ # Set the constraint
257
+ self._constraint = constraint
258
+
259
+ def to_json(self, encoder):
260
+ """Pick out the attributes we want to store / publish.
261
+ """
262
+ attr_dict = {
263
+ 'type': AttributeType.from_raw_type_to_string(self._value),
264
+ 'value': self._value,
265
+ 'constraint': self._constraint
266
+ }
267
+
268
+ # Name should not be added for @online message
269
+ # attr_dict['name'] = self._name
270
+
271
+ # Get the type of the value and convert it to endpoint attribute type
272
+ # attr_dict['timestamp'] = self._timestamp
273
+
274
+ return encoder.default(attr_dict)
@@ -0,0 +1,68 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ class AttributeConstraint(object):
4
+ """Defines the different possible attribute constraints.
5
+ """
6
+
7
+ # The attribute is a static value and can't be changed during runtime.
8
+ Static = 0
9
+
10
+ # The attribute is a parameter that can be configured from the cloud and its value should be saved locally on
11
+ # the "Endpoint".
12
+ Parameter = 1
13
+
14
+ # The attribute is a status.
15
+ Status = 2
16
+
17
+ # The attribute is a set point that can be changed from the cloud. Note that there is no guarantee that the value
18
+ # of set points are stored within the "Endpoint" and might be initialized to the default value on the next power
19
+ # cycle.
20
+ SetPoint = 3
21
+
22
+ # The attribute is a measure of any kind and can change at any time.
23
+ Measure = 4
24
+
25
+ # If unknown or not set.
26
+ Invalid = -1
27
+
28
+ def __init__(self, value):
29
+
30
+ if isinstance(value, str):
31
+ if value.lower() == 'static':
32
+ self._value = self.Static
33
+ elif value.lower() == 'parameter':
34
+ self._value = self.Parameter
35
+ elif value.lower() == 'status':
36
+ self._value = self.Status
37
+ elif value.lower() == 'setpoint':
38
+ self._value = self.SetPoint
39
+ elif value.lower() == 'measure':
40
+ self._value = self.Measure
41
+ elif value.lower() == 'invalid':
42
+ self._value = self.Invalid
43
+ elif isinstance(value, int):
44
+ self._value = value
45
+ else:
46
+ self._value = self.Invalid
47
+
48
+ def get_value(self):
49
+ return self._value
50
+
51
+ def to_string(self):
52
+ if self._value == self.Static:
53
+ return 'Static'
54
+ elif self._value == self.Parameter:
55
+ return 'Parameter'
56
+ elif self._value == self.Status:
57
+ return 'Status'
58
+ elif self._value == self.SetPoint:
59
+ return 'SetPoint'
60
+ elif self._value == self.Measure:
61
+ return 'Measure'
62
+ else:
63
+ return 'Invalid'
64
+
65
+ def to_json(self, encoder):
66
+ """Pick out the attributes we want to store / publish.
67
+ """
68
+ return self.to_string()
@@ -0,0 +1,97 @@
1
+ import inspect
2
+ import logging
3
+ import traceback
4
+
5
+
6
+ # Links:
7
+ # - http://stackoverflow.com/questions/5189699/how-can-i-make-a-class-property-in-python
8
+ # - http://www.artima.com/weblogs/viewpost.jsp?thread=240845
9
+ # - https://www.codementor.io/python/tutorial/advanced-use-python-decorators-class-function
10
+ # - http://krzysztofzuraw.com/blog/2016/python-class-decorators.html
11
+ #
12
+ class endpoint_attribute(object):
13
+ """Decorator class adding the possibility to auto-update a model attribute to the cloud whenever it changes.
14
+
15
+ The model attribute's name corresponds to the method which gets decorated with this
16
+ decorator (similar to the @property decorator).
17
+ """
18
+
19
+ def __init__(self, fget, fset=None):
20
+ self._fget = fget
21
+ self._fset = fset
22
+
23
+ def __get__(self, obj, the_type=None):
24
+ """
25
+ :return: A value
26
+ """
27
+ try:
28
+ # Try if fget method is another descriptor
29
+ return self._fget.__get__(obj, the_type)()
30
+ except TypeError:
31
+ pass
32
+
33
+ try:
34
+ return self._fget.__get__(obj)
35
+ except TypeError:
36
+ # Call real fget method
37
+ return self._fget(obj) # Called for example when having ABC meta derived property
38
+
39
+ def __set__(self, obj, value):
40
+ """Assigns value to decorated attribute.
41
+
42
+ :param obj: The composite instance containing the attribute
43
+ :param value: The value to assign to the attribute
44
+ :return: Value returned by the setter method.
45
+ """
46
+
47
+ try:
48
+ # Try if fget method is another descriptor
49
+ ret_value = self._fget.__set__(obj, value)
50
+ except Exception:
51
+ if not self._fset:
52
+ raise AttributeError('Can\'t set attribute. No setter provided!')
53
+ # Use setter method to assign new value
54
+ ret_value = self._fset.__get__(obj)(value)
55
+
56
+ try:
57
+ # Update value on the cloud by calling method '_update_endpoint_attribute'
58
+ # which must be provided by the instance having the endpoint_attribute
59
+ # decorated attribute.
60
+ #
61
+ # Give as second parameter the value using the fget.__get__ property and
62
+ # not the value parameter. It may be different.
63
+ # obj._update_endpoint_attribute(self._fget.__name__, self._fget.__get__(obj)())
64
+ obj._update_endpoint_attribute(self.__name__, self.__get__(obj))
65
+ except (AttributeError, TypeError):
66
+ traceback.print_exc()
67
+ callback_name = '_update_endpoint_attribute'
68
+
69
+ if not hasattr(obj, callback_name):
70
+ logging.error(f'Method \'{callback_name}\' not provided!')
71
+ else:
72
+ attr = getattr(obj, callback_name)
73
+ # It should be a method
74
+ if not inspect.ismethod(attr):
75
+ logging.error(f'\'{callback_name}\' must be a method!')
76
+ return ret_value
77
+
78
+ def setter(self, fset):
79
+ """Explicitly sets the setter method for the attribute.
80
+ """
81
+ # Check if fget method is another descriptor
82
+ if hasattr(self._fget, 'setter'):
83
+ # Give the fset method to it. fset needs to be hierarchically seen a leaf method
84
+ self._fget.setter(fset)
85
+ self._fset = fset
86
+ else:
87
+ self._fset = fset
88
+ return self
89
+
90
+ @property
91
+ def __name__(self):
92
+ try:
93
+ return self._fget.__name__
94
+ except AttributeError:
95
+ # @property does not have an attribute '__name__'. We need to go
96
+ # deeper to reach the name of the decorated method
97
+ return self._fget.fget.__name__
@@ -0,0 +1,85 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from thingsboard.endpoint.exception.invalid_attribute_type_exception import InvalidAttributeTypeException
4
+
5
+
6
+ class AttributeType(object):
7
+ """Identifies the different data types of attributes currently supported by endpoint.
8
+ """
9
+ Invalid = 0 # Invalid data type
10
+ Boolean = 1 # The attribute's value is of type boolean
11
+ Integer = 2 # The attribute's value is of type short, int or long
12
+ Number = 3 # The attribute's value is of type float or double
13
+ String = 4 # The attribute's value is of type String
14
+
15
+ def __init__(self, attribute_type):
16
+ super(AttributeType, self).__init__()
17
+ # Check if parameter is valid and yell otherwise
18
+ if attribute_type in (self.Invalid, self.Boolean, self.Integer, self.Number, self.String):
19
+ self._type = attribute_type
20
+ else:
21
+ raise InvalidAttributeTypeException(attribute_type)
22
+
23
+ @classmethod
24
+ def from_raw_type(cls, raw_type) -> int:
25
+ """Converts a standard type to its endpoint type representation.
26
+ :raw_type The standard type to convert from.
27
+ :return The corresponding endpoint type.
28
+ """
29
+ if isinstance(raw_type, bool):
30
+ return cls.Boolean
31
+ elif isinstance(raw_type, int):
32
+ return cls.Integer
33
+ elif isinstance(raw_type, float):
34
+ return cls.Number
35
+ elif isinstance(raw_type, str) or isinstance(raw_type, bytes):
36
+ return cls.String
37
+ else:
38
+ return cls.Invalid
39
+
40
+ @classmethod
41
+ def from_raw_type_to_string(cls, raw_type) -> str:
42
+ """Converts a standard type to a string.
43
+ :raw_type The standard type to convert from.
44
+ :return The type represented as a string.
45
+ """
46
+ if isinstance(raw_type, bool):
47
+ return 'Boolean'
48
+ elif isinstance(raw_type, int):
49
+ return 'Integer'
50
+ elif isinstance(raw_type, float):
51
+ return 'Number'
52
+ elif isinstance(raw_type, str) or isinstance(raw_type, bytes):
53
+ return 'String'
54
+ else:
55
+ return 'Invalid'
56
+
57
+ @property
58
+ def type(self):
59
+ return self._type
60
+
61
+ def to_string(self) -> str:
62
+ """Converts AttributeType to string.
63
+ :return The type in string format
64
+ """
65
+ if self._type == self.Boolean:
66
+ return 'Boolean'
67
+ elif self._type == self.Integer:
68
+ return 'Integer'
69
+ elif self._type == self.Number:
70
+ return 'Number'
71
+ elif self._type == self.String:
72
+ return 'String'
73
+ else:
74
+ return 'Invalid'
75
+
76
+ def __eq__(self, other):
77
+ """== operator to work with attribute types."""
78
+ if isinstance(other, int):
79
+ return self._type == other
80
+ else:
81
+ raise InvalidAttributeTypeException(other)
82
+
83
+ def __ne__(self, other):
84
+ """!= operator to work with attribute types."""
85
+ return not self.__eq__(other)
@@ -0,0 +1,7 @@
1
+ # Tell python that there are more sub-packages present, physically located elsewhere.
2
+ # See: https://stackoverflow.com/questions/8936884/python-import-path-packages-with-the-same-name-in-different-folders
3
+ import pkgutil
4
+
5
+ __path__ = pkgutil.extend_path(__path__, __name__)
6
+
7
+ from .model_to_cloud import Model2CloudConnector