thingsboard-endpoint 0.1.0__tar.gz

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 (56) hide show
  1. thingsboard_endpoint-0.1.0/LICENSE +21 -0
  2. thingsboard_endpoint-0.1.0/PKG-INFO +68 -0
  3. thingsboard_endpoint-0.1.0/README.md +32 -0
  4. thingsboard_endpoint-0.1.0/pyproject.toml +14 -0
  5. thingsboard_endpoint-0.1.0/setup.cfg +4 -0
  6. thingsboard_endpoint-0.1.0/setup.py +199 -0
  7. thingsboard_endpoint-0.1.0/src/thingsboard/__init__.py +6 -0
  8. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/__init__.py +15 -0
  9. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/attribute/__init__.py +5 -0
  10. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/attribute/attribute.py +274 -0
  11. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/attribute/constraint.py +68 -0
  12. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/attribute/decorator.py +97 -0
  13. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/attribute/type.py +85 -0
  14. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/connector/__init__.py +7 -0
  15. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/connector/model_to_cloud.py +409 -0
  16. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/endpoint.py +635 -0
  17. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/exception/__init__.py +1 -0
  18. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/exception/invalid_attribute_exception.py +13 -0
  19. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/exception/invalid_attribute_type_exception.py +6 -0
  20. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/exception/invalid_property_exception.py +7 -0
  21. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/exception/modification_exception.py +5 -0
  22. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/factory/__init__.py +9 -0
  23. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/factory/xml.py +111 -0
  24. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/__init__.py +16 -0
  25. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/attribute_container.py +60 -0
  26. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/attribute_listener.py +23 -0
  27. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/message_format.py +59 -0
  28. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/named_item.py +29 -0
  29. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/node_container.py +26 -0
  30. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/object_container.py +90 -0
  31. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/unique_identifiable.py +18 -0
  32. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/interface/uuid.py +48 -0
  33. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/message_format/__init__.py +1 -0
  34. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/message_format/factory.py +34 -0
  35. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/message_format/json_format.py +144 -0
  36. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/message_format/jsonzip_format.py +8 -0
  37. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/message_format/thingsboard_format.py +11 -0
  38. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/mqtt/__init__.py +15 -0
  39. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/mqtt/client.py +265 -0
  40. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/mqtt/pending_update.py +21 -0
  41. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/mqtt/persistence.py +232 -0
  42. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/node/__init__.py +3 -0
  43. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/node/node.py +115 -0
  44. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/object/__init__.py +8 -0
  45. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/object/object.py +249 -0
  46. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/properties_endpoint_configuration.py +28 -0
  47. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/runtime/__init__.py +4 -0
  48. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/runtime/node.py +71 -0
  49. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/runtime/object.py +80 -0
  50. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/topicuuid.py +106 -0
  51. thingsboard_endpoint-0.1.0/src/thingsboard/endpoint/version.py +14 -0
  52. thingsboard_endpoint-0.1.0/src/thingsboard_endpoint.egg-info/PKG-INFO +68 -0
  53. thingsboard_endpoint-0.1.0/src/thingsboard_endpoint.egg-info/SOURCES.txt +54 -0
  54. thingsboard_endpoint-0.1.0/src/thingsboard_endpoint.egg-info/dependency_links.txt +1 -0
  55. thingsboard_endpoint-0.1.0/src/thingsboard_endpoint.egg-info/requires.txt +2 -0
  56. thingsboard_endpoint-0.1.0/src/thingsboard_endpoint.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 HES-SO Valais
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: thingsboard-endpoint
3
+ Version: 0.1.0
4
+ Summary: ThingsBoard endpoint package
5
+ Home-page: https://gitlab.com/things-board
6
+ Author: HES-SO Valais, School of Engineering, Sion
7
+ Author-email: thomas.sterren@hes-so.ch
8
+ License-Expression: MIT
9
+ Project-URL: Bug Tracker, https://gitlab.com/things-board/thingsboard-endpoint/-/issues
10
+ Project-URL: Source Code, https://gitlab.com/things-board/thingsboard-endpoint
11
+ Project-URL: Documentation, https://gitlab.com/things-board/thingsboard-endpoint#thingsboard-endpoint
12
+ Keywords: ThingsBoard endpoint library
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Education
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Intended Audience :: Information Technology
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Operating System :: OS Independent
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: thingsboard-common<1.0.0
26
+ Requires-Dist: configobj<6.0.0,>=5.0.9
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: home-page
31
+ Dynamic: keywords
32
+ Dynamic: license-file
33
+ Dynamic: project-url
34
+ Dynamic: requires-dist
35
+ Dynamic: summary
36
+
37
+ # ThingsBoard Endpoint
38
+
39
+ > Note:
40
+ >
41
+ > This is not an official project of the [ThingsBoard](https://thingsboard.io/) authors! Please refer to
42
+ > [ThingsBoard - Open-source IoT Platform](https://github.com/thingsboard) for official ThingsBoard projects!
43
+
44
+ The ThingsBoard Endpoint package adds a data Meta-Model to the ThingsBoard devices sending data over MQTT. This
45
+ allows to provide a data model for each device type.
46
+
47
+ The devices providing telemetry and attributes information to ThingsBoard are named **Endpoint**s to remove confusion
48
+ added when using names like _clients_ or _devices_.
49
+
50
+ ## Endpoint Data Meta-Model
51
+ The object meta-structure is given as follows:
52
+ - An EndPoint can have Nodes
53
+ - Nodes can have Objects
54
+ - Objects can have Objects and/or Attributes
55
+
56
+ The [Attribute](https://gitlab.com/things-board/thingsboard-endpoint/-/blob/main/src/thingsboard/endpoint/attribute/attribute.py) objects represent the leafs in the data structure.
57
+
58
+ An `Attribute` is responsible to synchronise a variable or an attribute to the cloud. Depending on the write policy the
59
+ attribute may be changed from the cloud in which case the attribute gets updated on the endpoint.
60
+
61
+ To set up your endpoint data model you should first think about how you would like to show up your IoT device in the
62
+ cloud, keeping in mind the _EndPoint->Node->Object->Attribute_ meta-structure implied.
63
+
64
+ We encourage you to provide the data model using an [XML](https://en.wikipedia.org/wiki/XML) or
65
+ [JSON](https://en.wikipedia.org/wiki/JSON) based file. The file needs then to be parsed and the Endpoint's object
66
+ structure set up accordingly. There are [Factory](https://gitlab.com/things-board/thingsboard-endpoint/-/tree/main/src/thingsboard/endpoint/factory)
67
+ classes provided to simplify this process (XML only for the moment). The `Factory` class reads a data model file and
68
+ creates the Endpoint object.
@@ -0,0 +1,32 @@
1
+ # ThingsBoard Endpoint
2
+
3
+ > Note:
4
+ >
5
+ > This is not an official project of the [ThingsBoard](https://thingsboard.io/) authors! Please refer to
6
+ > [ThingsBoard - Open-source IoT Platform](https://github.com/thingsboard) for official ThingsBoard projects!
7
+
8
+ The ThingsBoard Endpoint package adds a data Meta-Model to the ThingsBoard devices sending data over MQTT. This
9
+ allows to provide a data model for each device type.
10
+
11
+ The devices providing telemetry and attributes information to ThingsBoard are named **Endpoint**s to remove confusion
12
+ added when using names like _clients_ or _devices_.
13
+
14
+ ## Endpoint Data Meta-Model
15
+ The object meta-structure is given as follows:
16
+ - An EndPoint can have Nodes
17
+ - Nodes can have Objects
18
+ - Objects can have Objects and/or Attributes
19
+
20
+ The [Attribute](https://gitlab.com/things-board/thingsboard-endpoint/-/blob/main/src/thingsboard/endpoint/attribute/attribute.py) objects represent the leafs in the data structure.
21
+
22
+ An `Attribute` is responsible to synchronise a variable or an attribute to the cloud. Depending on the write policy the
23
+ attribute may be changed from the cloud in which case the attribute gets updated on the endpoint.
24
+
25
+ To set up your endpoint data model you should first think about how you would like to show up your IoT device in the
26
+ cloud, keeping in mind the _EndPoint->Node->Object->Attribute_ meta-structure implied.
27
+
28
+ We encourage you to provide the data model using an [XML](https://en.wikipedia.org/wiki/XML) or
29
+ [JSON](https://en.wikipedia.org/wiki/JSON) based file. The file needs then to be parsed and the Endpoint's object
30
+ structure set up accordingly. There are [Factory](https://gitlab.com/things-board/thingsboard-endpoint/-/tree/main/src/thingsboard/endpoint/factory)
31
+ classes provided to simplify this process (XML only for the moment). The `Factory` class reads a data model file and
32
+ creates the Endpoint object.
@@ -0,0 +1,14 @@
1
+ [build-system]
2
+ requires = ["setuptools>=67.6.1", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "thingsboard-endpoint"
7
+ dynamic = ["version", "classifiers", "dependencies", "urls", "keywords", "authors", "description"]
8
+ requires-python = ">=3.9"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICEN[CS]E*"]
12
+
13
+ [tool.setuptools.dynamic]
14
+ version = {attr = "thingsboard.endpoint.version"}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Script to install project using pip
5
+
6
+ See:
7
+ https://packaging.python.org/en/latest/distributing.html
8
+ https://github.com/pypa/sampleproject
9
+ """
10
+
11
+ import os
12
+ # To use a consistent encoding
13
+ from codecs import open
14
+
15
+ # Always prefer setuptools over distutils
16
+ from setuptools import setup, find_packages
17
+
18
+
19
+ def read_version_info():
20
+ with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
21
+ 'src/thingsboard/endpoint/version.py')) as vf:
22
+ content = vf.readlines()
23
+ for line in content:
24
+ if '__version__' in line:
25
+ values = line.split('=')
26
+ version = values[1]
27
+ version = version.strip('\n')
28
+ version = version.strip('\r')
29
+ version = version.replace('\'', '')
30
+ version = version.strip(' ')
31
+ return version
32
+ return '0.0.0'
33
+
34
+
35
+ __version__ = read_version_info()
36
+
37
+ # Get the long description from the README file
38
+ current_directory = os.path.abspath(os.path.dirname(__file__))
39
+ with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
40
+ long_description = f.read()
41
+
42
+ # Arguments marked as "Required" below must be included for upload to PyPI.
43
+ # Fields marked as "Optional" may be commented out.
44
+
45
+ setup(
46
+ # This is the name of your project. The first time you publish this
47
+ # package, this name will be registered for you. It will determine how
48
+ # users can install this project, e.g.:
49
+ #
50
+ # $ pip install <sample project>
51
+ #
52
+ # And where it will live on PyPI: https://pypi.org/project/sampleproject/
53
+ #
54
+ # There are some restrictions on what makes a valid project name
55
+ # specification here:
56
+ # https://packaging.python.org/specifications/core-metadata/#name
57
+ name='thingsboard-endpoint', # Required
58
+
59
+ # Versions should comply with PEP 440:
60
+ # https://www.python.org/dev/peps/pep-0440/
61
+ #
62
+ # For a discussion on single-sourcing the version across setup.py and the
63
+ # project code, see
64
+ # https://packaging.python.org/en/latest/single_source_version.html
65
+ version=__version__, # Required
66
+
67
+ # This is a one-line description or tagline of what your project does. This
68
+ # corresponds to the "Summary" metadata field:
69
+ # https://packaging.python.org/specifications/core-metadata/#summary
70
+ description='ThingsBoard endpoint package', # Required
71
+
72
+ # This is an optional longer description of your project that represents
73
+ # the body of text which users will see when they visit PyPI.
74
+ #
75
+ # Often, this is the same as your README, so you can just read it in from
76
+ # that file directly (as we have already done above)
77
+ #
78
+ # This field corresponds to the "Description" metadata field:
79
+ # https://packaging.python.org/specifications/core-metadata/#description-optional
80
+ # long_description=long_description, # Optional
81
+ long_description=long_description,
82
+
83
+ long_description_content_type='text/markdown',
84
+
85
+ # This should be a valid link to your project's main homepage.
86
+ #
87
+ # This field corresponds to the "Home-Page" metadata field:
88
+ # https://packaging.python.org/specifications/core-metadata/#home-page-optional
89
+ url='https://gitlab.com/things-board', # Optional
90
+
91
+ project_urls={
92
+ "Bug Tracker": "https://gitlab.com/things-board/thingsboard-endpoint/-/issues",
93
+ "Source Code": "https://gitlab.com/things-board/thingsboard-endpoint",
94
+ "Documentation": "https://gitlab.com/things-board/thingsboard-endpoint#thingsboard-endpoint",
95
+ },
96
+
97
+ # This should be your name or the name of the organization which owns the
98
+ # project.
99
+ author='HES-SO Valais, School of Engineering, Sion', # Optional
100
+
101
+ # This should be a valid email address corresponding to the author listed
102
+ # above.
103
+ author_email='thomas.sterren@hes-so.ch', # Optional
104
+
105
+ # Classifiers help users find your project by categorizing it.
106
+ #
107
+ # For a list of valid classifiers, see
108
+ # https://pypi.python.org/pypi?%3Aaction=list_classifiers
109
+ classifiers=[ # Optional
110
+ # How mature is this project? Common values are
111
+ # 3 - Alpha
112
+ # 4 - Beta
113
+ # 5 - Production/Stable
114
+ 'Development Status :: 3 - Alpha',
115
+
116
+ # Indicate who your project is intended for
117
+ 'Intended Audience :: Developers',
118
+ 'Intended Audience :: Education',
119
+ 'Intended Audience :: Science/Research',
120
+ 'Intended Audience :: Information Technology',
121
+ 'Topic :: Software Development :: Libraries :: Python Modules',
122
+
123
+ # Specify the Python versions you support here. In particular, ensure
124
+ # that you indicate whether you support Python 2, Python 3 or both.
125
+ 'Programming Language :: Python :: 3.12',
126
+ 'Programming Language :: Python :: 3.13',
127
+
128
+ 'Operating System :: OS Independent',
129
+ ],
130
+
131
+ # This field adds keywords for your project which will appear on the
132
+ # project page. What does your project relate to?
133
+ #
134
+ # Note that this is a string of words separated by whitespace, not a list.
135
+ keywords='ThingsBoard endpoint library', # Optional
136
+
137
+ # You can just specify package directories manually here if your project is
138
+ # simple. Or you can use find_packages().
139
+ #
140
+ # Alternatively, if you just want to distribute a single Python file, use
141
+ # the `py_modules` argument instead as follows, which will expect a file
142
+ # called `my_module.py` to exist:
143
+ #
144
+ # py_modules=["my_module"],
145
+ #
146
+ packages=find_packages('src'), # Required
147
+ package_dir={'': 'src'},
148
+
149
+ # This field lists other packages that your project depends on to run.
150
+ # Any package you put here will be installed by pip when your project is
151
+ # installed, so they must be valid existing projects.
152
+ #
153
+ # For an analysis of "install_requires" vs pip's requirements files see:
154
+ # https://packaging.python.org/en/latest/requirements.html
155
+ install_requires=['thingsboard-common<1.0.0',
156
+ 'configobj>=5.0.9,<6.0.0'], # Optional
157
+
158
+ # List additional groups of dependencies here (e.g. development
159
+ # dependencies). Users will be able to install these using the "extras"
160
+ # syntax, for example:
161
+ #
162
+ # $ pip install <sample project>[dev]
163
+ #
164
+ # Similar to `install_requires` above, these must be valid existing
165
+ # projects.
166
+ extras_require={ # Optional
167
+ # 'tests': ['coverage'],
168
+ },
169
+
170
+ # If there are data files included in your packages that need to be
171
+ # installed, specify them here.
172
+ #
173
+ # If using Python 2.6 or earlier, then these have to be included in
174
+ # MANIFEST.in as well.
175
+ package_data={ # Optional
176
+ # 'sample': ['package_data.dat'],
177
+ },
178
+
179
+ # Although 'package_data' is the preferred approach, in some case you may
180
+ # need to place data files outside of your packages. See:
181
+ # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
182
+ #
183
+ # In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
184
+ # data_files=[('my_data', ['data/data_file'])], # Optional
185
+ data_files=[], # Optional
186
+
187
+ # To provide executable scripts, use entry points in preference to the
188
+ # "scripts" keyword. Entry points provide cross-platform support and allow
189
+ # `pip` to create the appropriate form of executable for the target
190
+ # platform.
191
+ #
192
+ # For example, the following would provide a command called `sample` which
193
+ # executes the function `main` from this package when invoked:
194
+ # entry_points={ # Optional
195
+ # 'console_scripts': [
196
+ # 'sample=sample:main',
197
+ # ],
198
+ # },
199
+ )
@@ -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)