tangods-mcmax 1.0.3__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.
@@ -0,0 +1,162 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
@@ -0,0 +1,58 @@
1
+ stages:
2
+ - pre-commit
3
+ - build
4
+ - test
5
+ - deploy
6
+
7
+ precommit-job:
8
+ image: python:3.11-bookworm
9
+ stage: pre-commit
10
+ before_script:
11
+ - python -m venv ci-venv
12
+ - source ci-venv/bin/activate
13
+ - pip install --upgrade pip
14
+ - pip install pre-commit
15
+ script:
16
+ - pre-commit run --all
17
+
18
+ build-job:
19
+ image: python:3.11-bookworm
20
+ stage: build
21
+ before_script:
22
+ - apt update
23
+ - apt install -y cppzmq-dev libboost-dev libboost-python-dev libtango-dev libomniorb4-dev
24
+ - python -m venv ci-venv
25
+ - source ci-venv/bin/activate
26
+ - pip install --upgrade pip
27
+ script:
28
+ - pip install build wheel setuptools_scm
29
+ - python -m build
30
+ artifacts:
31
+ paths:
32
+ - dist/
33
+
34
+ unit-test-job:
35
+ image: python:3.11-bookworm
36
+ stage: test
37
+ before_script:
38
+ - apt update
39
+ - apt install -y cppzmq-dev libboost-dev libboost-python-dev libtango-dev libomniorb4-dev
40
+ - python -m venv ci-venv
41
+ - source ci-venv/bin/activate
42
+ - pip install --upgrade pip
43
+ script:
44
+ - pip install '.[test]'
45
+ - pytest -v
46
+
47
+ deploy:
48
+ image: python:3.11-bookworm
49
+ stage: deploy
50
+ only:
51
+ - tags
52
+ before_script:
53
+ - python -m venv ci-venv
54
+ - source ci-venv/bin/activate
55
+ - pip install --upgrade pip
56
+ - pip install twine
57
+ script:
58
+ - twine upload dist/* -u __token__ -p $PYPI_API_TOKEN
@@ -0,0 +1,24 @@
1
+ ---
2
+ repos:
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v5.0.0
5
+ hooks:
6
+ - id: trailing-whitespace
7
+ - id: check-json
8
+ - id: trailing-whitespace
9
+ args: [--markdown-linebreak-ext=md]
10
+ - id: mixed-line-ending
11
+ - id: fix-byte-order-marker
12
+ - id: check-executables-have-shebangs
13
+ - id: check-merge-conflict
14
+ - id: check-symlinks
15
+ - repo: https://github.com/pycqa/flake8
16
+ rev: 7.1.1
17
+ hooks:
18
+ - id: flake8
19
+ - repo: https://github.com/psf/black
20
+ rev: 24.10.0
21
+ hooks:
22
+ - id: black
23
+ language_version: python3
24
+ args: [-l 79]
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.2
2
+ Name: tangods-mcmax
3
+ Version: 1.0.3
4
+ Summary: A tango device server to control the microcontrollers in the project MC-MAX
5
+ Author-email: Antonio Bartalesi <antonio.bartalesi@gmail.com>, Laura Torres Garcia <lautg88@gmail.com>
6
+ Project-URL: repository, https://gitlab.com/ABartalesi/mc-max-tango-device-server
7
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pytango>=9.5
11
+ Requires-Dist: paho-mqtt>=2.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+
15
+ # Tango Device Server for the MC-MAX project
16
+
17
+ This tango device server connects to an mqtt broker using the paho-mqtt library
18
+ and upon success reads the esp-32 self description topic, and starts a tango
19
+ device with dynamic attributes and commands.
20
+
21
+ ## Properties
22
+
23
+ Name | Description
24
+ ---- | ----
25
+ `broker` | A string, URI of the mqtt broker
26
+ `username` | The username for the mqtt broker connection
27
+ `password` | The password for the mqtt broker connection
28
+ `mqtt_name` | The name of the microcontroller in the mqtt topic tree. Usually it's the hostname of the microcontroller (without domain).
@@ -0,0 +1,14 @@
1
+ # Tango Device Server for the MC-MAX project
2
+
3
+ This tango device server connects to an mqtt broker using the paho-mqtt library
4
+ and upon success reads the esp-32 self description topic, and starts a tango
5
+ device with dynamic attributes and commands.
6
+
7
+ ## Properties
8
+
9
+ Name | Description
10
+ ---- | ----
11
+ `broker` | A string, URI of the mqtt broker
12
+ `username` | The username for the mqtt broker connection
13
+ `password` | The password for the mqtt broker connection
14
+ `mqtt_name` | The name of the microcontroller in the mqtt topic tree. Usually it's the hostname of the microcontroller (without domain).
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+
3
+ requires = ["setuptools", "setuptools_scm", "build"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [tool.setuptools_scm]
7
+ write_to = "src/mcmax/_version.py"
8
+
9
+ [project]
10
+ dynamic = ["version"]
11
+ name = "tangods-mcmax"
12
+ dependencies = [
13
+ "pytango>=9.5",
14
+ "paho-mqtt>=2.0",
15
+ ]
16
+ authors = [
17
+ {name = "Antonio Bartalesi", email = "antonio.bartalesi@gmail.com"},
18
+ {name = "Laura Torres Garcia", email = "lautg88@gmail.com"},
19
+ ]
20
+ description = "A tango device server to control the microcontrollers in the project MC-MAX"
21
+ readme = "README.md"
22
+ classifiers = [
23
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ test = [
28
+ "pytest",
29
+ ]
30
+
31
+ [project.urls]
32
+ repository = "https://gitlab.com/ABartalesi/mc-max-tango-device-server"
33
+
34
+ [project.scripts]
35
+ McMaxTangoDs = "mcmax:main"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,73 @@
1
+ # Specifications for the MC-MAX project
2
+
3
+ The MC-MAX project encompasses four components:
4
+
5
+ 1. Microcontroller firmware
6
+ 2. Tango device server
7
+ 3. A data formatting specification to allow the two system above to communicate, described [further down](#mqtt-data-exchange-format) in this document.
8
+ 4. CI/CD toolchain (gitlab CI + ansible) to monitor the firmware and deploy updates.
9
+
10
+ ## Microcontroller firmware
11
+
12
+ The microcontroller must belong to Espressif's ESP32 family.
13
+
14
+ The firmware must be compiled using the [esp-idf](https://github.com/espressif/esp-idf) toolchain. This is because it simplify devOps.
15
+
16
+ The Microcontroller must have the following features:
17
+ 1. Use OTA firmware update: it should be possible to update the microcontroller remotely.
18
+ 2. Use MQTT protocol: simple and easy, the microcontroller should describe its own features and firmware.
19
+ 3. Self describe its features according to the [MQTT data exchange specification](#mqtt-data-exchange-format).
20
+ 4. [*Not confirmed*] display a web page for configuration. In any case, the MQTT broker address must be configured somehow.
21
+
22
+ ## Tango DS
23
+
24
+ There should be only **one** tango device server class, capable of adapting to all the different firmwares.
25
+
26
+ One tango device connects to one microcontroller.
27
+
28
+ It must have a tango property for the microcontroller hostname, to find the appropriate device in the MQTT tree.
29
+
30
+ It must populate attributes and commands dynamically, by reading the microcontroller self description through MQTT.
31
+
32
+ ## MQTT data exchange specification
33
+
34
+ The microcontroller must advertise the following:
35
+ 1. Firmware flavor (a name, example "Relay controller").
36
+ 2. Firmware version. Must be the same as the output of `git-describe`.
37
+ 3. Self description. A JSON formatted dictionary having all the tango goodies: which tango attributes, which tango commands and so on.
38
+ 4. Somewhere to publish the data.
39
+ 5. Somewhere to listen for data.
40
+
41
+ Here is how the MQTT topic tree should look like:
42
+
43
+ ```
44
+ mc_max
45
+ └─ <hostname, without domain>
46
+ ├─ firmware_name: str
47
+ ├─ firmware_version: str
48
+ ├─ tango_attributes: str (list of valid keyword dictionaries to create attributes, JSON formatted)
49
+ ├─ tango_commands: str (list of valid keyword dictionaries to create commands, JSON formatted)
50
+ ├─ mc_output
51
+ │ ├─ variable_1: str
52
+ │ ├─ variable_2: str
53
+ │ ├─ ...
54
+ │ └─ variable_n: str
55
+ ├─ mc_input
56
+ │ ├─ variable_1: str
57
+ │ ├─ variable_2: str
58
+ │ ├─ ...
59
+ │ └─ variable_n: str
60
+ └─ command
61
+ ├─ command_1: str
62
+ ├─ command_2: str
63
+ ├─ ...
64
+ └─ command_n: str
65
+ ```
66
+
67
+ So to have a complete example:
68
+
69
+ `mc_max/mydevice/mc_output/voltage` could contain useful data that must be translated to a tango attribute; while `mc_max/mydevice/mc_input/voltage` could be used as a setpoint for a controlled process variable.
70
+
71
+ For a command, there is a list called `command`. Commands always have a string as `dtype_in`. Exaple writing `"1"` into `mc_max/mydevice/command/enable_voltage` could tell the microcontroller to perform a specific action such as switching voltage on.
72
+
73
+ This feature could be used with more complex parameters, to pass data together with a command. Example: writing `'{"time": "1s", "voltage": "2V"}'` into the topic `mc_max/mydevice/command/pulse_voltage` could perform the complex action of pulsing the voltage on the microcontroller.
@@ -0,0 +1,3 @@
1
+ __all__ = ["main", "McMaxTangoDs", "MqttMessage"]
2
+
3
+ from .mcmax import main, McMaxTangoDs, MqttMessage
@@ -0,0 +1,21 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
5
+
6
+ TYPE_CHECKING = False
7
+ if TYPE_CHECKING:
8
+ from typing import Tuple
9
+ from typing import Union
10
+
11
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
12
+ else:
13
+ VERSION_TUPLE = object
14
+
15
+ version: str
16
+ __version__: str
17
+ __version_tuple__: VERSION_TUPLE
18
+ version_tuple: VERSION_TUPLE
19
+
20
+ __version__ = version = '1.0.3'
21
+ __version_tuple__ = version_tuple = (1, 0, 3)
@@ -0,0 +1,316 @@
1
+ import json
2
+ from tango.server import (
3
+ AttrDataFormat,
4
+ Device,
5
+ attribute,
6
+ command,
7
+ device_property,
8
+ )
9
+ from tango import AttrQuality, AttrWriteType, DevState, DispLevel
10
+ from tango import GreenMode
11
+ from paho.mqtt.client import Client
12
+ from paho.mqtt.enums import CallbackAPIVersion, MQTTProtocolVersion
13
+ from datetime import datetime
14
+ from time import time
15
+ from dataclasses import dataclass
16
+ import builtins
17
+ import types
18
+
19
+
20
+ @dataclass
21
+ class MqttMessage:
22
+ """MQTT message"""
23
+
24
+ payload: str
25
+ topic: str
26
+
27
+
28
+ class McMaxTangoDs(Device):
29
+ """Tango device server to control MC-MAX microcontrollers thru MQTT"""
30
+
31
+ green_mode = GreenMode.Asyncio
32
+
33
+ # To connect to the MQTT server
34
+ broker = device_property(dtype=str, default_value="localhost")
35
+ username = device_property(dtype=str, default_value="")
36
+ password = device_property(dtype=str, default_value="")
37
+ mqtt_name = device_property(dtype=str, default_value="")
38
+
39
+ firmware_name = attribute(dtype=str, display_level=DispLevel.EXPERT)
40
+ firmware_version = attribute(dtype=str, display_level=DispLevel.EXPERT)
41
+
42
+ async def init_device(self):
43
+ self.mc_attributes_description = []
44
+ self.rec_messages: list[MqttMessage] = []
45
+ self.old_attributes = []
46
+ self.old_commands = []
47
+ self.max_msg_circular_buffer = 10
48
+ self.last_received_values = {}
49
+ self.conversions = {}
50
+ self._firmware_name = ""
51
+ self._firmware_version = ""
52
+
53
+ await super().init_device()
54
+ self.info_stream("Connecting to MQTT server")
55
+ self.set_state(DevState.INIT)
56
+ self.set_status(
57
+ f"Initialization started {datetime.now()}.\nTrying to connect."
58
+ )
59
+
60
+ # Creating a client instance
61
+ self.mqtt = Client(
62
+ callback_api_version=CallbackAPIVersion.VERSION2,
63
+ protocol=MQTTProtocolVersion.MQTTv5,
64
+ )
65
+ try:
66
+ self.connect()
67
+ except Exception as exc:
68
+ msg = f"Error connecting to the MQTT server: {exc}"
69
+ self.error_stream(msg)
70
+ self.set_state(DevState.FAULT)
71
+ self.set_status(msg)
72
+ return
73
+
74
+ # Subscribe to firmware name
75
+ topic = f"mc_max/{self.mqtt_name}/firmware_name"
76
+ self.mqtt.subscribe(topic=topic)
77
+ self.mqtt.message_callback_add(
78
+ sub=topic, callback=self.process_firmware_name
79
+ )
80
+
81
+ # Subscribe to firmware version
82
+ topic = f"mc_max/{self.mqtt_name}/firmware_version"
83
+ self.mqtt.subscribe(topic=topic)
84
+ self.mqtt.message_callback_add(
85
+ sub=topic, callback=self.process_firmware_version
86
+ )
87
+
88
+ topic = f"mc_max/{self.mqtt_name}/tango_attributes"
89
+ self.mqtt.subscribe(topic=topic)
90
+ self.mqtt.message_callback_add(
91
+ sub=topic, callback=self.process_attributes_self_description
92
+ )
93
+
94
+ topic = f"mc_max/{self.mqtt_name}/tango_commands"
95
+ self.mqtt.subscribe(topic=topic)
96
+ self.mqtt.message_callback_add(
97
+ sub=topic, callback=self.process_commands_self_description
98
+ )
99
+
100
+ # TODO mc should be able to publish tango state
101
+ self.set_status(
102
+ f"Initialization completed {datetime.now()}.\n"
103
+ "Waiting for Microcontroller self description..."
104
+ )
105
+
106
+ # MQTT connection
107
+ def connect(self):
108
+ self.mqtt.username_pw_set(
109
+ username=self.username, password=self.password
110
+ )
111
+ self.mqtt.connect(host=self.broker)
112
+ self.mqtt.loop_start()
113
+
114
+ def process_firmware_name(self, client, userdata, msg):
115
+ self._firmware_name = msg.payload
116
+
117
+ def process_firmware_version(self, client, userdata, msg):
118
+ self._firmware_version = msg.payload
119
+
120
+ def process_attributes_self_description(self, client, userdata, msg):
121
+ # load as JSON
122
+ try:
123
+ self.mc_attributes_description = json.loads(msg.payload)
124
+ except Exception as exc:
125
+ msg = (
126
+ "Error in microcontroller self description: "
127
+ f"Exception was: {exc}"
128
+ )
129
+ self.error_stream(msg)
130
+ raise RuntimeError(msg)
131
+
132
+ # Clean up old attributes
133
+ for old_attribute in self.old_attributes:
134
+ try:
135
+ self.remove_attribute(old_attribute)
136
+ except Exception:
137
+ self.warn_stream(
138
+ f"Tried to remove attribute {attribute} "
139
+ "without success, ignoring."
140
+ )
141
+ self.old_attributes = []
142
+
143
+ # Process the list of attribute dictionaries
144
+ for new_attribute in self.mc_attributes_description:
145
+ if "access" in new_attribute:
146
+ new_attribute["access"] = getattr(
147
+ AttrWriteType, new_attribute["access"]
148
+ )
149
+ if "display_level" in new_attribute:
150
+ new_attribute["display_level"] = getattr(
151
+ DispLevel, new_attribute["display_level"]
152
+ )
153
+ if "dformat" in new_attribute:
154
+ new_attribute["dformat"] = getattr(
155
+ AttrDataFormat, new_attribute["dformat"]
156
+ )
157
+ attr = attribute(**new_attribute)
158
+ if attr.attr_write in [
159
+ AttrWriteType.READ_WRITE,
160
+ AttrWriteType.WRITE,
161
+ AttrWriteType.READ_WITH_WRITE,
162
+ ]:
163
+ write_method = self.generic_write
164
+ else:
165
+ write_method = None
166
+ self.add_attribute(
167
+ attr, r_meth=self.generic_read, w_meth=write_method
168
+ )
169
+
170
+ self.old_attributes.append(attr.name)
171
+ try:
172
+ _dtype = new_attribute["dtype"]
173
+ if _dtype == "bool":
174
+ self.conversions[attr.name] = self.str2bool
175
+ else:
176
+ self.conversions[attr.name] = getattr(builtins, _dtype)
177
+ except KeyError:
178
+ msg = (
179
+ "Error in microcontroller self description: no dtype "
180
+ f"specified for attribute {attr.name}"
181
+ )
182
+ self.error_stream(msg)
183
+ raise RuntimeError(msg)
184
+
185
+ self.set_change_event(attr.name, True)
186
+ mc_output_data_topic = (
187
+ f"mc_max/{self.mqtt_name}/mc_output/{attr.name}"
188
+ )
189
+ self.mqtt.subscribe(topic=mc_output_data_topic)
190
+ self.debug_stream(f"Subscribing to {mc_output_data_topic}")
191
+
192
+ def generic_event_pusher(client, userdata, msg):
193
+ # get attribute name
194
+ att_name = msg.topic.split("/")[-1]
195
+ try:
196
+ conversion_function = self.conversions[att_name]
197
+ value = conversion_function(msg.payload.decode("utf-8"))
198
+ quality = AttrQuality.ATTR_VALID
199
+ self.last_received_values[att_name] = value
200
+ self.debug_stream(f"{att_name} = {value}")
201
+ except AttributeError:
202
+ # The dtype is not a builtin
203
+ self.last_received_values[att_name] = None
204
+ msg = (
205
+ "Error in microcontroller self description: dtype "
206
+ f"{self.conversions[att_name]} for attribute "
207
+ f"{att_name} does not match any python "
208
+ "builtin data type"
209
+ )
210
+ self.error_stream(msg)
211
+ # In this case, we interrupt the code flow
212
+ # because we don't even know what dtype we should push
213
+ raise RuntimeError(msg)
214
+ except Exception as exc:
215
+ self.last_received_values[att_name] = None
216
+ # trick to have a placeholder value of correct type
217
+ # Must be set to ATTR_INVALID
218
+ value = conversion_function()
219
+ quality = AttrQuality.ATTR_INVALID
220
+ self.error_stream(
221
+ f"Could not translate value {value} for attribute "
222
+ f"{att_name}, exception was {exc}"
223
+ )
224
+ self.push_change_event(att_name, value, time(), quality)
225
+
226
+ # give this function a unique name and make it an attribute
227
+ specific_callback_name = f"{attr.name}_event_pusher"
228
+ setattr(self, specific_callback_name, generic_event_pusher)
229
+ self.mqtt.message_callback_add(
230
+ sub=mc_output_data_topic,
231
+ callback=getattr(self, specific_callback_name),
232
+ )
233
+ if self.dev_state() is DevState.INIT:
234
+ # here if first self description received since init
235
+ self.set_state(DevState.ON)
236
+ self.set_status(
237
+ f"Microcontroller description received {datetime.now()}.\n"
238
+ "Device operating normally."
239
+ )
240
+
241
+ def _create_method(self, name):
242
+ @command(dtype_in=str)
243
+ async def dynamic_method(self, parameters):
244
+ topic = f"mc_max/{self.mqtt_name}/command/{name}"
245
+ payload = parameters
246
+ self.mqtt.publish(topic=topic, payload=payload)
247
+
248
+ dynamic_method.__name__ = name
249
+
250
+ return dynamic_method
251
+
252
+ def process_commands_self_description(self, client, userdata, msg):
253
+ # load as JSON
254
+ try:
255
+ self.mc_commands_description = json.loads(msg.payload)
256
+ except Exception as exc:
257
+ msg = (
258
+ "Error in microcontroller commands self description: "
259
+ f"Exception was: {exc}"
260
+ )
261
+ self.error_stream(msg)
262
+ raise RuntimeError(msg)
263
+
264
+ # Clean up old commands
265
+ for old_command in self.old_commands:
266
+ try:
267
+ self.remove_command(old_command)
268
+ except Exception:
269
+ self.warn_stream(
270
+ f"Failed to remove command {old_command}. " "Ignoring it"
271
+ )
272
+ self.old_commands = []
273
+
274
+ # Process the list of attribute dictionaries
275
+ for new_command in self.mc_commands_description:
276
+ setattr(
277
+ self,
278
+ new_command["name"],
279
+ types.MethodType(
280
+ self._create_method(new_command["name"]), self
281
+ ),
282
+ )
283
+ self.add_command(getattr(self, new_command["name"]))
284
+ self.old_commands.append(new_command["name"])
285
+
286
+ async def generic_read(self, attr):
287
+ self.debug_stream(f"Generic read for attribute {attr.get_name()}")
288
+ if attr.get_name() not in self.last_received_values:
289
+ attr.set_quality(AttrQuality.ATTR_INVALID)
290
+ return
291
+ return self.last_received_values[attr.get_name()]
292
+
293
+ async def generic_write(self, attr):
294
+ topic = f"mc_max/{self.mqtt_name}/mc_input/{attr.get_name()}"
295
+ payload = str(attr.get_write_value())
296
+ self.mqtt.publish(topic=topic, payload=payload)
297
+
298
+ async def read_firmware_version(self):
299
+ return self._firmware_version
300
+
301
+ async def read_firmware_name(self):
302
+ return self._firmware_name
303
+
304
+ def str2bool(self, data: str) -> bool:
305
+ if data.lower() in ("true", "yes", "on", "1"):
306
+ return True
307
+ else:
308
+ return False
309
+
310
+
311
+ def main():
312
+ McMaxTangoDs.run_server()
313
+
314
+
315
+ if __name__ == "__main__":
316
+ main()
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.2
2
+ Name: tangods-mcmax
3
+ Version: 1.0.3
4
+ Summary: A tango device server to control the microcontrollers in the project MC-MAX
5
+ Author-email: Antonio Bartalesi <antonio.bartalesi@gmail.com>, Laura Torres Garcia <lautg88@gmail.com>
6
+ Project-URL: repository, https://gitlab.com/ABartalesi/mc-max-tango-device-server
7
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pytango>=9.5
11
+ Requires-Dist: paho-mqtt>=2.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+
15
+ # Tango Device Server for the MC-MAX project
16
+
17
+ This tango device server connects to an mqtt broker using the paho-mqtt library
18
+ and upon success reads the esp-32 self description topic, and starts a tango
19
+ device with dynamic attributes and commands.
20
+
21
+ ## Properties
22
+
23
+ Name | Description
24
+ ---- | ----
25
+ `broker` | A string, URI of the mqtt broker
26
+ `username` | The username for the mqtt broker connection
27
+ `password` | The password for the mqtt broker connection
28
+ `mqtt_name` | The name of the microcontroller in the mqtt topic tree. Usually it's the hostname of the microcontroller (without domain).
@@ -0,0 +1,17 @@
1
+ .gitignore
2
+ .gitlab-ci.yml
3
+ .pre-commit-config.yaml
4
+ LICENSE
5
+ README.md
6
+ pyproject.toml
7
+ specs/README.md
8
+ src/mcmax/__init__.py
9
+ src/mcmax/_version.py
10
+ src/mcmax/mcmax.py
11
+ src/tangods_mcmax.egg-info/PKG-INFO
12
+ src/tangods_mcmax.egg-info/SOURCES.txt
13
+ src/tangods_mcmax.egg-info/dependency_links.txt
14
+ src/tangods_mcmax.egg-info/entry_points.txt
15
+ src/tangods_mcmax.egg-info/requires.txt
16
+ src/tangods_mcmax.egg-info/top_level.txt
17
+ tests/test_mcmax.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ McMaxTangoDs = mcmax:main
@@ -0,0 +1,5 @@
1
+ pytango>=9.5
2
+ paho-mqtt>=2.0
3
+
4
+ [test]
5
+ pytest
@@ -0,0 +1,206 @@
1
+ import pytest
2
+ import json
3
+ from tango import DevState
4
+ from tango.server import command
5
+ from tango.test_context import DeviceTestContext
6
+ from unittest.mock import patch
7
+
8
+ # Import tango DS
9
+ from mcmax import McMaxTangoDs, MqttMessage
10
+
11
+
12
+ MQTT_NAME = "test"
13
+
14
+
15
+ @pytest.fixture
16
+ def deviceProxy():
17
+ device = DeviceTestContext(
18
+ McMaxTangoDs,
19
+ properties={
20
+ "broker": "localhost",
21
+ "username": "user",
22
+ "password": "password",
23
+ "mqtt_name": MQTT_NAME,
24
+ },
25
+ process=True,
26
+ )
27
+ yield device
28
+
29
+
30
+ def testImport():
31
+ """Test importation of the Tango DS"""
32
+ from mcmax import McMaxTangoDs # noqa: F401
33
+
34
+
35
+ @patch("mcmax.mcmax.Client")
36
+ def testInit(mocker, deviceProxy):
37
+ """Test device goes into INIT when initialised"""
38
+ with deviceProxy as proxy:
39
+ assert proxy.status().startswith("Initialization completed")
40
+ assert proxy.state() == DevState.INIT
41
+
42
+
43
+ @patch(
44
+ "mcmax.mcmax.Client.username_pw_set",
45
+ side_effect=ValueError("PROBLEM"),
46
+ )
47
+ def testConnectionFailed(mocker, deviceProxy):
48
+ """Test device failed to connect to the MQTT broker"""
49
+ with deviceProxy as proxy:
50
+ assert proxy.state() == DevState.FAULT
51
+ assert proxy.status() == "Error connecting to the MQTT server: PROBLEM"
52
+
53
+
54
+ def testProcessingFirmware():
55
+ """Test device can process firmware information"""
56
+
57
+ # Process the messages
58
+ McMaxTangoDs.process_firmware_name(
59
+ McMaxTangoDs,
60
+ None,
61
+ None,
62
+ MqttMessage(
63
+ topic=f"mc_max/{MQTT_NAME}/firmware_name", payload="TestFirmware"
64
+ ),
65
+ )
66
+ McMaxTangoDs.process_firmware_version(
67
+ McMaxTangoDs,
68
+ None,
69
+ None,
70
+ MqttMessage(
71
+ topic=f"mc_max/{MQTT_NAME}/firmware_version", payload="1.0.0"
72
+ ),
73
+ )
74
+
75
+ # Assert values
76
+ assert McMaxTangoDs._firmware_name == "TestFirmware"
77
+ assert McMaxTangoDs._firmware_version == "1.0.0"
78
+
79
+
80
+ def testProcessingAttributesSelfDescription():
81
+ """Test device can receive attribute self-description information"""
82
+
83
+ class MqttMessageRaw:
84
+ topic = ""
85
+ payload = None
86
+
87
+ def __init__(self, topic, payload):
88
+ self.topic = topic
89
+ self.payload = payload
90
+
91
+ class TestDev(McMaxTangoDs):
92
+ @command(dtype_in=str)
93
+ async def test_process_attribute_self_description(self, string):
94
+ msg = MqttMessage(payload=string, topic="test/notopic")
95
+ self.process_attributes_self_description(None, None, msg)
96
+
97
+ @command(dtype_in=float)
98
+ async def test_add_fake_voltage_value(self, value):
99
+ msg = MqttMessageRaw(
100
+ topic=f"mc_max/{MQTT_NAME}/mc_output/voltage",
101
+ payload=str(value).encode("ascii"),
102
+ )
103
+ self.voltage_event_pusher(None, None, msg)
104
+
105
+ with DeviceTestContext(
106
+ TestDev,
107
+ properties={
108
+ "broker": "localhost",
109
+ "username": "user",
110
+ "password": "password",
111
+ "mqtt_name": MQTT_NAME,
112
+ },
113
+ process=True,
114
+ ) as device:
115
+
116
+ attributes_description = [
117
+ {
118
+ "name": "voltage",
119
+ "dtype": "float",
120
+ "Unit": "V",
121
+ "fget": "default_get",
122
+ }
123
+ ]
124
+ attributes_description = json.dumps(attributes_description)
125
+
126
+ # Process the messages
127
+ device.test_process_attribute_self_description(attributes_description)
128
+
129
+ assert "voltage" in device.get_attribute_list()
130
+
131
+ device.test_add_fake_voltage_value(123.4)
132
+
133
+ assert device.voltage == 123.4
134
+
135
+ attributes_description_2 = [
136
+ {
137
+ "name": "voltage_2",
138
+ "dtype": "float",
139
+ "Unit": "V",
140
+ "fget": "default_get",
141
+ }
142
+ ]
143
+ attributes_description_2 = json.dumps(attributes_description_2)
144
+
145
+ # Process the messages
146
+ device.test_process_attribute_self_description(
147
+ attributes_description_2
148
+ )
149
+
150
+ assert "voltage" not in device.get_attribute_list()
151
+
152
+ assert "voltage_2" in device.get_attribute_list()
153
+
154
+
155
+ @patch("mcmax.mcmax.Client")
156
+ def testDynamicCommandCreation(mocker, deviceProxy):
157
+ """Test device can send messages to MQTT broker"""
158
+
159
+ class TestDev(McMaxTangoDs):
160
+ @command(dtype_in=str)
161
+ async def test_process_commands_self_description(self, string):
162
+ msg = MqttMessage(payload=string, topic="test/notopic")
163
+ self.process_commands_self_description(None, None, msg)
164
+
165
+ with DeviceTestContext(
166
+ TestDev,
167
+ properties={
168
+ "broker": "localhost",
169
+ "username": "user",
170
+ "password": "password",
171
+ "mqtt_name": MQTT_NAME,
172
+ },
173
+ process=True,
174
+ ) as device:
175
+
176
+ commands_description = [
177
+ {
178
+ "name": "new_command",
179
+ }
180
+ ]
181
+ commands_description = json.dumps(commands_description)
182
+
183
+ # Process the messages
184
+ device.test_process_commands_self_description(commands_description)
185
+
186
+ assert "new_command" in device.get_command_list()
187
+
188
+ device.new_command("test string input")
189
+
190
+ device.test_process_commands_self_description(commands_description)
191
+
192
+ commands_description_2 = [
193
+ {
194
+ "name": "new_command_2",
195
+ }
196
+ ]
197
+ commands_description_2 = json.dumps(commands_description_2)
198
+
199
+ # Process the second mesage
200
+ device.test_process_commands_self_description(commands_description_2)
201
+
202
+ assert "new_command" not in device.get_command_list()
203
+
204
+ assert "new_command_2" in device.get_command_list()
205
+
206
+ device.new_command_2("test string input")