raise-suite-sdk 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.
@@ -0,0 +1,291 @@
1
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
2
+ EUPL © the European Union 2007, 2016
3
+
4
+ This European Union Public Licence (the ‘EUPL’) applies to the Work (as
5
+ defined below) which is provided under the terms of this Licence. Any use of
6
+ the Work, other than as authorised under this Licence is prohibited (to the
7
+ extent such use is covered by a right of the copyright holder of the Work).
8
+
9
+ The Work is provided under the terms of this Licence when the Licensor (as
10
+ defined below) has placed the following notice immediately following the
11
+ copyright notice for the Work:
12
+
13
+ Licensed under the EUPL
14
+
15
+ or has expressed by any other means his willingness to license under the EUPL.
16
+
17
+ 1. Definitions
18
+
19
+ In this Licence, the following terms have the following meaning:
20
+
21
+ - ‘The Licence’: this Licence.
22
+
23
+ - ‘The Original Work’: the work or software distributed or communicated by the
24
+ Licensor under this Licence, available as Source Code and also as Executable
25
+ Code as the case may be.
26
+
27
+ - ‘Derivative Works’: the works or software that could be created by the
28
+ Licensee, based upon the Original Work or modifications thereof. This
29
+ Licence does not define the extent of modification or dependence on the
30
+ Original Work required in order to classify a work as a Derivative Work;
31
+ this extent is determined by copyright law applicable in the country
32
+ mentioned in Article 15.
33
+
34
+ - ‘The Work’: the Original Work or its Derivative Works.
35
+
36
+ - ‘The Source Code’: the human-readable form of the Work which is the most
37
+ convenient for people to study and modify.
38
+
39
+ - ‘The Executable Code’: any code which has generally been compiled and which
40
+ is meant to be interpreted by a computer as a program.
41
+
42
+ - ‘The Licensor’: the natural or legal person that distributes or communicates
43
+ the Work under the Licence.
44
+
45
+ - ‘Contributor(s)’: any natural or legal person who modifies the Work under
46
+ the Licence, or otherwise contributes to the creation of a Derivative Work.
47
+
48
+ - ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of
49
+ the Work under the terms of the Licence.
50
+
51
+ - ‘Distribution’ or ‘Communication’: any act of selling, giving, lending,
52
+ renting, distributing, communicating, transmitting, or otherwise making
53
+ available, online or offline, copies of the Work or providing access to its
54
+ essential functionalities at the disposal of any other natural or legal
55
+ person.
56
+
57
+ 2. Scope of the rights granted by the Licence
58
+
59
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
60
+ sublicensable licence to do the following, for the duration of copyright
61
+ vested in the Original Work:
62
+
63
+ - use the Work in any circumstance and for all usage,
64
+ - reproduce the Work,
65
+ - modify the Work, and make Derivative Works based upon the Work,
66
+ - communicate to the public, including the right to make available or display
67
+ the Work or copies thereof to the public and perform publicly, as the case
68
+ may be, the Work,
69
+ - distribute the Work or copies thereof,
70
+ - lend and rent the Work or copies thereof,
71
+ - sublicense rights in the Work or copies thereof.
72
+
73
+ Those rights can be exercised on any media, supports and formats, whether now
74
+ known or later invented, as far as the applicable law permits so.
75
+
76
+ In the countries where moral rights apply, the Licensor waives his right to
77
+ exercise his moral right to the extent allowed by law in order to make
78
+ effective the licence of the economic rights here above listed.
79
+
80
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights
81
+ to any patents held by the Licensor, to the extent necessary to make use of
82
+ the rights granted on the Work under this Licence.
83
+
84
+ 3. Communication of the Source Code
85
+
86
+ The Licensor may provide the Work either in its Source Code form, or as
87
+ Executable Code. If the Work is provided as Executable Code, the Licensor
88
+ provides in addition a machine-readable copy of the Source Code of the Work
89
+ along with each copy of the Work that the Licensor distributes or indicates,
90
+ in a notice following the copyright notice attached to the Work, a repository
91
+ where the Source Code is easily and freely accessible for as long as the
92
+ Licensor continues to distribute or communicate the Work.
93
+
94
+ 4. Limitations on copyright
95
+
96
+ Nothing in this Licence is intended to deprive the Licensee of the benefits
97
+ from any exception or limitation to the exclusive rights of the rights owners
98
+ in the Work, of the exhaustion of those rights or of other applicable
99
+ limitations thereto.
100
+
101
+ 5. Obligations of the Licensee
102
+
103
+ The grant of the rights mentioned above is subject to some restrictions and
104
+ obligations imposed on the Licensee. Those obligations are the following:
105
+
106
+ Attribution right: The Licensee shall keep intact all copyright, patent or
107
+ trademarks notices and all notices that refer to the Licence and to the
108
+ disclaimer of warranties. The Licensee must include a copy of such notices and
109
+ a copy of the Licence with every copy of the Work he/she distributes or
110
+ communicates. The Licensee must cause any Derivative Work to carry prominent
111
+ notices stating that the Work has been modified and the date of modification.
112
+
113
+ Copyleft clause: If the Licensee distributes or communicates copies of the
114
+ Original Works or Derivative Works, this Distribution or Communication will be
115
+ done under the terms of this Licence or of a later version of this Licence
116
+ unless the Original Work is expressly distributed only under this version of
117
+ the Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee
118
+ (becoming Licensor) cannot offer or impose any additional terms or conditions
119
+ on the Work or Derivative Work that alter or restrict the terms of the
120
+ Licence.
121
+
122
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative
123
+ Works or copies thereof based upon both the Work and another work licensed
124
+ under a Compatible Licence, this Distribution or Communication can be done
125
+ under the terms of this Compatible Licence. For the sake of this clause,
126
+ ‘Compatible Licence’ refers to the licences listed in the appendix attached to
127
+ this Licence. Should the Licensee's obligations under the Compatible Licence
128
+ conflict with his/her obligations under this Licence, the obligations of the
129
+ Compatible Licence shall prevail.
130
+
131
+ Provision of Source Code: When distributing or communicating copies of the
132
+ Work, the Licensee will provide a machine-readable copy of the Source Code or
133
+ indicate a repository where this Source will be easily and freely available
134
+ for as long as the Licensee continues to distribute or communicate the Work.
135
+
136
+ Legal Protection: This Licence does not grant permission to use the trade
137
+ names, trademarks, service marks, or names of the Licensor, except as required
138
+ for reasonable and customary use in describing the origin of the Work and
139
+ reproducing the content of the copyright notice.
140
+
141
+ 6. Chain of Authorship
142
+
143
+ The original Licensor warrants that the copyright in the Original Work granted
144
+ hereunder is owned by him/her or licensed to him/her and that he/she has the
145
+ power and authority to grant the Licence.
146
+
147
+ Each Contributor warrants that the copyright in the modifications he/she
148
+ brings to the Work are owned by him/her or licensed to him/her and that he/she
149
+ has the power and authority to grant the Licence.
150
+
151
+ Each time You accept the Licence, the original Licensor and subsequent
152
+ Contributors grant You a licence to their contributions to the Work, under the
153
+ terms of this Licence.
154
+
155
+ 7. Disclaimer of Warranty
156
+
157
+ The Work is a work in progress, which is continuously improved by numerous
158
+ Contributors. It is not a finished work and may therefore contain defects or
159
+ ‘bugs’ inherent to this type of development.
160
+
161
+ For the above reason, the Work is provided under the Licence on an ‘as is’
162
+ basis and without warranties of any kind concerning the Work, including
163
+ without limitation merchantability, fitness for a particular purpose, absence
164
+ of defects or errors, accuracy, non-infringement of intellectual property
165
+ rights other than copyright as stated in Article 6 of this Licence.
166
+
167
+ This disclaimer of warranty is an essential part of the Licence and a
168
+ condition for the grant of any rights to the Work.
169
+
170
+ 8. Disclaimer of Liability
171
+
172
+ Except in the cases of wilful misconduct or damages directly caused to natural
173
+ persons, the Licensor will in no event be liable for any direct or indirect,
174
+ material or moral, damages of any kind, arising out of the Licence or of the
175
+ use of the Work, including without limitation, damages for loss of goodwill,
176
+ work stoppage, computer failure or malfunction, loss of data or any commercial
177
+ damage, even if the Licensor has been advised of the possibility of such
178
+ damage. However, the Licensor will be liable under statutory product liability
179
+ laws as far such laws apply to the Work.
180
+
181
+ 9. Additional agreements
182
+
183
+ While distributing the Work, You may choose to conclude an additional
184
+ agreement, defining obligations or services consistent with this Licence.
185
+ However, if accepting obligations, You may act only on your own behalf and on
186
+ your sole responsibility, not on behalf of the original Licensor or any other
187
+ Contributor, and only if You agree to indemnify, defend, and hold each
188
+ Contributor harmless for any liability incurred by, or claims asserted against
189
+ such Contributor by the fact You have accepted any warranty or additional
190
+ liability.
191
+
192
+ 10. Acceptance of the Licence
193
+
194
+ The provisions of this Licence can be accepted by clicking on an icon ‘I
195
+ agree’ placed under the bottom of a window displaying the text of this Licence
196
+ or by affirming consent in any other similar way, in accordance with the rules
197
+ of applicable law. Clicking on that icon indicates your clear and irrevocable
198
+ acceptance of this Licence and all of its terms and conditions.
199
+
200
+ Similarly, you irrevocably accept this Licence and all of its terms and
201
+ conditions by exercising any rights granted to You by Article 2 of this
202
+ Licence, such as the use of the Work, the creation by You of a Derivative Work
203
+ or the Distribution or Communication by You of the Work or copies thereof.
204
+
205
+ 11. Information to the public
206
+
207
+ In case of any Distribution or Communication of the Work by means of
208
+ electronic communication by You (for example, by offering to download the Work
209
+ from a remote location) the distribution channel or media (for example, a
210
+ website) must at least provide to the public the information requested by the
211
+ applicable law regarding the Licensor, the Licence and the way it may be
212
+ accessible, concluded, stored and reproduced by the Licensee.
213
+
214
+ 12. Termination of the Licence
215
+
216
+ The Licence and the rights granted hereunder will terminate automatically upon
217
+ any breach by the Licensee of the terms of the Licence.
218
+
219
+ Such a termination will not terminate the licences of any person who has
220
+ received the Work from the Licensee under the Licence, provided such persons
221
+ remain in full compliance with the Licence.
222
+
223
+ 13. Miscellaneous
224
+
225
+ Without prejudice of Article 9 above, the Licence represents the complete
226
+ agreement between the Parties as to the Work.
227
+
228
+ If any provision of the Licence is invalid or unenforceable under applicable
229
+ law, this will not affect the validity or enforceability of the Licence as a
230
+ whole. Such provision will be construed or reformed so as necessary to make it
231
+ valid and enforceable.
232
+
233
+ The European Commission may publish other linguistic versions or new versions
234
+ of this Licence or updated versions of the Appendix, so far this is required
235
+ and reasonable, without reducing the scope of the rights granted by the
236
+ Licence. New versions of the Licence will be published with a unique version
237
+ number.
238
+
239
+ All linguistic versions of this Licence, approved by the European Commission,
240
+ have identical value. Parties can take advantage of the linguistic version of
241
+ their choice.
242
+
243
+ 14. Jurisdiction
244
+
245
+ Without prejudice to specific agreement between parties,
246
+
247
+ - any litigation resulting from the interpretation of this License, arising
248
+ between the European Union institutions, bodies, offices or agencies, as a
249
+ Licensor, and any Licensee, will be subject to the jurisdiction of the Court
250
+ of Justice of the European Union, as laid down in article 272 of the Treaty
251
+ on the Functioning of the European Union,
252
+
253
+ - any litigation arising between other parties and resulting from the
254
+ interpretation of this License, will be subject to the exclusive
255
+ jurisdiction of the competent court where the Licensor resides or conducts
256
+ its primary business.
257
+
258
+ 15. Applicable Law
259
+
260
+ Without prejudice to specific agreement between parties,
261
+
262
+ - this Licence shall be governed by the law of the European Union Member State
263
+ where the Licensor has his seat, resides or has his registered office,
264
+
265
+ - this licence shall be governed by Belgian law if the Licensor has no seat,
266
+ residence or registered office inside a European Union Member State.
267
+
268
+ Appendix
269
+
270
+ ‘Compatible Licences’ according to Article 5 EUPL are:
271
+
272
+ - GNU General Public License (GPL) v. 2, v. 3
273
+ - GNU Affero General Public License (AGPL) v. 3
274
+ - Open Software License (OSL) v. 2.1, v. 3.0
275
+ - Eclipse Public License (EPL) v. 1.0
276
+ - CeCILL v. 2.0, v. 2.1
277
+ - Mozilla Public Licence (MPL) v. 2
278
+ - GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
279
+ - Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
280
+ works other than software
281
+ - European Union Public Licence (EUPL) v. 1.1, v. 1.2
282
+ - Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
283
+ Reciprocity (LiLiQ-R+).
284
+
285
+ The European Commission may update this Appendix to later versions of the
286
+ above licences without producing a new version of the EUPL, as long as they
287
+ provide the rights granted in Article 2 of this Licence and protect the
288
+ covered Source Code from exclusive appropriation.
289
+
290
+ All other changes or additions to this Appendix require the production of a
291
+ new EUPL version.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: raise-suite-sdk
3
+ Version: 0.1.0
4
+ Summary: RAISE Suite SDK for local devices to communicate with the local RAISE Suite Agent
5
+ License: EUPL-1.2
6
+ License-File: LICENSE
7
+ Author: RAISE Suite Developers
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: OSI Approved :: European Union Public Licence 1.2 (EUPL 1.2)
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Requires-Dist: paho-mqtt (>=2.0.0,<3.0.0)
16
+ Project-URL: Repository, https://github.com/cyclopt-pc/raise-suite-sdk
17
+ Description-Content-Type: text/markdown
18
+
19
+ # RAISE Suite SDK
20
+
21
+ A Python SDK that enables local devices to communicate with a local RAISE Suite Agent over MQTT. It provides a clean, type-safe wrapper around `paho-mqtt` v2 for connecting, publishing, subscribing, and handling device messages.
22
+
23
+ ## Features
24
+ - **Modern Packaging**: Fully managed via Poetry with `pyproject.toml`.
25
+ - **Clean Namespace**: Main class exposed via `from raise_suite_sdk import MqttClient`.
26
+ - **Robust Logging**: Zero direct terminal spam. All communications use structured standard Python logging under `raise_suite_sdk`.
27
+ - **Type Hints**: Full PEP 484 type signatures for enhanced IDE autocomplete.
28
+
29
+ ## Installation
30
+
31
+ Using Poetry:
32
+ ```bash
33
+ poetry add raise-suite-sdk
34
+ ```
35
+
36
+ Or pip:
37
+ ```bash
38
+ pip install raise-suite-sdk
39
+ ```
40
+
41
+ ## Quick Start
42
+
43
+ ```python
44
+ import logging
45
+ from raise_suite_sdk import MqttClient
46
+
47
+ # Configure logging in your parent application
48
+ logging.basicConfig(level=logging.INFO)
49
+
50
+ # Define callback
51
+ def on_message_received(topic: str, payload: dict, qos: int):
52
+ print(f"Received message from {topic}: {payload}")
53
+
54
+ # Initialize and start the client
55
+ client = MqttClient(
56
+ client_id="my-app-client",
57
+ user="my_username",
58
+ password="my_password",
59
+ broker="localhost",
60
+ port=1883,
61
+ on_message=on_message_received
62
+ )
63
+
64
+ client.start()
65
+
66
+ # Publish a dictionary payload (automatically serialized to JSON)
67
+ client.publish("my/topic", {"status": "ok"}, qos=1)
68
+
69
+ # Stop the client when done
70
+ client.stop()
71
+ ```
72
+
73
+ ## License
74
+
75
+ Licensed under the European Union Public Licence 1.2 (EUPL-1.2). See [LICENSE](LICENSE) for the full text.
76
+
@@ -0,0 +1,57 @@
1
+ # RAISE Suite SDK
2
+
3
+ A Python SDK that enables local devices to communicate with a local RAISE Suite Agent over MQTT. It provides a clean, type-safe wrapper around `paho-mqtt` v2 for connecting, publishing, subscribing, and handling device messages.
4
+
5
+ ## Features
6
+ - **Modern Packaging**: Fully managed via Poetry with `pyproject.toml`.
7
+ - **Clean Namespace**: Main class exposed via `from raise_suite_sdk import MqttClient`.
8
+ - **Robust Logging**: Zero direct terminal spam. All communications use structured standard Python logging under `raise_suite_sdk`.
9
+ - **Type Hints**: Full PEP 484 type signatures for enhanced IDE autocomplete.
10
+
11
+ ## Installation
12
+
13
+ Using Poetry:
14
+ ```bash
15
+ poetry add raise-suite-sdk
16
+ ```
17
+
18
+ Or pip:
19
+ ```bash
20
+ pip install raise-suite-sdk
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ```python
26
+ import logging
27
+ from raise_suite_sdk import MqttClient
28
+
29
+ # Configure logging in your parent application
30
+ logging.basicConfig(level=logging.INFO)
31
+
32
+ # Define callback
33
+ def on_message_received(topic: str, payload: dict, qos: int):
34
+ print(f"Received message from {topic}: {payload}")
35
+
36
+ # Initialize and start the client
37
+ client = MqttClient(
38
+ client_id="my-app-client",
39
+ user="my_username",
40
+ password="my_password",
41
+ broker="localhost",
42
+ port=1883,
43
+ on_message=on_message_received
44
+ )
45
+
46
+ client.start()
47
+
48
+ # Publish a dictionary payload (automatically serialized to JSON)
49
+ client.publish("my/topic", {"status": "ok"}, qos=1)
50
+
51
+ # Stop the client when done
52
+ client.stop()
53
+ ```
54
+
55
+ ## License
56
+
57
+ Licensed under the European Union Public Licence 1.2 (EUPL-1.2). See [LICENSE](LICENSE) for the full text.
@@ -0,0 +1,26 @@
1
+ [tool.poetry]
2
+ name = "raise-suite-sdk"
3
+ version = "0.1.0"
4
+ description = "RAISE Suite SDK for local devices to communicate with the local RAISE Suite Agent"
5
+ license = "EUPL-1.2"
6
+ repository = "https://github.com/cyclopt-pc/raise-suite-sdk"
7
+ authors = ["RAISE Suite Developers"]
8
+ readme = "README.md"
9
+ packages = [{include = "raise_suite_sdk", from = "src"}]
10
+
11
+ [tool.poetry.dependencies]
12
+ python = "^3.11"
13
+ paho-mqtt = "^2.0.0"
14
+
15
+ [tool.poetry.group.dev.dependencies]
16
+ pytest = "^7.0"
17
+
18
+ [tool.pytest.ini_options]
19
+ markers = [
20
+ "unit: fast tests that do not need external services",
21
+ "integration: tests that require a running MQTT broker",
22
+ ]
23
+
24
+ [build-system]
25
+ requires = ["poetry-core"]
26
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,21 @@
1
+ import logging
2
+ from .client import MqttClient
3
+ from .exceptions import (
4
+ MqttSdkException,
5
+ MqttConnectionError,
6
+ MqttPublishError,
7
+ MqttTlsConfigurationError,
8
+ MqttSerializationError,
9
+ )
10
+
11
+ # Set default logging handler to prevent "No handler found" warnings
12
+ logging.getLogger("raise_suite_sdk").addHandler(logging.NullHandler())
13
+
14
+ __all__ = [
15
+ "MqttClient",
16
+ "MqttSdkException",
17
+ "MqttConnectionError",
18
+ "MqttPublishError",
19
+ "MqttTlsConfigurationError",
20
+ "MqttSerializationError",
21
+ ]
@@ -0,0 +1,438 @@
1
+ """Local MQTT Client Wrapper.
2
+
3
+ This client wraps the paho-mqtt library to establish clean pub-sub connections,
4
+ handles SSL/TLS, and monitors connection stability.
5
+ """
6
+
7
+ import json
8
+ import logging
9
+ import ssl
10
+ import struct
11
+ import threading
12
+ import time
13
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
14
+
15
+ from paho.mqtt import client as mqtt_client
16
+ from paho.mqtt.reasoncodes import ReasonCode
17
+ from paho.mqtt.packettypes import PacketTypes
18
+ from paho.mqtt.properties import Properties
19
+
20
+ from .exceptions import (
21
+ MqttSdkException,
22
+ MqttConnectionError,
23
+ MqttPublishError,
24
+ MqttTlsConfigurationError,
25
+ MqttSerializationError,
26
+ )
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ class _PatchedClient(mqtt_client.Client): # pylint: disable=too-few-public-methods
32
+ """Paho Client subclass that captures the PUBREC reason code.
33
+
34
+ Mosquitto sends rc=135 (Not Authorized) in PUBREC when denying a QoS 2
35
+ publish, but paho discards it before calling on_publish (which only sees
36
+ the final PUBCOMP, always rc=0). This subclass intercepts the PUBREC
37
+ reason code and substitutes it into the on_publish callback so that
38
+ reason_code.is_failure correctly reflects broker-side ACL denials.
39
+ """
40
+
41
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
42
+ super().__init__(*args, **kwargs)
43
+ self._pubrec_reason_codes: Dict[int, ReasonCode] = {} # mid → ReasonCode captured from PUBREC
44
+
45
+ def _handle_pubrec(self) -> int:
46
+ rc = super()._handle_pubrec() # let paho do state update + send PUBREL
47
+ mid, = struct.unpack("!H", self._in_packet['packet'][:2])
48
+ if self._protocol == mqtt_client.MQTTv5 and self._in_packet['remaining_length'] > 2:
49
+ reason_code = ReasonCode(PacketTypes.PUBREC)
50
+ reason_code.unpack(self._in_packet['packet'][2:])
51
+ self._pubrec_reason_codes[mid] = reason_code
52
+ return rc
53
+
54
+ def _do_on_publish(self, mid: int, reason_code: ReasonCode, properties: Optional[Properties]) -> None:
55
+ # Use the PUBREC reason code if captured; fall back to PUBCOMP reason code
56
+ real_rc = self._pubrec_reason_codes.pop(mid, reason_code)
57
+ return super()._do_on_publish(mid, real_rc, properties)
58
+
59
+
60
+ class MqttClient: # pylint: disable=too-many-instance-attributes
61
+ """MQTT client wrapper using Paho MQTT for clean, reliable pub-sub communication.
62
+
63
+ This class encapsulates connection setup, credential handling, TLS configuration,
64
+ and automatic reconnection loops. Key capabilities include:
65
+ - Custom callback handling for connections, publishing, message reception, and disconnection.
66
+ - Background reconnection logic via daemon thread (_reconnect).
67
+ - Session state tracking to re-establish active subscriptions upon reconnecting.
68
+ - JSON serialization of published payloads and message-info tracking.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ client_id: str,
74
+ user: str,
75
+ password: str,
76
+ broker: str,
77
+ port: int,
78
+ ca_cert_path: Optional[str] = None,
79
+ on_message: Optional[Callable[[str, Any, int], None]] = None,
80
+ clean_start: bool = True,
81
+ session_expiry_interval: int = 0
82
+ ) -> None:
83
+ """Initialize the MQTT client SDK.
84
+
85
+ Args:
86
+ client_id (str): Unique identifier for this client session.
87
+ user (str): Username for MQTT broker authentication.
88
+ password (str): Password/token for MQTT broker authentication.
89
+ broker (str): Address/hostname of the MQTT broker.
90
+ port (int): Port number for connecting to the broker (e.g. 1883 for TCP, 8883 for TLS).
91
+ ca_cert_path (Optional[str]): Path to custom CA certificate for TLS verification.
92
+ on_message (Optional[Callable]): Callback invoked when a message arrives.
93
+ Signature: (topic: str, payload: dict, qos: int) -> None.
94
+ clean_start (bool): If True, starts a clean connection session. If False, attempts
95
+ to resume a persistent session. Defaults to True.
96
+ session_expiry_interval (int): Time in seconds the broker remembers this session
97
+ after disconnection. Set to 0 to expire immediately. Defaults to 0.
98
+ """
99
+ # Set variables for MQTT connection
100
+ self.client_id: str = client_id
101
+ self.user: str = user
102
+ self.password: str = password
103
+ self.broker: str = broker
104
+ self.port: int = port
105
+ self.ca_cert_path: Optional[str] = ca_cert_path
106
+ self.on_message: Optional[Callable[[str, Any, int], None]] = on_message
107
+ self.clean_start: bool = clean_start
108
+ self.session_expiry_interval: int = session_expiry_interval
109
+
110
+ self.connected: bool = False
111
+ self.reconnecting: bool = False
112
+ self._stored_subscriptions: List[Tuple[str, int]] = [] # Track subscriptions for reconnecting
113
+ self._connection_announced: bool = False # Guard to prevent duplicate connection logs
114
+ self._mid_to_topic: Dict[int, Tuple[str, Optional[int]]] = {}
115
+ self._mid_to_topic_lock: threading.Lock = threading.Lock()
116
+
117
+ # Setup Logger (Inheriting from SDK parent namespace)
118
+ self.mqtt_logger = logging.getLogger(__name__)
119
+
120
+ # Initialize Client (patched subclass to capture PUBREC reason codes)
121
+ self.client = _PatchedClient(
122
+ callback_api_version=mqtt_client.CallbackAPIVersion.VERSION2,
123
+ client_id=client_id,
124
+ protocol=mqtt_client.MQTTv5
125
+ )
126
+
127
+ # Attach Callbacks
128
+ self.client.on_connect = self._on_connect
129
+ self.client.on_publish = self._on_publish
130
+ self.client.on_message = self._on_message
131
+ self.client.on_disconnect = self._on_disconnect
132
+
133
+ # Set credentials
134
+ # (Commented out token fallback logic: username/password are now strictly required)
135
+ # if password is not None and user is None:
136
+ # self.client.username_pw_set("", password)
137
+ # else:
138
+ # self.client.username_pw_set(user, password)
139
+
140
+ if not broker:
141
+ raise ValueError("Broker address must be provided.")
142
+ if not port or port <= 0:
143
+ raise ValueError("A valid port must be provided.")
144
+ if not user or not password:
145
+ raise ValueError("Both user (username) and password must be provided.")
146
+ self.client.username_pw_set(user, password)
147
+
148
+ # Enable Logger integration in Paho
149
+ self.client.enable_logger(self.mqtt_logger)
150
+
151
+ # Set TLS for secure connection
152
+ if self.ca_cert_path:
153
+ try:
154
+ self.client.tls_set(
155
+ ca_certs=self.ca_cert_path,
156
+ tls_version=ssl.PROTOCOL_TLSv1_2
157
+ )
158
+ except Exception as e:
159
+ self.mqtt_logger.error("[%s] Failed to set TLS: %s", self.client_id, e)
160
+ raise MqttTlsConfigurationError(f"Failed to set TLS with CA cert: {e}") from e
161
+ elif self.port == 8883:
162
+ try:
163
+ context = ssl.create_default_context()
164
+ self.client.tls_set_context(context)
165
+ self.client.tls_insecure_set(False)
166
+
167
+ self.mqtt_logger.info(
168
+ "[%s] 🔒 No custom CA cert provided but using port %s. "
169
+ "Connecting with secure TLS using system trust store.",
170
+ self.client_id,
171
+ self.port
172
+ )
173
+ except Exception as e:
174
+ self.mqtt_logger.error("[%s] Failed to set TLS context: %s", self.client_id, e)
175
+ raise MqttTlsConfigurationError(f"Failed to configure secure TLS context: {e}") from e
176
+ else:
177
+ self.mqtt_logger.warning(
178
+ "[%s] ⚠️ No CA cert provided and not on port 8883. Connecting without TLS.",
179
+ self.client_id
180
+ )
181
+
182
+ # Set connect callback
183
+ def _on_connect(
184
+ self,
185
+ _client: mqtt_client.Client,
186
+ _userdata: Any,
187
+ flags: Any,
188
+ reason_code: ReasonCode,
189
+ _properties: Optional[Properties]
190
+ ) -> None:
191
+ if reason_code == 0:
192
+ self.connected = True
193
+ # Only log connection message once per connection cycle
194
+ if not self._connection_announced:
195
+ self.mqtt_logger.info("[%s] ✅ Connection fully acknowledged!", self.client_id)
196
+ self._connection_announced = True
197
+
198
+ # Check if the broker remembered our session and subscriptions!
199
+ session_present = False
200
+ if hasattr(flags, 'session_present'):
201
+ session_present = flags.session_present
202
+ elif isinstance(flags, dict):
203
+ session_present = flags.get('session_present', False)
204
+
205
+ if session_present:
206
+ self.mqtt_logger.info(
207
+ "[%s] 🧠 Session resumed! Broker remembered our subscriptions.",
208
+ self.client_id
209
+ )
210
+ else:
211
+ self.mqtt_logger.info("[%s] 🆕 Clean session. Re-subscribing...", self.client_id)
212
+ for topic, qos in self._stored_subscriptions:
213
+ self.client.subscribe(topic, qos=qos)
214
+ else:
215
+ self.mqtt_logger.error(
216
+ "[%s] ❌ Connection failed with reason code %s",
217
+ self.client_id,
218
+ reason_code
219
+ )
220
+
221
+ # Set publish callback
222
+ def _on_publish(
223
+ self,
224
+ _client: mqtt_client.Client,
225
+ _userdata: Any,
226
+ mid: int,
227
+ reason_code: ReasonCode,
228
+ _properties: Optional[Properties]
229
+ ) -> None:
230
+ with self._mid_to_topic_lock:
231
+ topic, qos = self._mid_to_topic.pop(mid, ("unknown", None))
232
+
233
+ if reason_code.is_failure:
234
+ self.mqtt_logger.error(
235
+ "[%s] ❌ Publish REJECTED by broker! Message ID: %d, reason: %s (topic: %s)",
236
+ self.client_id,
237
+ mid,
238
+ reason_code,
239
+ topic
240
+ )
241
+ else:
242
+ if qos == 0:
243
+ self.mqtt_logger.debug(
244
+ "[%s] Message ID %d no handshake for QoS 0! (topic: %s)",
245
+ self.client_id,
246
+ mid,
247
+ topic
248
+ )
249
+ elif qos == 1:
250
+ self.mqtt_logger.debug(
251
+ "[%s] Message ID %d has completed the QoS 1 handshake! (topic: %s)",
252
+ self.client_id,
253
+ mid,
254
+ topic
255
+ )
256
+ else:
257
+ self.mqtt_logger.debug(
258
+ "[%s] Message ID %d has completed the QoS 2 handshake! (topic: %s)",
259
+ self.client_id,
260
+ mid,
261
+ topic
262
+ )
263
+ self.mqtt_logger.info("[%s] ✅ Published! (topic: %s)", self.client_id, topic)
264
+
265
+ # Set message callback
266
+ def _on_message(self, _client: mqtt_client.Client, _userdata: Any, msg: mqtt_client.MQTTMessage) -> None:
267
+ payload_str = msg.payload.decode("utf-8", errors="replace")
268
+ self.mqtt_logger.debug("[%s] 📩 Received: %s -> %s", self.client_id, msg.topic, payload_str)
269
+ try:
270
+ payload = json.loads(payload_str)
271
+ except json.JSONDecodeError as e:
272
+ self.mqtt_logger.error("[%s] ⚠️ Failed to decode JSON payload: %s", self.client_id, e)
273
+ return # Skip messages that aren't valid JSON
274
+ if self.on_message:
275
+ self.on_message(msg.topic, payload, msg.qos)
276
+
277
+ # Set disconnect callback
278
+ def _on_disconnect(
279
+ self,
280
+ _client: mqtt_client.Client,
281
+ _userdata: Any,
282
+ _disconnect_flags: Any,
283
+ reason_code: ReasonCode,
284
+ _properties: Optional[Properties]
285
+ ) -> None:
286
+ self.connected = False
287
+ self._connection_announced = False # Reset flag for next connection
288
+ self.mqtt_logger.warning(
289
+ "[%s] ⚠️ Disconnected from broker. Reason: %s",
290
+ self.client_id,
291
+ reason_code
292
+ )
293
+ if reason_code != 0 and not self.reconnecting: # Not a clean disconnect
294
+ self.reconnecting = True
295
+ # Start reconnection in a separate thread to avoid blocking
296
+ threading.Thread(target=self._reconnect, daemon=True).start()
297
+
298
+ def _reconnect(self) -> None:
299
+ """Keep trying to reconnect every 1 second"""
300
+ while not self.connected:
301
+ self.mqtt_logger.warning("[%s] 🔄 Attempting to reconnect...", self.client_id)
302
+ time.sleep(1)
303
+ try:
304
+ self.client.reconnect()
305
+ # Wait a bit to check if connected
306
+ time.sleep(1)
307
+ if self.connected:
308
+ self.reconnecting = False
309
+ return
310
+ except Exception as e:
311
+ self.mqtt_logger.error("[%s] ❌ Reconnect failed: %s", self.client_id, e)
312
+ self.reconnecting = False
313
+
314
+ def start(self) -> None:
315
+ """Initiate async connection to the MQTT broker and start the network loop.
316
+
317
+ Constructs connection properties, sets session lifetimes, and waits for connection success.
318
+ """
319
+ self.mqtt_logger.info("[%s] Connecting to MQTT Broker...", self.client_id)
320
+
321
+ # 1. Create properties and set the Session Expiry Interval
322
+ connect_properties = Properties(PacketTypes.CONNECT)
323
+ connect_properties.SessionExpiryInterval = self.session_expiry_interval
324
+
325
+ # 2. Connect with clean_start to force a persistent session
326
+ try:
327
+ self.client.connect_async(
328
+ self.broker,
329
+ self.port,
330
+ keepalive=60,
331
+ clean_start=self.clean_start,
332
+ properties=connect_properties
333
+ )
334
+ except Exception as e:
335
+ self.mqtt_logger.error("[%s] Connection async failed: %s", self.client_id, e)
336
+ raise MqttConnectionError(f"Failed to initiate connection: {e}") from e
337
+
338
+ self.mqtt_logger.info("[%s] Connection initiated...", self.client_id)
339
+ # Start the network loop
340
+ self.client.loop_start()
341
+ self.mqtt_logger.info("[%s] Waiting for connection...", self.client_id)
342
+
343
+ # Wait up to 10 seconds for connection to succeed to avoid infinite hang
344
+ start_time = time.time()
345
+ while not self.connected:
346
+ if time.time() - start_time > 10.0:
347
+ self.mqtt_logger.error("[%s] Connection timed out after 10s", self.client_id)
348
+ raise MqttConnectionError("MQTT connection timed out after 10 seconds.")
349
+ time.sleep(0.1)
350
+
351
+ self.mqtt_logger.info(
352
+ "[%s] ✅ Connected and ready to publish/subscribe messages...",
353
+ self.client_id
354
+ )
355
+
356
+ def publish(self, topic: str, message: Any, qos: int = 2) -> Optional[mqtt_client.MQTTMessageInfo]:
357
+ """Publish a message to a specific MQTT topic.
358
+
359
+ Args:
360
+ topic (str): Target MQTT topic.
361
+ message (Any): Payload message to serialize. Can be a dict, Pydantic model, or raw JSON string.
362
+ qos (int): Quality of Service level (default: 2).
363
+
364
+ Returns:
365
+ paho.mqtt.client.MQTTMessageInfo: Message info container with
366
+ message ID and publish status.
367
+ """
368
+ self.mqtt_logger.info(
369
+ "[%s] 📤 Handing message to internal queue: %s [QoS %d]...",
370
+ self.client_id,
371
+ topic,
372
+ qos
373
+ )
374
+
375
+ try:
376
+ message_json = json.dumps(message, ensure_ascii=False)
377
+ except TypeError as e:
378
+ self.mqtt_logger.error("[%s] ⚠️ Failed to encode message as JSON: %s", self.client_id, e)
379
+ raise MqttSerializationError(f"Object of type {type(message).__name__} is not JSON serializable") from e
380
+
381
+ try:
382
+ msg_info = self.client.publish(topic, message_json, qos=qos)
383
+ except Exception as e:
384
+ self.mqtt_logger.error("[%s] ❌ Failed to publish message: %s", self.client_id, e)
385
+ raise MqttPublishError(f"Publish failed: {e}") from e
386
+
387
+ with self._mid_to_topic_lock:
388
+ self._mid_to_topic[msg_info.mid] = (topic, qos)
389
+
390
+ if not self.connected:
391
+ self.mqtt_logger.warning(
392
+ "[%s] ⚠️ Not connected! Message will be queued locally...",
393
+ self.client_id
394
+ )
395
+
396
+ return msg_info
397
+
398
+ def subscribe(self, topic: str, qos: int = 2) -> None:
399
+ """Subscribe to a specific MQTT topic.
400
+
401
+ Args:
402
+ topic (str): Topic pattern to subscribe to.
403
+ qos (int): QoS level (default: 2).
404
+ """
405
+ # Store subscription to restore it after a disconnect
406
+ if (topic, qos) not in self._stored_subscriptions:
407
+ self._stored_subscriptions.append((topic, qos))
408
+ self.mqtt_logger.info("[%s] 👂 Subscribing to %s...", self.client_id, topic)
409
+ try:
410
+ self.client.subscribe(topic, qos=qos)
411
+ except Exception as e:
412
+ self.mqtt_logger.error("[%s] Failed to subscribe to %s: %s", self.client_id, topic, e)
413
+ raise MqttSdkException(f"Failed to subscribe to {topic}: {e}") from e
414
+
415
+ def stop(self) -> None:
416
+ """Gracefully disconnect from the MQTT broker and stop the background network loop.
417
+
418
+ Disconnects, waits for processing, and terminates the event loop.
419
+ """
420
+ try:
421
+ self.mqtt_logger.info("[%s] 🛑 Stopping client gracefully...", self.client_id)
422
+
423
+ # NOTE: For persistent sessions to work, we must NOT unsubscribe here.
424
+ # Unsubscribing tells the broker to discard all subscriptions and queued messages.
425
+ # By just sending DISCONNECT, the broker holds the session and queues messages.
426
+
427
+ # Send DISCONNECT packet while loop is still running
428
+ self.mqtt_logger.info("[%s] 📤 Sending DISCONNECT...", self.client_id)
429
+ self.client.disconnect()
430
+ time.sleep(0.5)
431
+
432
+ # Stop the network loop
433
+ self.mqtt_logger.info("[%s] 🔌 Stopping network loop...", self.client_id)
434
+ self.client.loop_stop()
435
+ self.mqtt_logger.info("[%s] ✅ Client stopped gracefully!", self.client_id)
436
+ except Exception as e:
437
+ self.mqtt_logger.error("[%s] ❌ Error during stop: %s", self.client_id, e)
438
+ raise MqttSdkException(f"Error during client shutdown: {e}") from e
@@ -0,0 +1,25 @@
1
+ """Custom exceptions for the MQTT SDK."""
2
+
3
+ class MqttSdkException(Exception):
4
+ """Base exception class for all errors raised by the MQTT SDK."""
5
+ pass
6
+
7
+
8
+ class MqttConnectionError(MqttSdkException):
9
+ """Raised when connection to the MQTT broker fails or is refused."""
10
+ pass
11
+
12
+
13
+ class MqttPublishError(MqttSdkException):
14
+ """Raised when publishing a message fails."""
15
+ pass
16
+
17
+
18
+ class MqttTlsConfigurationError(MqttSdkException):
19
+ """Raised when SSL/TLS configuration fails."""
20
+ pass
21
+
22
+
23
+ class MqttSerializationError(MqttSdkException):
24
+ """Raised when a message payload cannot be serialized to JSON."""
25
+ pass
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561. This package supports type hints.