From e083fd2fb478bafd60530460d65a28974b9c125d Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 15 Dec 2024 11:38:12 +0100 Subject: [PATCH 01/76] Fixed stray newline in URL --- sbapp/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index a8034c6..f5745bd 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3753,11 +3753,11 @@ class SidebandApp(MDApp): else: ipstr = "" for ip in ips: - ipstr += "https://"+str(ip)+":4444/\n" + ipstr += "https://"+str(ip)+":4444/" self.reposository_url = ipstr ms = "" if len(ips) == 1 else "es" - info += "The repository server is running at the following address"+ms+":\n [u][ref=link]"+ipstr+"[/ref][u]" + info += "The repository server is running at the following address"+ms+":\n [u][ref=link]"+ipstr+"[/ref][u]\n" self.repository_screen.ids.repository_info.bind(on_ref_press=self.repository_link_action) def cb(dt): From 78f2b5de3ba282b72149085cae015c293886d83d Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 15 Dec 2024 12:03:48 +0100 Subject: [PATCH 02/76] Updated readme --- README.md | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 77d4cae..76bf49a 100644 --- a/README.md +++ b/README.md @@ -195,24 +195,36 @@ To install Sideband via `pip`, follow these instructions: ```bash # Install Sideband and dependencies on macOS using pip: -pip3 install sbapp --user --break-system-packages +pip3 install sbapp # Optionally install RNS command line utilities: pip3 install rns # Run Sideband from the terminal: +################################# +sideband +# or python3 -m sbapp.main # Enable debug logging: +################################# +sideband -v +# or python3 -m sbapp.main -v # Start Sideband in daemon mode: +################################# +sideband -d +# or python3 -m sbapp.main -d -# If you add your pip install location to -# the PATH environment variable, you can -# also run Sideband simply using: -sideband +# If Python and pip was installed correctly, +# you can simply use the "sideband" command +# directly. Otherwise, you will manually +# need to add the pip binaries directory to +# your PATH environment variable, or start +# Sideband via the "python3 -m sbapp.main" +# syntax. ``` From 9e6cdc859a9dc17fe14618f798b6bfbd22897766 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 15 Dec 2024 12:06:06 +0100 Subject: [PATCH 03/76] Updated readme --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 76bf49a..cf0a057 100644 --- a/README.md +++ b/README.md @@ -197,9 +197,6 @@ To install Sideband via `pip`, follow these instructions: # Install Sideband and dependencies on macOS using pip: pip3 install sbapp -# Optionally install RNS command line utilities: -pip3 install rns - # Run Sideband from the terminal: ################################# sideband From c1f04e8e3e073da5d20dc756c3053f02679c6dc0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 17 Dec 2024 13:25:55 +0100 Subject: [PATCH 04/76] Fixed cert generation on Android. Fixes #65. --- sbapp/buildozer.spec | 2 +- sbapp/sideband/certgen.py | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 09f9530..04ab47f 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,7 +10,7 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20241213 +android.numeric_version = 20241217 requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions diff --git a/sbapp/sideband/certgen.py b/sbapp/sideband/certgen.py index 70e4802..631a8b4 100644 --- a/sbapp/sideband/certgen.py +++ b/sbapp/sideband/certgen.py @@ -47,7 +47,11 @@ def get_key(key_path, force_reload=False): return LOADED_KEY elif os.path.isfile(KEY_PATH): with open(KEY_PATH, "rb") as f: - key = load_pem_private_key(f.read(), KEY_PASSPHRASE) + if cryptography_major_version > 3: + key = load_pem_private_key(f.read(), KEY_PASSPHRASE) + else: + from cryptography.hazmat.backends import default_backend + key = load_pem_private_key(f.read(), KEY_PASSPHRASE, backend=default_backend()) else: if cryptography_major_version > 3: key = ec.generate_private_key(curve=ec.SECP256R1()) @@ -87,6 +91,7 @@ def gen_cert(cert_path, key): cb = cb.not_valid_before(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(days=-14)) cb = cb.not_valid_after(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(days=3652)) cb = cb.add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False) + if cryptography_major_version > 3: cert = cb.sign(key, hashes.SHA256()) else: From ab5798d8de28c8da60f518d634d265890a908212 Mon Sep 17 00:00:00 2001 From: malteish Date: Sat, 28 Dec 2024 19:58:49 +0100 Subject: [PATCH 05/76] fix formatting of rnode server urls --- sbapp/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index f5745bd..505aad9 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3753,11 +3753,11 @@ class SidebandApp(MDApp): else: ipstr = "" for ip in ips: - ipstr += "https://"+str(ip)+":4444/" - self.reposository_url = ipstr + ipstr += "[u][ref=link]https://" + str(ip) + ":4444/[/ref][u]\n" + self.repository_url = ipstr ms = "" if len(ips) == 1 else "es" - info += "The repository server is running at the following address"+ms+":\n [u][ref=link]"+ipstr+"[/ref][u]\n" + info += "The repository server is running at the following address" + ms +":\n"+ipstr self.repository_screen.ids.repository_info.bind(on_ref_press=self.repository_link_action) def cb(dt): From 2ce03c1508b7f772e647e856d5ffed9e077656ce Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 2 Jan 2025 10:55:13 +0100 Subject: [PATCH 06/76] Fixed advanced RNS config acting unexpectedly --- sbapp/sideband/core.py | 3 ++- sbapp/ui/utilities.py | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 90da196..b337de8 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -181,6 +181,7 @@ class SidebandCore(): self.allow_service_dispatch = True self.version_str = "" self.config_template = rns_config + self.default_config_template = rns_config if config_path == None: self.app_dir = plyer.storagepath.get_home_dir()+"/.config/sideband" @@ -5012,6 +5013,6 @@ rns_config = """# This template is used to generate a # No additional interfaces are currently # defined, but you can use this section -# to do so. +# to add additional custom interfaces. [interfaces] """ diff --git a/sbapp/ui/utilities.py b/sbapp/ui/utilities.py index a35b6bd..43f0f59 100644 --- a/sbapp/ui/utilities.py +++ b/sbapp/ui/utilities.py @@ -135,13 +135,24 @@ class Utilities(): def update_advanced(self, sender=None): if RNS.vendor.platformutils.is_android(): ct = self.app.sideband.config["config_template"] + if ct == None: + ct = self.app.sideband.default_config_template self.advanced_screen.ids.config_template.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]{ct}[/size][/font]" else: self.advanced_screen.ids.config_template.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]On this platform, Reticulum configuration is managed by the system. You can change the configuration by editing the file located at:\n\n{self.app.sideband.reticulum.configpath}[/size][/font]" + def reset_config(self, sender=None): + if RNS.vendor.platformutils.is_android(): + self.app.sideband.config["config_template"] = None + self.app.sideband.save_configuration() + self.update_advanced() + def copy_config(self, sender=None): if RNS.vendor.platformutils.is_android(): - Clipboard.copy(self.app.sideband.config_template) + if self.app.sideband.config["config_template"]: + Clipboard.copy(self.app.sideband.config["config_template"]) + else: + Clipboard.copy(self.app.sideband.default_config_template) def paste_config(self, sender=None): if RNS.vendor.platformutils.is_android(): @@ -409,7 +420,7 @@ MDScreen: padding: [dp(0), dp(14), dp(0), dp(24)] MDRectangleFlatIconButton: - id: telemetry_button + id: conf_copy_button icon: "content-copy" text: "Copy Configuration" padding: [dp(0), dp(14), dp(0), dp(14)] @@ -420,7 +431,7 @@ MDScreen: disabled: False MDRectangleFlatIconButton: - id: coordinates_button + id: conf_paste_button icon: "download" text: "Paste Configuration" padding: [dp(0), dp(14), dp(0), dp(14)] @@ -430,6 +441,23 @@ MDScreen: on_release: root.delegate.paste_config(self) disabled: False + MDBoxLayout: + orientation: "horizontal" + spacing: dp(24) + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(24)] + + MDRectangleFlatIconButton: + id: conf_reset_button + icon: "cog-counterclockwise" + text: "Reset Configuration" + padding: [dp(0), dp(14), dp(0), dp(14)] + icon_size: dp(24) + font_size: dp(16) + size_hint: [1.0, None] + on_release: root.delegate.reset_config(self) + disabled: False MDLabel: id: config_template From 0c062ee16b1d5453774b5fcb8e0c726737b2061e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 2 Jan 2025 11:17:21 +0100 Subject: [PATCH 07/76] Fix repository link handling typo --- sbapp/main.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 505aad9..dbe0880 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -385,7 +385,8 @@ class SidebandApp(MDApp): self.connectivity_updater = None self.last_map_update = 0 self.last_telemetry_received = 0 - self.reposository_url = None + self.repository_url = None + self.rnode_flasher_url = None ################################################# @@ -3705,9 +3706,9 @@ class SidebandApp(MDApp): self.root.ids.screen_manager.transition = self.slide_transition def repository_link_action(self, sender=None, event=None): - if self.reposository_url != None: + if self.repository_url != None: def lj(): - webbrowser.open(self.reposository_url) + webbrowser.open(self.repository_url) threading.Thread(target=lj, daemon=True).start() def repository_update_info(self, sender=None): @@ -3749,15 +3750,19 @@ class SidebandApp(MDApp): ips = getIP() if ips == None or len(ips) == 0: info += "The repository server is running, but the local device IP address could not be determined.\n\nYou can access the repository by pointing a browser to: https://DEVICE_IP:4444/" - self.reposository_url = None + self.repository_url = None else: ipstr = "" + self.repository_url = None for ip in ips: - ipstr += "[u][ref=link]https://" + str(ip) + ":4444/[/ref][u]\n" - self.repository_url = ipstr + ipurl = "https://" + str(ip) + ":4444/" + ipstr += "[u][ref=link]"+ipurl+"[/ref][u]\n" + if self.repository_url == None: + self.repository_url = ipurl + self.rnode_flasher_url = ipurl+"mirrors/rnode-flasher/index.html" ms = "" if len(ips) == 1 else "es" - info += "The repository server is running at the following address" + ms +":\n"+ipstr + info += "The repository server is running at the following address" + ms +":\n\n"+ipstr self.repository_screen.ids.repository_info.bind(on_ref_press=self.repository_link_action) def cb(dt): @@ -3777,7 +3782,7 @@ class SidebandApp(MDApp): Clock.schedule_once(self.repository_update_info, 1.0) def repository_stop_action(self, sender=None): - self.reposository_url = None + self.repository_url = None self.sideband.stop_webshare() Clock.schedule_once(self.repository_update_info, 0.75) From b80a42947bc5b983be661e5ab38a6e323e4fcce0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 2 Jan 2025 11:24:46 +0100 Subject: [PATCH 08/76] Changed formatting --- docs/utilities/rns_audio_call_calc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/utilities/rns_audio_call_calc.py b/docs/utilities/rns_audio_call_calc.py index 61bbfff..6bb2ccb 100644 --- a/docs/utilities/rns_audio_call_calc.py +++ b/docs/utilities/rns_audio_call_calc.py @@ -98,7 +98,7 @@ def simulate(link_speed=9600, audio_slot_ms=70, codec_rate=1200, method="msgpack print(f" Encrypted payload : {ENCRYPTED_PAYLOAD_LEN} bytes") print(f" Transport overhead : {TRANSPORT_OVERHEAD} bytes ({RNS_OVERHEAD} from RNS, {PHY_OVERHEAD} from PHY)") print(f" On-air length : {PACKET_LEN} bytes") - print(f" Packet airtime : {PACKET_AIRTIME}ms") + print(f" Packet airtime : {round(PACKET_AIRTIME,2)}ms") print( "\n===== Results for "+RNS.prettyspeed(LINK_SPEED)+" Link Speed ===\n") print(f" Final latency : {TOTAL_LATENCY}ms") From 19e3364b7ff2bf064d5e2ad95b1db0d5ddc0dbf7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 2 Jan 2025 11:25:34 +0100 Subject: [PATCH 09/76] Launch RNode flasher directly from utilities --- sbapp/main.py | 9 ++++++++- sbapp/ui/utilities.py | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index dbe0880..dc02b92 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3768,13 +3768,20 @@ class SidebandApp(MDApp): def cb(dt): self.repository_screen.ids.repository_enable_button.disabled = True self.repository_screen.ids.repository_disable_button.disabled = False + if hasattr(self, "wants_flasher_launch") and self.wants_flasher_launch == True: + self.wants_flasher_launch = False + if self.rnode_flasher_url != None: + def lj(): + webbrowser.open(self.rnode_flasher_url) + threading.Thread(target=lj, daemon=True).start() + Clock.schedule_once(cb, 0.1) else: self.repository_screen.ids.repository_enable_button.disabled = False self.repository_screen.ids.repository_disable_button.disabled = True - info += "\n" + info += "" self.repository_screen.ids.repository_info.text = info def repository_start_action(self, sender=None): diff --git a/sbapp/ui/utilities.py b/sbapp/ui/utilities.py index 43f0f59..bf46914 100644 --- a/sbapp/ui/utilities.py +++ b/sbapp/ui/utilities.py @@ -64,6 +64,7 @@ class Utilities(): ) def dl_yes(s): dialog.dismiss() + self.app.wants_flasher_launch = True self.app.sideband.start_webshare() def cb(dt): self.app.repository_action() From 9f48fae6e85a848e3d9d27e6b18c057814b1fbf8 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 2 Jan 2025 11:37:14 +0100 Subject: [PATCH 10/76] Updated version --- sbapp/buildozer.spec | 2 +- sbapp/main.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 04ab47f..688446b 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,7 +10,7 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20241217 +android.numeric_version = 20250102 requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions diff --git a/sbapp/main.py b/sbapp/main.py index dc02b92..1d20e33 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.2.0" +__version__ = "1.2.1" __variant__ = "" import sys From e515889e210037f881c201e0d627a7b09a48eb69 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 3 Jan 2025 22:35:27 +0100 Subject: [PATCH 11/76] Add support for SX1280 bandwidth options --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 1d20e33..e4fdc93 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4238,7 +4238,7 @@ class SidebandApp(MDApp): valid = False try: - valid_vals = [7.8, 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125, 250, 500] + valid_vals = [7.8, 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125, 250, 500, 203.125, 406.25, 812.5, 1625] val = float(self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text) if not val in valid_vals: raise ValueError("Invalid bandwidth") From 5b61885beabf257a1f7fd716789c05576787bd66 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 6 Jan 2025 20:46:34 +0100 Subject: [PATCH 12/76] Updated issue template --- .github/ISSUE_TEMPLATE/πŸ›-bug-report.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md b/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md index 77ad6c2..ddb78fc 100644 --- a/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md +++ b/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md @@ -15,7 +15,11 @@ Before creating a bug report on this issue tracker, you **must** read the [Contr - After reading the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md), delete this section from your bug report. **Describe the Bug** -A clear and concise description of what the bug is. +First of all: Is this really a bug? Is it reproducible? + +If this is a request for help because something is not working as you expected, stop right here, and go to the [discussions](https://github.com/markqvist/Reticulum/discussions) instead, where you can post your questions and get help from other users. + +If this really is a bug or issue with the software, remove this section of the template, and provide **a clear and concise description of what the bug is**. **To Reproduce** Describe in detail how to reproduce the bug. @@ -24,7 +28,7 @@ Describe in detail how to reproduce the bug. A clear and concise description of what you expected to happen. **Logs & Screenshots** -Please include any relevant log output. If applicable, also add screenshots to help explain your problem. +Please include any relevant log output. If applicable, also add screenshots to help explain your problem. In most cases, without any relevant log output, we will not be able to determine the cause of the bug, or reproduce it. **System Information** - OS and version From ad32349e2c43629c6c4aa7c22c2032b8255624ff Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Jan 2025 16:05:31 +0100 Subject: [PATCH 13/76] Fix propagation node detector in daemon mode --- sbapp/sideband/core.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index b337de8..f6d922f 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -64,9 +64,14 @@ class PropagationNodeDetector(): # age = 0 pass - link_stats = {"rssi": self.owner_app.sideband.reticulum.get_packet_rssi(announce_packet_hash), - "snr": self.owner_app.sideband.reticulum.get_packet_snr(announce_packet_hash), - "q": self.owner_app.sideband.reticulum.get_packet_q(announce_packet_hash)} + if self.owner_app != None: + stat_endpoint = self.owner_app.sideband + else: + stat_endpoint = self.owner + + link_stats = {"rssi": stat_endpoint.reticulum.get_packet_rssi(announce_packet_hash), + "snr": stat_endpoint.reticulum.get_packet_snr(announce_packet_hash), + "q": stat_endpoint.reticulum.get_packet_q(announce_packet_hash)} RNS.log("Detected active propagation node "+RNS.prettyhexrep(destination_hash)+" emission "+str(age)+" seconds ago, "+str(hops)+" hops away") self.owner.log_announce(destination_hash, app_data, dest_type=PropagationNodeDetector.aspect_filter, link_stats=link_stats) @@ -4684,7 +4689,7 @@ class SidebandCore(): thread.start() self.setstate("core.started", True) - RNS.log("Sideband Core "+str(self)+" "+str(self.version_str)+" started") + RNS.log("Sideband Core "+str(self)+" "+str(self.version_str)+"started") def stop_webshare(self): if self.webshare_server != None: From b9e224579b9bcd0c576b82de924ad63dc87dde43 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 14 Jan 2025 22:05:28 +0100 Subject: [PATCH 14/76] Updated versions --- sbapp/buildozer.spec | 2 +- sbapp/main.py | 2 +- setup.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 688446b..3c64903 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,7 +10,7 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20250102 +android.numeric_version = 20250115 requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions diff --git a/sbapp/main.py b/sbapp/main.py index e4fdc93..19a7f36 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.2.1" +__version__ = "1.3.0" __variant__ = "" import sys diff --git a/setup.py b/setup.py index 0cf38f8..4f2ff5c 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.8.8", - "lxmf>=0.5.8", + "rns>=0.9.0", + "lxmf>=0.5.9", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 60591d3f0d722b8168d53909d968de6cff55dd8b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 15 Jan 2025 09:43:52 +0100 Subject: [PATCH 15/76] Fixed typo --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 19a7f36..bbf0e8c 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4887,7 +4887,7 @@ class SidebandApp(MDApp): self.bind_clipboard_actions(self.keys_screen.ids) self.keys_screen.ids.keys_scrollview.effect_cls = ScrollEffect - info = "Your primary encryption keys are stored in a Reticulum Identity within the Sideband app. If you want to backup this Identity for later use on this or another device, you can export it as a plain text blob, with the key data encoded in Base32 format. This will allow you to restore your address in Sideband or other LXMF clients at a later point.\n\n[b]Warning![/b] Anyone that gets access to the key data will be able to control your LXMF address, impersonate you, and read your messages. In is [b]extremely important[/b] that you keep the Identity data secure if you export it.\n\nBefore displaying or exporting your Identity data, make sure that no machine or person in your vicinity is able to see, copy or record your device screen or similar." + info = "Your primary encryption keys are stored in a Reticulum Identity within the Sideband app. If you want to backup this Identity for later use on this or another device, you can export it as a plain text blob, with the key data encoded in Base32 format. This will allow you to restore your address in Sideband or other LXMF clients at a later point.\n\n[b]Warning![/b] Anyone that gets access to the key data will be able to control your LXMF address, impersonate you, and read your messages. It is [b]extremely important[/b] that you keep the Identity data secure if you export it.\n\nBefore displaying or exporting your Identity data, make sure that no machine or person in your vicinity is able to see, copy or record your device screen or similar." if not RNS.vendor.platformutils.get_platform() == "android": self.widget_hide(self.keys_screen.ids.keys_share) From 4dfd42391528aa203e0263ebd78007f7cfa3b56c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 19:12:08 +0100 Subject: [PATCH 16/76] Added ability to cancel outbound messages --- sbapp/sideband/core.py | 39 ++++++++++++++++++++++++++++++++++ sbapp/ui/helpers.py | 3 +++ sbapp/ui/messages.py | 48 ++++++++++++++++++++++++++++++++++++------ 3 files changed, 84 insertions(+), 6 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index f6d922f..2ae73d1 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1868,6 +1868,10 @@ class SidebandCore(): image=args["image"], audio=args["audio"]) connection.send(send_result) + elif "cancel_message" in call: + args = call["cancel_message"] + cancel_result = self.cancel_message(args["message_id"]) + connection.send(cancel_result) elif "send_command" in call: args = call["send_command"] send_result = self.send_command( @@ -4273,6 +4277,21 @@ class SidebandCore(): RNS.log("An error occurred while getting message transfer stamp cost: "+str(e), RNS.LOG_ERROR) return None + def _service_cancel_message(self, message_id): + if not RNS.vendor.platformutils.is_android(): + return False + else: + if self.is_client: + try: + return self.service_rpc_request({"cancel_message": {"message_id": message_id }}) + + except Exception as e: + RNS.log("Error while cancelling message over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + else: + return False + def _service_send_message(self, content, destination_hash, propagation, skip_fields=False, no_display=False, attachment = None, image = None, audio = None): if not RNS.vendor.platformutils.is_android(): return False @@ -4316,6 +4335,26 @@ class SidebandCore(): else: return False + def cancel_message(self, message_id): + if self.allow_service_dispatch and self.is_client: + try: + return self._service_cancel_message(message_id) + + except Exception as e: + RNS.log("Error while cancelling message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + + else: + try: + self.message_router.cancel_outbound(message_id) + return True + + except Exception as e: + RNS.log("Error while cancelling message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + def send_message(self, content, destination_hash, propagation, skip_fields=False, no_display=False, attachment = None, image = None, audio = None): if self.allow_service_dispatch and self.is_client: try: diff --git a/sbapp/ui/helpers.py b/sbapp/ui/helpers.py index 80d2971..c3b454c 100644 --- a/sbapp/ui/helpers.py +++ b/sbapp/ui/helpers.py @@ -20,11 +20,13 @@ color_delivered = "Blue" color_paper = "Indigo" color_propagated = "Indigo" color_failed = "Red" +color_cancelled = "Red" color_unknown = "Gray" intensity_msgs_dark = "800" intensity_msgs_light = "500" intensity_play_dark = "600" intensity_play_light = "300" +intensity_cancelled = "900" intensity_msgs_dark_alt = "800" @@ -38,6 +40,7 @@ color_paper_alt = "DeepPurple" color_playing_alt = "Amber" color_failed_alt = "Red" color_unknown_alt = "Gray" +color_cancelled_alt = "Red" class ContentNavigationDrawer(Screen): pass diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 08093cf..5486f5c 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -34,14 +34,14 @@ if RNS.vendor.platformutils.get_platform() == "android": import plyer from sideband.sense import Telemeter, Commands from ui.helpers import ts_format, file_ts_format, mdc - from ui.helpers import color_playing, color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light, intensity_play_dark, intensity_play_light - from ui.helpers import color_received_alt, color_received_alt_light, color_delivered_alt, color_propagated_alt, color_paper_alt, color_failed_alt, color_unknown_alt, color_playing_alt, intensity_msgs_dark_alt, intensity_msgs_light_alt, intensity_delivered_alt_dark + from ui.helpers import color_playing, color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light, intensity_play_dark, intensity_play_light, color_cancelled, intensity_cancelled + from ui.helpers import color_received_alt, color_received_alt_light, color_delivered_alt, color_propagated_alt, color_paper_alt, color_failed_alt, color_unknown_alt, color_playing_alt, intensity_msgs_dark_alt, intensity_msgs_light_alt, intensity_delivered_alt_dark, color_cancelled_alt else: import sbapp.plyer as plyer from sbapp.sideband.sense import Telemeter, Commands from .helpers import ts_format, file_ts_format, mdc - from .helpers import color_playing, color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light, intensity_play_dark, intensity_play_light - from .helpers import color_received_alt, color_received_alt_light, color_delivered_alt, color_propagated_alt, color_paper_alt, color_failed_alt, color_unknown_alt, color_playing_alt, intensity_msgs_dark_alt, intensity_msgs_light_alt, intensity_delivered_alt_dark + from .helpers import color_playing, color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light, intensity_play_dark, intensity_play_light, color_cancelled, intensity_cancelled + from .helpers import color_received_alt, color_received_alt_light, color_delivered_alt, color_propagated_alt, color_paper_alt, color_failed_alt, color_unknown_alt, color_playing_alt, intensity_msgs_dark_alt, intensity_msgs_light_alt, intensity_delivered_alt_dark, color_cancelled_alt if RNS.vendor.platformutils.is_darwin(): from PIL import Image as PilImage @@ -213,6 +213,7 @@ class Messages(): c_paper = color_paper_alt c_unknown = color_unknown_alt c_failed = color_failed_alt + c_cancelled = color_cancelled_alt else: c_delivered = color_delivered c_received = color_received @@ -221,6 +222,7 @@ class Messages(): c_paper = color_paper c_unknown = color_unknown c_failed = color_failed + c_cancelled = color_cancelled for new_message in self.app.sideband.list_messages(self.context_dest, after=self.latest_message_timestamp,limit=limit): self.new_messages.append(new_message) @@ -369,7 +371,7 @@ class Messages(): m["state"] = msg["state"] if msg["state"] == LXMF.LXMessage.FAILED: - w.md_bg_color = msg_color = mdc(c_failed, intensity_msgs) + w.md_bg_color = msg_color = mdc(c_failed, intensity_cancelled) txstr = time.strftime(ts_format, time.localtime(msg["sent"])) titlestr = "" if msg["title"]: @@ -381,6 +383,19 @@ class Messages(): w.heading += f"\n[b]Audio Message[/b] ({alstr})" w.dmenu.items.append(w.dmenu.retry_item) + if msg["state"] == LXMF.LXMessage.CANCELLED: + w.md_bg_color = msg_color = mdc(c_cancelled, intensity_cancelled) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Cancelled" + m["state"] = msg["state"] + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + w.dmenu.items.append(w.dmenu.retry_item) + def hide_widget(self, wid, dohide=True): if hasattr(wid, 'saved_attrs'): @@ -427,6 +442,7 @@ class Messages(): c_paper = color_paper_alt c_unknown = color_unknown_alt c_failed = color_failed_alt + c_cancelled = color_cancelled_alt else: c_delivered = color_delivered c_received = color_received @@ -435,6 +451,7 @@ class Messages(): c_paper = color_paper c_unknown = color_unknown c_failed = color_failed + c_cancelled = color_cancelled self.ids.message_text.font_name = self.app.input_font @@ -602,9 +619,13 @@ class Messages(): heading_str = titlestr+"[b]Created[/b] "+txstr+"\n[b]State[/b] Paper Message" elif m["state"] == LXMF.LXMessage.FAILED: - msg_color = mdc(c_failed, intensity_msgs) + msg_color = mdc(c_failed, intensity_cancelled) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Failed" + elif m["state"] == LXMF.LXMessage.CANCELLED: + msg_color = mdc(c_cancelled, intensity_cancelled) + heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Cancelled" + elif m["state"] == LXMF.LXMessage.OUTBOUND or m["state"] == LXMF.LXMessage.SENDING: msg_color = mdc(c_unknown, intensity_msgs) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Sending " @@ -798,6 +819,13 @@ class Messages(): return x + def gen_cancel(mhash, item): + def x(): + self.app.sideband.cancel_message(mhash) + item.dmenu.dismiss() + + return x + def gen_save_image(item): if RNS.vendor.platformutils.is_android(): def x(): @@ -1197,6 +1225,14 @@ class Messages(): "on_release": gen_save_attachment(item) } dm_items.append(extra_item) + if m["state"] <= LXMF.LXMessage.SENT: + extra_item = { + "viewclass": "OneLineListItem", + "text": "Cancel message", + "height": dp(40), + "on_release": gen_cancel(m["hash"], item) + } + dm_items.append(extra_item) item.dmenu = MDDropdownMenu( caller=item.ids.msg_submenu, From 3111f767f0086ab3c422367135822c6583a7d0e1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 21:34:33 +0100 Subject: [PATCH 17/76] Show indication on receiver message reject --- sbapp/ui/messages.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 5486f5c..0ec17cb 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -396,6 +396,19 @@ class Messages(): w.heading += f"\n[b]Audio Message[/b] ({alstr})" w.dmenu.items.append(w.dmenu.retry_item) + if msg["state"] == LXMF.LXMessage.REJECTED: + w.md_bg_color = msg_color = mdc(c_cancelled, intensity_cancelled) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Rejected" + m["state"] = msg["state"] + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + w.dmenu.items.append(w.dmenu.retry_item) + def hide_widget(self, wid, dohide=True): if hasattr(wid, 'saved_attrs'): @@ -626,6 +639,10 @@ class Messages(): msg_color = mdc(c_cancelled, intensity_cancelled) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Cancelled" + elif m["state"] == LXMF.LXMessage.REJECTED: + msg_color = mdc(c_cancelled, intensity_cancelled) + heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Rejected" + elif m["state"] == LXMF.LXMessage.OUTBOUND or m["state"] == LXMF.LXMessage.SENDING: msg_color = mdc(c_unknown, intensity_msgs) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Sending " From 752c080d83a3b0cba7cf3ca135894260fb43816b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 21:39:59 +0100 Subject: [PATCH 18/76] Updated versions --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 4f2ff5c..e6b2cf7 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.0", - "lxmf>=0.5.9", + "rns>=0.9.1", + "lxmf>=0.6.0", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 235bfa64593c19ca84919efa8b15933bd6105bd9 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 22:45:24 +0100 Subject: [PATCH 19/76] Auto switch message mode on attachment --- sbapp/main.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sbapp/main.py b/sbapp/main.py index bbf0e8c..b06a5b6 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1767,6 +1767,11 @@ class SidebandApp(MDApp): if self.root.ids.screen_manager.current == "messages_screen": self.object_details_action(self.messages_view, from_conv=True) + def outbound_mode_reset(self, sender=None): + self.outbound_mode_paper = False + self.outbound_mode_propagation = False + self.outbound_mode_command = False + def message_propagation_action(self, sender): if self.outbound_mode_command: self.outbound_mode_paper = False @@ -1796,6 +1801,8 @@ class SidebandApp(MDApp): tf = open(path, "rb") tf.close() self.attach_path = path + if self.outbound_mode_command: + self.outbound_mode_reset() if RNS.vendor.platformutils.is_android(): toast("Attached \""+str(fbn)+"\"") @@ -2048,6 +2055,8 @@ class SidebandApp(MDApp): self.sideband.ui_stopped_recording() if self.message_process_audio(): + if self.outbound_mode_command: + self.outbound_mode_reset() self.message_send_action() Clock.schedule_once(cb_s, 0.35) @@ -2195,6 +2204,8 @@ class SidebandApp(MDApp): else: self.message_process_audio() + if self.outbound_mode_command: + self.outbound_mode_reset() self.update_message_widgets() toast("Added recorded audio to message") From 4d7cb57d3816c2539299f7caa8960447927468ce Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 23:15:02 +0100 Subject: [PATCH 20/76] Fixed attachments not displaying while sending message --- sbapp/ui/messages.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 0ec17cb..f7f21dc 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -336,6 +336,12 @@ class Messages(): w.heading += f"\n[b]Audio Message[/b] ({alstr})" m["state"] = msg["state"] + att_heading_str = "" + if hasattr(w, "has_attachment") and w.has_attachment: + att_heading_str = "\n[b]Attachments[/b] " + for attachment in w.attachments_field: + att_heading_str += str(attachment[0])+", " + att_heading_str = att_heading_str[:-2] if msg["state"] == LXMF.LXMessage.DELIVERED: w.md_bg_color = msg_color = mdc(c_delivered, intensity_delivered) @@ -409,6 +415,8 @@ class Messages(): w.heading += f"\n[b]Audio Message[/b] ({alstr})" w.dmenu.items.append(w.dmenu.retry_item) + w.heading += att_heading_str + def hide_widget(self, wid, dohide=True): if hasattr(wid, 'saved_attrs'): @@ -656,9 +664,6 @@ class Messages(): heading_str = titlestr if phy_stats_str != "" and self.app.sideband.config["advanced_stats"]: heading_str += phy_stats_str+"\n" - # TODO: Remove - # if stamp_valid: - # txstr += f" [b]Stamp[/b] value is {stamp_value} " heading_str += "[b]Sent[/b] "+txstr+delivery_syms heading_str += "\n[b]Received[/b] "+rxstr @@ -696,6 +701,9 @@ class Messages(): if has_attachment: item.attachments_field = attachments_field + item.has_attachment = True + else: + item.has_attachment = False if has_audio: def play_audio(sender): From dd1399d7ce1bf02c4d17761092f8b8ad8416ddaf Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 23:23:16 +0100 Subject: [PATCH 21/76] Improved attachment feedback --- sbapp/main.py | 29 +++-------------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index b06a5b6..d2ca278 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -274,9 +274,7 @@ else: import sbapp.pyogg as pyogg from sbapp.pydub import AudioSegment - class toast: - def __init__(self, *kwargs): - pass + from kivymd.toast import toast from kivy.config import Config Config.set('input', 'mouse', 'mouse,disable_multitouch') @@ -1804,17 +1802,7 @@ class SidebandApp(MDApp): if self.outbound_mode_command: self.outbound_mode_reset() - if RNS.vendor.platformutils.is_android(): - toast("Attached \""+str(fbn)+"\"") - else: - ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - ate_dialog = MDDialog( - title="File Attached", - text="The file \""+str(fbn)+"\" was attached, and will be included with the next message sent.", - buttons=[ ok_button ], - ) - ok_button.bind(on_release=ate_dialog.dismiss) - ate_dialog.open() + toast("Attached \""+str(fbn)+"\"") except Exception as e: RNS.log(f"Error while attaching \"{fbn}\": "+str(e), RNS.LOG_ERROR) @@ -2332,18 +2320,7 @@ class SidebandApp(MDApp): self.attach_type = None self.update_message_widgets() - if RNS.vendor.platformutils.get_platform() == "android": - toast("Attachment removed") - else: - ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - ate_dialog = MDDialog( - title="Attachment Removed", - text="The attached resource was removed from the message", - buttons=[ ok_button ], - ) - ok_button.bind(on_release=ate_dialog.dismiss) - ate_dialog.open() - + toast("Attachment removed") def shared_attachment_action(self, attachment_data): if not self.root.ids.screen_manager.current == "messages_screen": From 56add0bc505b8471a471074b3d23da22523aef5a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Jan 2025 23:48:35 +0100 Subject: [PATCH 22/76] Strip markup from notifications --- sbapp/sideband/core.py | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 2ae73d1..53fd60d 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -7,6 +7,7 @@ import struct import sqlite3 import random import shlex +import re import RNS.vendor.umsgpack as msgpack import RNS.Interfaces.Interface as Interface @@ -127,19 +128,20 @@ class SidebandCore(): # Add the announce to the directory announce # stream logger - link_stats = {"rssi": self.reticulum.get_packet_rssi(announce_packet_hash), - "snr": self.reticulum.get_packet_snr(announce_packet_hash), - "q": self.reticulum.get_packet_q(announce_packet_hash)} + if self.reticulum != None: + link_stats = {"rssi": self.reticulum.get_packet_rssi(announce_packet_hash), + "snr": self.reticulum.get_packet_snr(announce_packet_hash), + "q": self.reticulum.get_packet_q(announce_packet_hash)} - # This reformats the new v0.5.0 announce data back to the expected format - # for Sidebands database and other handling functions. - dn = LXMF.display_name_from_app_data(app_data) - sc = LXMF.stamp_cost_from_app_data(app_data) - app_data = b"" - if dn != None: - app_data = dn.encode("utf-8") + # This reformats the new v0.5.0 announce data back to the expected format + # for Sidebands database and other handling functions. + dn = LXMF.display_name_from_app_data(app_data) + sc = LXMF.stamp_cost_from_app_data(app_data) + app_data = b"" + if dn != None: + app_data = dn.encode("utf-8") - self.log_announce(destination_hash, app_data, dest_type=SidebandCore.aspect_filter, stamp_cost=sc, link_stats=link_stats) + self.log_announce(destination_hash, app_data, dest_type=SidebandCore.aspect_filter, stamp_cost=sc, link_stats=link_stats) def __init__(self, owner_app, config_path = None, is_service=False, is_client=False, android_app_dir=None, verbose=False, owner_service=None, service_context=None, is_daemon=False, load_config_only=False): self.is_service = is_service @@ -4532,6 +4534,11 @@ class SidebandCore(): self.setstate("lxm_uri_ingest.result", response) + def strip_markup(self, text): + if not hasattr(self, "smr") or self.smr == None: + self.smr = re.compile(r'\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]',re.IGNORECASE | re.MULTILINE ) + return self.smr.sub("", text) + def lxm_ingest(self, message, originator = False): should_notify = False is_trusted = False @@ -4614,7 +4621,7 @@ class SidebandCore(): if should_notify: nlen = 128 text = message.content.decode("utf-8") - notification_content = text[:nlen] + notification_content = self.strip_markup(text[:nlen]) if len(text) > nlen: notification_content += " [...]" From ebaf66788bec2bd8dc0ef6cbe2bfe4ebdccb5854 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 19 Jan 2025 10:05:29 +0100 Subject: [PATCH 23/76] Cancel message menu item --- sbapp/ui/messages.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index f7f21dc..b884b76 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -303,6 +303,17 @@ class Messages(): delivery_syms += " πŸ“¦" delivery_syms = multilingual_markup(delivery_syms.encode("utf-8")).decode("utf-8") + if msg["state"] > LXMF.LXMessage.SENT: + if hasattr(w, "dmenu"): + if hasattr(w.dmenu, "items"): + remove_item = None + for item in w.dmenu.items: + if item["text"] == "Cancel message": + remove_item = item + break + if remove_item != None: + w.dmenu.items.remove(remove_item) + if msg["state"] == LXMF.LXMessage.OUTBOUND or msg["state"] == LXMF.LXMessage.SENDING or msg["state"] == LXMF.LXMessage.SENT: w.md_bg_color = msg_color = mdc(c_unknown, intensity_msgs) txstr = time.strftime(ts_format, time.localtime(msg["sent"])) @@ -1250,7 +1261,7 @@ class Messages(): "on_release": gen_save_attachment(item) } dm_items.append(extra_item) - if m["state"] <= LXMF.LXMessage.SENT: + if m["source"] == self.app.sideband.lxmf_destination.hash and m["state"] <= LXMF.LXMessage.SENT: extra_item = { "viewclass": "OneLineListItem", "text": "Cancel message", From d6f54a0df3639b41217d746dd3cfcedf297a71fc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 19 Jan 2025 22:09:41 +0100 Subject: [PATCH 24/76] Update peer telemetry from map by right-clicking --- sbapp/main.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index d2ca278..803fef7 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -5778,8 +5778,23 @@ class SidebandApp(MDApp): self.map_action() self.map_show(location) - def map_display_telemetry(self, sender=None): - self.object_details_action(sender) + def map_display_telemetry(self, sender=None, event=None): + alt_event = False + if sender != None: + if hasattr(sender, "last_touch"): + if hasattr(sender.last_touch, "button"): + if sender.last_touch.button == "right": + alt_event = True + + if alt_event: + try: + if hasattr(sender, "source_dest"): + self.sideband.request_latest_telemetry(from_addr=sender.source_dest) + toast("Telemetry request sent") + except Exception as e: + RNS.log(f"Could not request telemetry update: {e}", RNS.LOG_ERROR) + else: + self.object_details_action(sender) def map_display_own_telemetry(self, sender=None): self.sideband.update_telemetry() From 304469315dceccdd79f4b0ec18cf3a39b5a75e99 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 19 Jan 2025 22:20:11 +0100 Subject: [PATCH 25/76] Updated build code --- sbapp/buildozer.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 3c64903..c9cb33c 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,7 +10,7 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20250115 +android.numeric_version = 20250119 requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions From 1d438f925b7b58c8e74e961065caab1b57ff13b7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 19 Jan 2025 22:30:30 +0100 Subject: [PATCH 26/76] Updated info text --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 803fef7..21ff373 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2760,7 +2760,7 @@ class SidebandApp(MDApp): str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)" str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)" str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Python[/b] (PSF License)" - str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright (c) 2024 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY" + str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright Β© 2025 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY" info = "This is "+self.root.ids.app_version_info.text+", on RNS v"+RNS.__version__+" and LXMF v"+LXMF.__version__+".\n\nHumbly build using the following open components:\n\n"+str_comps self.information_screen.ids.information_info.text = info self.information_screen.ids.information_info.bind(on_ref_press=link_exec) From 95fec8219b3d0fa50cec98857e64f78fc7c8457c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 11:32:50 +0100 Subject: [PATCH 27/76] Updated build code --- sbapp/buildozer.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index c9cb33c..01fea20 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,7 +10,7 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20250119 +android.numeric_version = 20250120 requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions From a90a451865b01f868097b05c456b780f25ca4014 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 11:46:32 +0100 Subject: [PATCH 28/76] Set LXMF renderer field if message has BB-code markup --- sbapp/sideband/core.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 53fd60d..b68186b 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -4396,6 +4396,8 @@ class SidebandCore(): fields[LXMF.FIELD_IMAGE] = image if audio != None: fields[LXMF.FIELD_AUDIO] = audio + if self.has_bb_markup(content): + fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_BBCODE lxm = LXMF.LXMessage(dest, source, content, title="", desired_method=desired_method, fields = fields, include_ticket=self.is_trusted(destination_hash)) @@ -4534,11 +4536,19 @@ class SidebandCore(): self.setstate("lxm_uri_ingest.result", response) - def strip_markup(self, text): + def strip_bb_markup(self, text): if not hasattr(self, "smr") or self.smr == None: self.smr = re.compile(r'\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]',re.IGNORECASE | re.MULTILINE ) return self.smr.sub("", text) + def has_bb_markup(self, text): + if not hasattr(self, "smr") or self.smr == None: + self.smr = re.compile(r'\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]',re.IGNORECASE | re.MULTILINE ) + if self.smr.match(text): + return True + else: + return False + def lxm_ingest(self, message, originator = False): should_notify = False is_trusted = False @@ -4621,7 +4631,7 @@ class SidebandCore(): if should_notify: nlen = 128 text = message.content.decode("utf-8") - notification_content = self.strip_markup(text[:nlen]) + notification_content = self.strip_bb_markup(text[:nlen]) if len(text) > nlen: notification_content += " [...]" From 84b214cb909abdb507fd91338da5930b3f16c943 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 14:25:58 +0100 Subject: [PATCH 29/76] Added markdown rendering and message composing --- sbapp/buildozer.spec | 2 +- sbapp/main.py | 54 +++++++++++++++++++++++++++++++++++++++++- sbapp/sideband/core.py | 15 +++++++++--- sbapp/ui/layouts.py | 16 +++++++++++++ sbapp/ui/messages.py | 25 +++++++++++++------ setup.py | 2 ++ 6 files changed, 102 insertions(+), 12 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 01fea20..24721b1 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -12,7 +12,7 @@ version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py android.numeric_version = 20250120 -requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions +requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions,mistune>=3.0.2,beautifulsoup4 android.gradle_dependencies = com.android.support:support-compat:28.0.0 #android.enable_androidx = True diff --git a/sbapp/main.py b/sbapp/main.py index 21ff373..6eb4294 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -19,6 +19,7 @@ import RNS import LXMF import time import os +import re import pathlib import base64 import threading @@ -1523,6 +1524,50 @@ class SidebandApp(MDApp): ### Messages (conversation) screen ###################################### + + def md_to_bbcode(self, text): + if not hasattr(self, "mdconv"): + from md2bbcode.main import process_readme as mdconv + self.mdconv = mdconv + converted = self.mdconv(text) + while converted.endswith("\n"): + converted = converted[:-1] + + return converted + + def process_bb_markup(self, text): + st = time.time() + ms = int(sp(14)) + h1s = int(sp(20)) + h2s = int(sp(18)) + h3s = int(sp(16)) + + if not hasattr(self, "pres"): + self.pres = [] + res = [ [r"\[(?:code|icode).*?\]", f"[font=mono][size={ms}]"], + [r"\[\/(?:code|icode).*?\]", "[/size][/font]"], + [r"\[(?:heading)\]", f"[b][size={h1s}]"], + [r"\[(?:heading=1)*?\]", f"[b][size={h1s}]"], + [r"\[(?:heading=2)*?\]", f"[b][size={h2s}]"], + [r"\[(?:heading=3)*?\]", f"[b][size={h3s}]"], + [r"\[(?:heading=).*?\]", f"[b][size={h3s}]"], # Match all remaining lower-level headings + [r"\[\/(?:heading).*?\]", "[/size][/b]"], + [r"\[(?:list).*?\]", ""], + [r"\[\/(?:list).*?\]", ""], + [r"\n\[(?:\*).*?\]", "\n - "], + [r"\[(?:url).*?\]", ""], # Strip URLs for now + [r"\[\/(?:url).*?\]", ""], + [r"\[(?:img).*?\].*\[\/(?:img).*?\]", ""] # Strip images for now + ] + + for r in res: + self.pres.append([re.compile(r[0], re.IGNORECASE | re.MULTILINE ), r[1]]) + + for pr in self.pres: + text = pr[0].sub(pr[1], text) + + return text + def conversation_from_announce_action(self, context_dest): if self.sideband.has_conversation(context_dest): pass @@ -2758,7 +2803,7 @@ class SidebandApp(MDApp): str_comps = " - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)" - str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)" + str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]MD2bbcode[/b] (GPL3 License)" str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Python[/b] (PSF License)" str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright Β© 2025 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY" info = "This is "+self.root.ids.app_version_info.text+", on RNS v"+RNS.__version__+" and LXMF v"+LXMF.__version__+".\n\nHumbly build using the following open components:\n\n"+str_comps @@ -3041,6 +3086,10 @@ class SidebandApp(MDApp): self.sideband.config["trusted_markup_only"] = self.settings_screen.ids.settings_trusted_markup_only.active self.sideband.save_configuration() + def save_compose_in_markdown(sender=None, event=None): + self.sideband.config["compose_in_markdown"] = self.settings_screen.ids.settings_compose_in_markdown.active + self.sideband.save_configuration() + def save_advanced_stats(sender=None, event=None): self.sideband.config["advanced_stats"] = self.settings_screen.ids.settings_advanced_statistics.active self.sideband.save_configuration() @@ -3219,6 +3268,9 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_trusted_markup_only.active = self.sideband.config["trusted_markup_only"] self.settings_screen.ids.settings_trusted_markup_only.bind(active=save_trusted_markup_only) + self.settings_screen.ids.settings_compose_in_markdown.active = self.sideband.config["compose_in_markdown"] + self.settings_screen.ids.settings_compose_in_markdown.bind(active=save_compose_in_markdown) + self.settings_screen.ids.settings_ignore_invalid_stamps.active = self.sideband.config["lxmf_ignore_invalid_stamps"] self.settings_screen.ids.settings_ignore_invalid_stamps.bind(active=save_lxmf_ignore_invalid_stamps) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index b68186b..c4c3669 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -457,6 +457,7 @@ class SidebandCore(): self.config["eink_mode"] = True self.config["lxm_limit_1mb"] = True self.config["trusted_markup_only"] = False + self.config["compose_in_markdown"] = False # Connectivity self.config["connect_transport"] = False @@ -601,6 +602,8 @@ class SidebandCore(): self.config["hq_ptt"] = False if not "trusted_markup_only" in self.config: self.config["trusted_markup_only"] = False + if not "compose_in_markdown" in self.config: + self.config["compose_in_markdown"] = False if not "input_language" in self.config: self.config["input_language"] = None @@ -4396,7 +4399,13 @@ class SidebandCore(): fields[LXMF.FIELD_IMAGE] = image if audio != None: fields[LXMF.FIELD_AUDIO] = audio - if self.has_bb_markup(content): + md_sig = "#!md\n" + if content.startswith(md_sig): + content = content[len(md_sig):] + fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_MARKDOWN + elif self.config["compose_in_markdown"]: + fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_MARKDOWN + elif self.has_bb_markup(content): fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_BBCODE lxm = LXMF.LXMessage(dest, source, content, title="", desired_method=desired_method, fields = fields, include_ticket=self.is_trusted(destination_hash)) @@ -4538,12 +4547,12 @@ class SidebandCore(): def strip_bb_markup(self, text): if not hasattr(self, "smr") or self.smr == None: - self.smr = re.compile(r'\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]',re.IGNORECASE | re.MULTILINE ) + self.smr = re.compile(r"\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]",re.IGNORECASE | re.MULTILINE ) return self.smr.sub("", text) def has_bb_markup(self, text): if not hasattr(self, "smr") or self.smr == None: - self.smr = re.compile(r'\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]',re.IGNORECASE | re.MULTILINE ) + self.smr = re.compile(r"\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]",re.IGNORECASE | re.MULTILINE ) if self.smr.match(text): return True else: diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 4e6ab43..6155953 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -1655,6 +1655,22 @@ MDScreen: disabled: False active: False + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Compose messages in markdown" + font_style: "H6" + + MDSwitch: + id: settings_compose_in_markdown + pos_hint: {"center_y": 0.3} + disabled: False + active: False + MDBoxLayout: orientation: "horizontal" size_hint_y: None diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index b884b76..87557b0 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -110,8 +110,6 @@ class Messages(): msg = self.app.sideband.message(lxm_hash) if msg: close_button = MDRectangleFlatButton(text="Close", font_size=dp(18)) - # d_items = [ ] - # d_items.append(DialogItem(IconLeftWidget(icon="postage-stamp"), text="[size="+str(ss)+"]Stamp[/size]")) d_text = "" @@ -492,11 +490,24 @@ class Messages(): for m in self.new_messages: if not m["hash"] in self.added_item_hashes: + renderer = None + message_source = m["content"] + if "lxm" in m and m["lxm"] and m["lxm"].fields != None and LXMF.FIELD_RENDERER in m["lxm"].fields: + renderer = m["lxm"].fields[LXMF.FIELD_RENDERER] + try: if self.app.sideband.config["trusted_markup_only"] and not self.is_trusted: message_input = str( escape_markup(m["content"].decode("utf-8")) ).encode("utf-8") else: message_input = m["content"] + if renderer == LXMF.RENDERER_MARKDOWN: + message_input = self.app.md_to_bbcode(message_input.decode("utf-8")).encode("utf-8") + message_input = self.app.process_bb_markup(message_input.decode("utf-8")).encode("utf-8") + elif renderer == LXMF.RENDERER_BBCODE: + message_input = self.app.process_bb_markup(message_input.decode("utf-8")).encode("utf-8") + else: + message_input = str(escape_markup(m["content"].decode("utf-8"))).encode("utf-8") + except Exception as e: RNS.log(f"Message content could not be decoded: {e}", RNS.LOG_DEBUG) message_input = b"" @@ -1144,7 +1155,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy message text", "height": dp(40), - "on_release": gen_copy(message_input.decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -1178,7 +1189,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy message text", "height": dp(40), - "on_release": gen_copy(message_input.decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -1196,7 +1207,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy", "height": dp(40), - "on_release": gen_copy(message_input.decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -1213,7 +1224,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy", "height": dp(40), - "on_release": gen_copy(message_input.decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "viewclass": "OneLineListItem", @@ -1236,7 +1247,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy", "height": dp(40), - "on_release": gen_copy(message_input.decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", diff --git a/setup.py b/setup.py index e6b2cf7..6a5f879 100644 --- a/setup.py +++ b/setup.py @@ -123,6 +123,8 @@ setuptools.setup( "ffpyplayer", "sh", "numpy<=1.26.4", + "mistune>=3.0.2", + "beautifulsoup4", "pycodec2;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", "pyaudio;sys.platform=='linux'", "pyobjus;sys.platform=='darwin'", From 033c3d6658f396b264cf9e4963383d5ebbcfeb5f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 14:46:28 +0100 Subject: [PATCH 30/76] Unify bbcode sizing across devices with different display densities --- sbapp/main.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sbapp/main.py b/sbapp/main.py index 6eb4294..46d4947 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1543,6 +1543,7 @@ class SidebandApp(MDApp): h3s = int(sp(16)) if not hasattr(self, "pres"): + self.presz = re.compile(r"\[(?:size=\d*?)\]", re.IGNORECASE | re.MULTILINE ) self.pres = [] res = [ [r"\[(?:code|icode).*?\]", f"[font=mono][size={ms}]"], [r"\[\/(?:code|icode).*?\]", "[/size][/font]"], @@ -1563,6 +1564,11 @@ class SidebandApp(MDApp): for r in res: self.pres.append([re.compile(r[0], re.IGNORECASE | re.MULTILINE ), r[1]]) + + size_matches = self.presz.findall(text) + for sm in size_matches: + text = text.replace(sm, f"{sm[:-1]}sp]") + for pr in self.pres: text = pr[0].sub(pr[1], text) From 0a28ec76f3ea7549bd103e1fa09b69267541dbb7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 14:46:48 +0100 Subject: [PATCH 31/76] Added library --- sbapp/md2bbcode/__init__.py | 0 sbapp/md2bbcode/html2bbcode.py | 132 ++++++++++++++ sbapp/md2bbcode/main.py | 67 ++++++++ sbapp/md2bbcode/md2ast.py | 47 +++++ sbapp/md2bbcode/plugins/merge_lists.py | 83 +++++++++ sbapp/md2bbcode/renderers/__init__.py | 0 sbapp/md2bbcode/renderers/bbcode.py | 228 +++++++++++++++++++++++++ 7 files changed, 557 insertions(+) create mode 100644 sbapp/md2bbcode/__init__.py create mode 100644 sbapp/md2bbcode/html2bbcode.py create mode 100644 sbapp/md2bbcode/main.py create mode 100644 sbapp/md2bbcode/md2ast.py create mode 100644 sbapp/md2bbcode/plugins/merge_lists.py create mode 100644 sbapp/md2bbcode/renderers/__init__.py create mode 100644 sbapp/md2bbcode/renderers/bbcode.py diff --git a/sbapp/md2bbcode/__init__.py b/sbapp/md2bbcode/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sbapp/md2bbcode/html2bbcode.py b/sbapp/md2bbcode/html2bbcode.py new file mode 100644 index 0000000..98fd830 --- /dev/null +++ b/sbapp/md2bbcode/html2bbcode.py @@ -0,0 +1,132 @@ +# converts some HTML tags to BBCode +# pass --debug to save the output to readme.finalpass +# may be better off replacing this with html to markdown (and then to bbcode). Lepture recommeds a JS html to markdown converter: sundown +from bs4 import BeautifulSoup, NavigableString +import argparse + +def handle_font_tag(tag, replacements): + """Handles the conversion of tag with attributes like color and size.""" + attributes = [] + if 'color' in tag.attrs: + attributes.append(f"COLOR={tag['color']}") + if 'size' in tag.attrs: + attributes.append(f"SIZE={tag['size']}") + if 'face' in tag.attrs: + attributes.append(f"FONT={tag['face']}") + + inner_content = ''.join(recursive_html_to_bbcode(child, replacements) for child in tag.children) + if attributes: + # Nest all attributes. Example: [COLOR=red][SIZE=5]content[/SIZE][/COLOR] + for attr in reversed(attributes): + inner_content = f"[{attr}]{inner_content}[/{attr.split('=')[0]}]" + return inner_content + +def handle_style_tag(tag, replacements): + """Handles the conversion of tags with style attributes like color, size, and font.""" + attributes = [] + style = tag.attrs.get('style', '') + + # Extracting CSS properties + css_properties = {item.split(':')[0].strip(): item.split(':')[1].strip() for item in style.split(';') if ':' in item} + + # Mapping CSS properties to BBCode + if 'color' in css_properties: + attributes.append(f"COLOR={css_properties['color']}") + if 'font-size' in css_properties: + attributes.append(f"SIZE={css_properties['font-size']}") + if 'font-family' in css_properties: + attributes.append(f"FONT={css_properties['font-family']}") + if 'text-decoration' in css_properties and 'line-through' in css_properties['text-decoration']: + attributes.append("S") # Assume strike-through + if 'text-decoration' in css_properties and 'underline' in css_properties['text-decoration']: + attributes.append("U") + if 'font-weight' in css_properties: + if css_properties['font-weight'].lower() == 'bold' or (css_properties['font-weight'].isdigit() and int(css_properties['font-weight']) >= 700): + attributes.append("B") # Assume bold + + inner_content = ''.join(recursive_html_to_bbcode(child, replacements) for child in tag.children) + if attributes: + # Nest all attributes + for attr in reversed(attributes): + if '=' in attr: # For attributes with values + inner_content = f"[{attr}]{inner_content}[/{attr.split('=')[0]}]" + else: # For simple BBCode tags like [B], [I], [U], [S] + inner_content = f"[{attr}]{inner_content}[/{attr}]" + return inner_content + +def recursive_html_to_bbcode(element): + """Recursively convert HTML elements to BBCode.""" + bbcode = '' + + if isinstance(element, NavigableString): + bbcode += str(element) + elif element.name == 'details': + # Handle
tag + summary = element.find('summary') + spoiler_title = '' + if summary: + # Get the summary content and remove the summary element + spoiler_title = '=' + ''.join([recursive_html_to_bbcode(child) for child in summary.contents]) + summary.decompose() + + # Process remaining content + content = ''.join([recursive_html_to_bbcode(child) for child in element.contents]) + bbcode += f'[SPOILER{spoiler_title}]{content}[/SPOILER]' + elif element.name == 'summary': + # Skip summary tag as it's handled in details + return '' + else: + # Handle other tags or pass through + content = ''.join([recursive_html_to_bbcode(child) for child in element.contents]) + bbcode += content + + return bbcode + +def html_to_bbcode(html): + replacements = { + 'b': 'B', + 'strong': 'B', + 'i': 'I', + 'em': 'I', + 'u': 'U', + 's': 'S', + 'sub': 'SUB', + 'sup': 'SUP', + 'p': '', # Handled by default + 'ul': 'LIST', + 'ol': 'LIST=1', + 'li': '*', # Special handling in recursive function + 'font': '', # To be handled for attributes + 'blockquote': 'QUOTE', + 'pre': 'CODE', + 'code': 'ICODE', + 'a': 'URL', # Special handling for attributes + 'img': 'IMG' # Special handling for attributes + } + + soup = BeautifulSoup(html, 'html.parser') + return recursive_html_to_bbcode(soup) + +def process_html(input_html, debug=False, output_file=None): + converted_bbcode = html_to_bbcode(input_html) + + if debug: + with open(output_file, 'w', encoding='utf-8') as file: + file.write(converted_bbcode) + else: + return converted_bbcode + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Convert HTML to BBCode with optional debugging output.") + parser.add_argument('input_file', type=str, help='Input HTML file path') + parser.add_argument('--debug', action='store_true', help='Save output to readme.finalpass for debugging') + + args = parser.parse_args() + input_file = args.input_file + output_file = 'readme.finalpass' if args.debug else None + + with open(input_file, 'r', encoding='utf-8') as file: + html_content = file.read() + + # Call the processing function + process_html(html_content, debug=args.debug, output_file=output_file) \ No newline at end of file diff --git a/sbapp/md2bbcode/main.py b/sbapp/md2bbcode/main.py new file mode 100644 index 0000000..4cb1d1c --- /dev/null +++ b/sbapp/md2bbcode/main.py @@ -0,0 +1,67 @@ +# uses a custom mistune renderer to convert Markdown to BBCode. The custom renderer is defined in the bbcode.py file. +# pass --debug to save the output to readme.1stpass (main.py) and readme.finalpass (html2bbcode) +# for further debugging, you can convert the markdown file to AST using md2ast.py. Remember to load the plugin(s) you want to test. + +#standard library +import argparse +import sys + +# mistune +import mistune +from mistune.plugins.formatting import strikethrough, mark, superscript, subscript, insert +from mistune.plugins.table import table, table_in_list +from mistune.plugins.footnotes import footnotes +from mistune.plugins.task_lists import task_lists +from mistune.plugins.def_list import def_list +from mistune.plugins.abbr import abbr +from mistune.plugins.spoiler import spoiler + +# local +from md2bbcode.plugins.merge_lists import merge_ordered_lists +from md2bbcode.renderers.bbcode import BBCodeRenderer +from md2bbcode.html2bbcode import process_html + +def convert_markdown_to_bbcode(markdown_text, domain): + # Create a Markdown parser instance using the custom BBCode renderer + markdown_parser = mistune.create_markdown(renderer=BBCodeRenderer(domain=domain), plugins=[strikethrough, mark, superscript, subscript, insert, table, footnotes, task_lists, def_list, abbr, spoiler, table_in_list, merge_ordered_lists]) + + # Convert Markdown text to BBCode + return markdown_parser(markdown_text) + +def process_readme(markdown_text, domain=None, debug=False): + # Convert Markdown to BBCode + bbcode_text = convert_markdown_to_bbcode(markdown_text, domain) + + # If debug mode, save intermediate BBCode + if debug: + with open('readme.1stpass', 'w', encoding='utf-8') as file: + file.write(bbcode_text) + + # Convert BBCode formatted as HTML to final BBCode + final_bbcode = process_html(bbcode_text, debug, 'readme.finalpass') + + return final_bbcode + +def main(): + parser = argparse.ArgumentParser(description='Convert Markdown file to BBCode with HTML processing.') + parser.add_argument('input', help='Input Markdown file path') + parser.add_argument('--domain', help='Domain to prepend to relative URLs') + parser.add_argument('--debug', action='store_true', help='Output intermediate results to files for debugging') + args = parser.parse_args() + + if args.input == '-': + # Read Markdown content from stdin + markdown_text = sys.stdin.read() + else: + with open(args.input, 'r', encoding='utf-8') as md_file: + markdown_text = md_file.read() + + # Process the readme and get the final BBCode + final_bbcode = process_readme(markdown_text, args.domain, args.debug) + + # Optionally, print final BBCode to console + if not args.debug: + print(final_bbcode) + +if __name__ == '__main__': + main() diff --git a/sbapp/md2bbcode/md2ast.py b/sbapp/md2bbcode/md2ast.py new file mode 100644 index 0000000..65b7c3d --- /dev/null +++ b/sbapp/md2bbcode/md2ast.py @@ -0,0 +1,47 @@ +# this is for debugging the custom mistune renderer bbcode.py +import argparse +import mistune +import json # Import the json module for serialization +from mistune.plugins.formatting import strikethrough, mark, superscript, subscript, insert +from mistune.plugins.table import table, table_in_list +from mistune.plugins.footnotes import footnotes +from mistune.plugins.task_lists import task_lists +from mistune.plugins.def_list import def_list +from mistune.plugins.abbr import abbr +from mistune.plugins.spoiler import spoiler + +#local +from md2bbcode.plugins.merge_lists import merge_ordered_lists + +def convert_markdown_to_ast(input_filepath, output_filepath): + # Initialize Markdown parser with no renderer to produce an AST + markdown_parser = mistune.create_markdown(renderer=None, plugins=[strikethrough, mark, superscript, subscript, insert, table, footnotes, task_lists, def_list, abbr, spoiler, table_in_list, merge_ordered_lists]) + + # Read the input Markdown file + with open(input_filepath, 'r', encoding='utf-8') as md_file: + markdown_text = md_file.read() + + # Convert Markdown text to AST + ast_text = markdown_parser(markdown_text) + + # Serialize the AST to a JSON string + ast_json = json.dumps(ast_text, indent=4) + + # Write the output AST to a new file in JSON format + with open(output_filepath, 'w', encoding='utf-8') as ast_file: + ast_file.write(ast_json) + +def main(): + # Create argument parser + parser = argparse.ArgumentParser(description='Convert Markdown file to AST file (JSON format).') + # Add arguments + parser.add_argument('input', help='Input Markdown file path') + parser.add_argument('output', help='Output AST file path (JSON format)') + # Parse arguments + args = parser.parse_args() + + # Convert the Markdown to AST using the provided paths + convert_markdown_to_ast(args.input, args.output) + +if __name__ == '__main__': + main() diff --git a/sbapp/md2bbcode/plugins/merge_lists.py b/sbapp/md2bbcode/plugins/merge_lists.py new file mode 100644 index 0000000..5f499e1 --- /dev/null +++ b/sbapp/md2bbcode/plugins/merge_lists.py @@ -0,0 +1,83 @@ +from typing import Dict, Any, List + +def merge_ordered_lists(md): + """ + A plugin to merge consecutive "top-level" ordered lists into one, + and also attach any intervening code blocks or blank lines to the + last list item so that the final BBCode appears as a single list + with multiple steps. + + This relies on a few assumptions: + 1) The only tokens between two ordered lists that should be merged + are code blocks or blank lines (not normal paragraphs). + 2) We want any code block(s) right after a list item to appear in + that same bullet item. + """ + + def rewrite_tokens(md, state): + tokens = state.tokens + merged = [] + i = 0 + + while i < len(tokens): + token = tokens[i] + + # Check if this token is a top-level ordered list + if ( + token["type"] == "list" + and token.get("attrs", {}).get("ordered", False) + and token.get("attrs", {}).get("depth", 0) == 0 + ): + # Start new merged list + current_depth = token["attrs"]["depth"] + list_items = list(token["children"]) # bullet items in the first list + i += 1 + + # Continue until we run into something that's not: + # another top-level ordered list, + # or code blocks / blank lines (which we'll attach to the last bullet). + while i < len(tokens): + nxt = tokens[i] + + # If there's another ordered list at the same depth, merge its bullet items + if ( + nxt["type"] == "list" + and nxt.get("attrs", {}).get("ordered", False) + and nxt.get("attrs", {}).get("depth", 0) == current_depth + ): + list_items.extend(nxt["children"]) + i += 1 + + # If there's a code block or blank line, attach it to the *last* bullet item. + elif nxt["type"] in ["block_code", "blank_line"]: + if list_items: # attach to last bullet item, if any + list_items[-1]["children"].append(nxt) + i += 1 + + else: + # Not a same-depth list or code blockβ€”stop merging + break + + # Create single merged list token + merged.append( + { + "type": "list", + "children": list_items, + "attrs": { + "ordered": True, + "depth": current_depth, + }, + } + ) + + else: + # If not a top-level ordered list, just keep it as-is + merged.append(token) + i += 1 + + # Replace the old tokens with the merged version + state.tokens = merged + + # Attach to before_render_hooks so we can manipulate tokens before rendering + md.before_render_hooks.append(rewrite_tokens) + return md \ No newline at end of file diff --git a/sbapp/md2bbcode/renderers/__init__.py b/sbapp/md2bbcode/renderers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sbapp/md2bbcode/renderers/bbcode.py b/sbapp/md2bbcode/renderers/bbcode.py new file mode 100644 index 0000000..32e8b49 --- /dev/null +++ b/sbapp/md2bbcode/renderers/bbcode.py @@ -0,0 +1,228 @@ +from mistune.core import BaseRenderer +from mistune.util import escape as escape_text, striptags, safe_entity +from urllib.parse import urljoin, urlparse + + +class BBCodeRenderer(BaseRenderer): + """A renderer for converting Markdown to BBCode.""" + _escape: bool + NAME = 'bbcode' + + def __init__(self, escape=False, domain=None): + super(BBCodeRenderer, self).__init__() + self._escape = escape + self.domain = domain + + def render_token(self, token, state): + func = self._get_method(token['type']) + attrs = token.get('attrs') + + if 'raw' in token: + text = token['raw'] + elif 'children' in token: + text = self.render_tokens(token['children'], state) + else: + if attrs: + return func(**attrs) + else: + return func() + if attrs: + return func(text, **attrs) + else: + return func(text) + + def safe_url(self, url: str) -> str: + # Simple URL sanitization + if url.startswith(('javascript:', 'vbscript:', 'data:')): + return '#harmful-link' + # Check if the URL is absolute by looking for a netloc part in the URL + if not urlparse(url).netloc: + url = urljoin(self.domain, url) + return url + + def text(self, text: str) -> str: + if self._escape: + return escape_text(text) + return text + + def emphasis(self, text: str) -> str: + return '[i]' + text + '[/i]' + + def strong(self, text: str) -> str: + return '[b]' + text + '[/b]' + + def link(self, text: str, url: str, title=None) -> str: + return '[url=' + self.safe_url(url) + ']' + text + '[/url]' + + def image(self, text: str, url: str, title=None) -> str: + alt_text = f' alt="{text}"' if text else '' + img_tag = f'[img{alt_text}]' + self.safe_url(url) + '[/img]' + # Check if alt text starts with 'pixel' and treat it as pixel art + if text and text.lower().startswith('pixel'): + return f'[pixelate]{img_tag}[/pixelate]' + return img_tag + + def codespan(self, text: str) -> str: + return '[icode]' + text + '[/icode]' + + def linebreak(self) -> str: + return '\n' + + def softbreak(self) -> str: + return '' + + def inline_html(self, html: str) -> str: + if self._escape: + return escape_text(html) + return html + + def paragraph(self, text: str) -> str: + return text + '\n\n' + + def heading(self, text: str, level: int, **attrs) -> str: + if 1 <= level <= 3: + return f"[HEADING={level}]{text}[/HEADING]\n" + else: + # Handle cases where level is outside 1-3 + return f"[HEADING=3]{text}[/HEADING]\n" + + def blank_line(self) -> str: + return '' + + def thematic_break(self) -> str: + return '[hr][/hr]\n' + + def block_text(self, text: str) -> str: + return text + + def block_code(self, code: str, **attrs) -> str: + # Renders blocks of code using the language specified in Markdown + special_cases = { + 'plaintext': None # Default [CODE] + } + + if 'info' in attrs: + lang_info = safe_entity(attrs['info'].strip()) + lang = lang_info.split(None, 1)[0].lower() + # Check if the language needs special handling + bbcode_lang = special_cases.get(lang, lang) # Use the special case if it exists, otherwise use lang as is + if bbcode_lang: + return f"[CODE={bbcode_lang}]{escape_text(code)}[/CODE]\n" + else: + return f"[CODE]{escape_text(code)}[/CODE]\n" + else: + # No language specified, render with a generic [CODE] tag + return f"[CODE]{escape_text(code)}[/CODE]\n" + + def block_quote(self, text: str) -> str: + return '[QUOTE]\n' + text + '[/QUOTE]\n' + + def block_html(self, html: str) -> str: + if self._escape: + return '

' + escape_text(html.strip()) + '

\n' + return html + '\n' + + def block_error(self, text: str) -> str: + return '[color=red][icode]' + text + '[/icode][/color]\n' + + def list(self, text: str, ordered: bool, **attrs) -> str: + # For ordered lists, always use [list=1] to get automatic sequential numbering + # For unordered lists, use [list] + tag = 'list=1' if ordered else 'list' + return '[{}]'.format(tag) + text + '[/list]\n' + + def list_item(self, text: str) -> str: + return '[*]' + text + '\n' + + def strikethrough(self, text: str) -> str: + return '[s]' + text + '[/s]' + + def mark(self, text: str) -> str: + # Simulate the mark effect with a background color in BBCode + return '[mark]' + text + '[/mark]' + + def insert(self, text: str) -> str: + # Use underline to represent insertion + return '[u]' + text + '[/u]' + + def superscript(self, text: str) -> str: + return '[sup]' + text + '[/sup]' + + def subscript(self, text: str) -> str: + return '[sub]' + text + '[/sub]' + + def inline_spoiler(self, text: str) -> str: + return '[ISPOILER]' + text + '[/ISPOILER]' + + def block_spoiler(self, text: str) -> str: + return '[SPOILER]\n' + text + '\n[/SPOILER]' + + def footnote_ref(self, key: str, index: int): + # Use superscript for the footnote reference + return f'[sup][u][JUMPTO=fn-{index}]{index}[/JUMPTO][/u][/sup]' + + def footnotes(self, text: str): + # Optionally wrap all footnotes in a specific section if needed + return '[b]Footnotes:[/b]\n' + text + + def footnote_item(self, text: str, key: str, index: int): + # Define the footnote with an anchor at the end of the document + return f'[ANAME=fn-{index}]{index}[/ANAME]. {text}' + + def table(self, children, **attrs): + # Starting with a full-width table by default if not specified + # width = attrs.get('width', '100%') # comment out until XF 2.3 + # return f'[TABLE width="{width}"]\n' + children + '[/TABLE]\n' # comment out until XF 2.3 + return '[TABLE]\n' + children + '[/TABLE]\n' + + def table_head(self, children, **attrs): + return '[TR]\n' + children + '[/TR]\n' + + def table_body(self, children, **attrs): + return children + + def table_row(self, children, **attrs): + return '[TR]\n' + children + '[/TR]\n' + + def table_cell(self, text, align=None, head=False, **attrs): + # BBCode does not support direct cell alignment, + # use [LEFT], [CENTER], or [RIGHT] tags + + # Use th for header cells and td for normal cells + tag = 'TH' if head else 'TD' + + # Initialize alignment tags + alignment_start = '' + alignment_end = '' + + if align == 'center': + alignment_start = '[CENTER]' + alignment_end = '[/CENTER]' + elif align == 'right': + alignment_start = '[RIGHT]' + alignment_end = '[/RIGHT]' + elif align == 'left': + alignment_start = '[LEFT]' + alignment_end = '[/LEFT]' + + return f'[{tag}]{alignment_start}{text}{alignment_end}[/{tag}]\n' + + def task_list_item(self, text: str, checked: bool = False) -> str: + # Using emojis to represent the checkbox + checkbox_emoji = 'πŸ—Ή' if checked else '☐' + return checkbox_emoji + ' ' + text + '\n' + + def def_list(self, text: str) -> str: + # No specific BBCode tag for
, so we just use the plain text grouping + return '\n' + text + '\n' + + def def_list_head(self, text: str) -> str: + return '[b]' + text + '[/b]' + ' ' + ':' + '\n' + + def def_list_item(self, text: str) -> str: + return '[INDENT]' + text + '[/INDENT]\n' + + def abbr(self, text: str, title: str) -> str: + if title: + return f'[abbr={title}]{text}[/abbr]' + return text \ No newline at end of file From 13071fd9d863bf82cf08ca14fe833777b2ef6a96 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 17:28:29 +0100 Subject: [PATCH 32/76] Updated build spec --- sideband.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sideband.spec b/sideband.spec index f0395be..67f1d3f 100644 --- a/sideband.spec +++ b/sideband.spec @@ -7,7 +7,7 @@ a = Analysis( pathex=[], binaries=[], datas=[], - hiddenimports=[], + hiddenimports=["mistune", "bs4"], hookspath=[], hooksconfig={}, runtime_hooks=[], From b3b5d607e0c83bb6a772ae359e7487524575cc28 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Jan 2025 02:35:59 +0100 Subject: [PATCH 33/76] Updated example --- docs/example_plugins/view.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/example_plugins/view.py b/docs/example_plugins/view.py index a30f9d1..5146ade 100644 --- a/docs/example_plugins/view.py +++ b/docs/example_plugins/view.py @@ -310,7 +310,8 @@ class ViewCommandPlugin(SidebandCommandPlugin): else: image_field = self.sources[source].get_image_field(quality_preset) image_timestamp = self.timestamp_str(self.sources[source].last_update) - message = f"Source [b]{source}[/b] at [b]{image_timestamp}[/b]" + message = "#!md\n" # Tell sideband to format this message + message += f"Source [b]{source}[/b] at [b]{image_timestamp}[/b]" if image_field != None: self.image_response(message, image_field, requestor) From 5def6199306964dffa18ae3b8f225458a1617507 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Jan 2025 22:30:27 +0100 Subject: [PATCH 34/76] Added MQTT renderers to Telemeter --- sbapp/sideband/sense.py | 438 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 433 insertions(+), 5 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 82b7ddb..002e6c7 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -33,6 +33,7 @@ class Telemeter(): s.data = s.unpack(p[sid]) s.synthesized = True s.active = True + s._telemeter = t t.sensors[name] = s return t @@ -53,8 +54,8 @@ class Telemeter(): Sensor.SID_PROXIMITY: Proximity, Sensor.SID_POWER_CONSUMPTION: PowerConsumption, Sensor.SID_POWER_PRODUCTION: PowerProduction, Sensor.SID_PROCESSOR: Processor, Sensor.SID_RAM: RandomAccessMemory, Sensor.SID_NVM: NonVolatileMemory, - Sensor.SID_CUSTOM: Custom, Sensor.SID_TANK: Tank, Sensor.SID_FUEL: Fuel, - } + Sensor.SID_CUSTOM: Custom, Sensor.SID_TANK: Tank, Sensor.SID_FUEL: Fuel} + self.available = { "time": Sensor.SID_TIME, "information": Sensor.SID_INFORMATION, "received": Sensor.SID_RECEIVED, @@ -66,8 +67,12 @@ class Telemeter(): "acceleration": Sensor.SID_ACCELERATION, "proximity": Sensor.SID_PROXIMITY, "power_consumption": Sensor.SID_POWER_CONSUMPTION, "power_production": Sensor.SID_POWER_PRODUCTION, "processor": Sensor.SID_PROCESSOR, "ram": Sensor.SID_RAM, "nvm": Sensor.SID_NVM, - "custom": Sensor.SID_CUSTOM, "tank": Sensor.SID_TANK, "fuel": Sensor.SID_FUEL - } + "custom": Sensor.SID_CUSTOM, "tank": Sensor.SID_TANK, "fuel": Sensor.SID_FUEL} + + self.names = {} + for name in self.available: + self.names[self.available[name]] = name + self.from_packed = from_packed self.sensors = {} if not self.from_packed: @@ -77,6 +82,12 @@ class Telemeter(): self.android_context = android_context self.service = service + def get_name(self, sid): + if sid in self.names: + return self.names[sid] + else: + return None + def synthesize(self, sensor): if sensor in self.available: if not sensor in self.sensors: @@ -268,6 +279,15 @@ class Sensor(): def render(self, relative_to=None): return None + def render_mqtt(self, relative_to=None): + return None + + def name(self): + if self._telemeter != None: + return self._telemeter.get_name(self._sid) + else: + return None + def check_permission(self, permission): if self._telemeter != None: return self._telemeter.check_permission(permission) @@ -319,6 +339,19 @@ class Time(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + topic = self.name() + rendered = { + f"{topic}/name": "Timestamp", + f"{topic}/icon": "clock-time-ten-outline", + f"{topic}/utc": self.data["utc"], + } + else: + rendered = None + + return rendered + class Information(Sensor): SID = Sensor.SID_INFORMATION STALE_TIME = 5 @@ -364,6 +397,19 @@ class Information(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + topic = self.name() + rendered = { + f"{topic}/name": "Information", + f"{topic}/icon": "information-variant", + f"{topic}/text": self.data["contents"], + } + else: + rendered = None + + return rendered + class Received(Sensor): SID = Sensor.SID_RECEIVED STALE_TIME = 5 @@ -430,6 +476,22 @@ class Received(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + topic = self.name() + rendered = { + f"{topic}/name": "Received", + f"{topic}/icon": "arrow-down-bold-hexagon-outline", + f"{topic}/by": mqtt_desthash(self.data["by"]), + f"{topic}/via": mqtt_desthash(self.data["via"]), + f"{topic}/distance/geodesic": self.data["distance"]["geodesic"], + f"{topic}/distance/euclidian": self.data["distance"]["euclidian"], + } + else: + rendered = None + + return rendered + class Battery(Sensor): SID = Sensor.SID_BATTERY STALE_TIME = 10 @@ -555,6 +617,22 @@ class Battery(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render() + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/percent": r["values"]["percent"], + f"{topic}/temperature": r["values"]["temperature"], + f"{topic}/meta": r["values"]["_meta"], + } + else: + rendered = None + + return rendered + class Pressure(Sensor): SID = Sensor.SID_PRESSURE STALE_TIME = 5 @@ -621,6 +699,20 @@ class Pressure(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render() + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/mbar": r["values"]["mbar"], + } + else: + rendered = None + + return rendered + class Location(Sensor): SID = Sensor.SID_LOCATION @@ -876,6 +968,45 @@ class Location(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/latitude": r["values"]["latitude"], + f"{topic}/longitude": r["values"]["longitude"], + f"{topic}/altitude": r["values"]["altitude"], + f"{topic}/speed": r["values"]["speed"], + f"{topic}/heading": r["values"]["heading"], + f"{topic}/accuracy": r["values"]["accuracy"], + f"{topic}/updated": r["values"]["updated"], + f"{topic}/angle_to_horizon": r["values"]["angle_to_horizon"], + f"{topic}/radio_horizon": r["values"]["radio_horizon"]} + if "distance" in r: + rendered[f"{topic}/distance/euclidian"] = r["distance"]["euclidian"] + rendered[f"{topic}/distance/orthodromic"] = r["distance"]["orthodromic"] + rendered[f"{topic}/distance/vertical"] = r["distance"]["vertical"] + if "azalt" in r: + rendered[f"{topic}/azalt/azimuth"] = r["azalt"]["azimuth"] + rendered[f"{topic}/azalt/altitude"] = r["azalt"]["altitude"] + rendered[f"{topic}/azalt/above_horizon"] = r["azalt"]["above_horizon"] + rendered[f"{topic}/azalt/altitude_delta"] = r["azalt"]["altitude_delta"] + rendered[f"{topic}/azalt/local_angle_to_horizon"] = r["azalt"]["local_angle_to_horizon"] + if "radio_horizon" in r: + rendered[f"{topic}/radio_horizon/object_range"] = r["radio_horizon"]["object_range"] + rendered[f"{topic}/radio_horizon/related_range"] = r["radio_horizon"]["related_range"] + rendered[f"{topic}/radio_horizon/combined_range"] = r["radio_horizon"]["combined_range"] + rendered[f"{topic}/radio_horizon/within_range"] = r["radio_horizon"]["within_range"] + rendered[f"{topic}/radio_horizon/geodesic_distance"] = r["radio_horizon"]["geodesic_distance"] + rendered[f"{topic}/radio_horizon/antenna_distance"] = r["radio_horizon"]["antenna_distance"] + + else: + rendered = None + + return rendered + class PhysicalLink(Sensor): SID = Sensor.SID_PHYSICAL_LINK STALE_TIME = 5 @@ -932,6 +1063,22 @@ class PhysicalLink(Sensor): if q > 90: rendered["icon"] = "network-strength-4" return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/rssi": r["values"]["rssi"], + f"{topic}/snr": r["values"]["snr"], + f"{topic}/q": r["values"]["q"], + } + else: + rendered = None + + return rendered + class Temperature(Sensor): SID = Sensor.SID_TEMPERATURE STALE_TIME = 5 @@ -988,6 +1135,20 @@ class Temperature(Sensor): } return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/c": r["values"]["c"], + } + else: + rendered = None + + return rendered + class Humidity(Sensor): SID = Sensor.SID_HUMIDITY STALE_TIME = 5 @@ -1044,6 +1205,20 @@ class Humidity(Sensor): } return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/percent_relative": r["values"]["percent"], + } + else: + rendered = None + + return rendered + class MagneticField(Sensor): SID = Sensor.SID_MAGNETIC_FIELD STALE_TIME = 1 @@ -1101,6 +1276,22 @@ class MagneticField(Sensor): } return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/x": r["values"]["x"], + f"{topic}/y": r["values"]["y"], + f"{topic}/z": r["values"]["z"], + } + else: + rendered = None + + return rendered + class AmbientLight(Sensor): SID = Sensor.SID_AMBIENT_LIGHT STALE_TIME = 1 @@ -1167,6 +1358,22 @@ class AmbientLight(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/lux": r["values"]["lux"], + } + if "deltas" in r: + rendered[f"{topic}/deltas/lux"] = r["deltas"]["lux"] + else: + rendered = None + + return rendered + class Gravity(Sensor): SID = Sensor.SID_GRAVITY STALE_TIME = 1 @@ -1224,6 +1431,22 @@ class Gravity(Sensor): } return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/x": r["values"]["x"], + f"{topic}/y": r["values"]["y"], + f"{topic}/z": r["values"]["z"], + } + else: + rendered = None + + return rendered + class AngularVelocity(Sensor): SID = Sensor.SID_ANGULAR_VELOCITY STALE_TIME = 1 @@ -1281,6 +1504,22 @@ class AngularVelocity(Sensor): } return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/x": r["values"]["x"], + f"{topic}/y": r["values"]["y"], + f"{topic}/z": r["values"]["z"], + } + else: + rendered = None + + return rendered + class Acceleration(Sensor): SID = Sensor.SID_ACCELERATION STALE_TIME = 1 @@ -1327,6 +1566,33 @@ class Acceleration(Sensor): except: return None + def render(self, relative_to=None): + if self.data == None: + return None + + rendered = { + "icon": "arrow-right-thick", + "name": "Acceleration", + "values": { "x": self.data["x"], "y": self.data["y"], "z": self.data["z"] }, + } + return rendered + + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/x": r["values"]["x"], + f"{topic}/y": r["values"]["y"], + f"{topic}/z": r["values"]["z"], + } + else: + rendered = None + + return rendered + class Proximity(Sensor): SID = Sensor.SID_PROXIMITY STALE_TIME = 1 @@ -1383,6 +1649,20 @@ class Proximity(Sensor): } return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/triggered": r["values"]["triggered"], + } + else: + rendered = None + + return rendered + class PowerConsumption(Sensor): SID = Sensor.SID_POWER_CONSUMPTION STALE_TIME = 5 @@ -1464,6 +1744,22 @@ class PowerConsumption(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for consumer in r["values"]: + rendered[f"{topic}/{consumer["label"]}/w"] = consumer["w"] + rendered[f"{topic}/{consumer["label"]}/icon"] = consumer["custom_icon"] + else: + rendered = None + + return rendered + class PowerProduction(Sensor): SID = Sensor.SID_POWER_PRODUCTION STALE_TIME = 5 @@ -1545,6 +1841,22 @@ class PowerProduction(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for producer in r["values"]: + rendered[f"{topic}/{producer["label"]}/w"] = producer["w"] + rendered[f"{topic}/{producer["label"]}/icon"] = producer["custom_icon"] + else: + rendered = None + + return rendered + class Processor(Sensor): SID = Sensor.SID_PROCESSOR STALE_TIME = 5 @@ -1631,6 +1943,25 @@ class Processor(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for cpu in r["values"]: + rendered[f"{topic}/{cpu["label"]}/current_load"] = cpu["current_load"] + rendered[f"{topic}/{cpu["label"]}/avgs/1m"] = cpu["load_avgs"][0] + rendered[f"{topic}/{cpu["label"]}/avgs/5m"] = cpu["load_avgs"][1] + rendered[f"{topic}/{cpu["label"]}/avgs/15m"] = cpu["load_avgs"][2] + rendered[f"{topic}/{cpu["label"]}/clock"] = cpu["clock"] + else: + rendered = None + + return rendered + class RandomAccessMemory(Sensor): SID = Sensor.SID_RAM STALE_TIME = 5 @@ -1718,6 +2049,24 @@ class RandomAccessMemory(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for ram in r["values"]: + rendered[f"{topic}/{ram["label"]}/capacity"] = ram["capacity"] + rendered[f"{topic}/{ram["label"]}/used"] = ram["used"] + rendered[f"{topic}/{ram["label"]}/free"] = ram["free"] + rendered[f"{topic}/{ram["label"]}/percent"] = ram["percent"] + else: + rendered = None + + return rendered + class NonVolatileMemory(Sensor): SID = Sensor.SID_NVM STALE_TIME = 5 @@ -1805,6 +2154,24 @@ class NonVolatileMemory(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for nvm in r["values"]: + rendered[f"{topic}/{nvm["label"]}/capacity"] = nvm["capacity"] + rendered[f"{topic}/{nvm["label"]}/used"] = nvm["used"] + rendered[f"{topic}/{nvm["label"]}/free"] = nvm["free"] + rendered[f"{topic}/{nvm["label"]}/percent"] = nvm["percent"] + else: + rendered = None + + return rendered + class Custom(Sensor): SID = Sensor.SID_CUSTOM STALE_TIME = 5 @@ -1890,6 +2257,21 @@ class Custom(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for custom in r["values"]: + rendered[f"{topic}/{custom["label"]}/value"] = custom["value"] + rendered[f"{topic}/{custom["label"]}/icon"] = custom["custom_icon"] + else: + rendered = None + + return rendered class Tank(Sensor): SID = Sensor.SID_TANK @@ -1984,6 +2366,26 @@ class Tank(Sensor): return rendered + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for tank in r["values"]: + rendered[f"{topic}/{tank["label"]}/unit"] = tank["unit"] + rendered[f"{topic}/{tank["label"]}/capacity"] = tank["capacity"] + rendered[f"{topic}/{tank["label"]}/level"] = tank["level"] + rendered[f"{topic}/{tank["label"]}/free"] = tank["free"] + rendered[f"{topic}/{tank["label"]}/percent"] = tank["percent"] + rendered[f"{topic}/{tank["label"]}/icon"] = tank["custom_icon"] + else: + rendered = None + + return rendered + class Fuel(Sensor): SID = Sensor.SID_FUEL STALE_TIME = 5 @@ -2075,4 +2477,30 @@ class Fuel(Sensor): "values": entries, } - return rendered \ No newline at end of file + return rendered + + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + topic = self.name() + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + for tank in r["values"]: + rendered[f"{topic}/{tank["label"]}/unit"] = tank["unit"] + rendered[f"{topic}/{tank["label"]}/capacity"] = tank["capacity"] + rendered[f"{topic}/{tank["label"]}/level"] = tank["level"] + rendered[f"{topic}/{tank["label"]}/free"] = tank["free"] + rendered[f"{topic}/{tank["label"]}/percent"] = tank["percent"] + rendered[f"{topic}/{tank["label"]}/icon"] = tank["custom_icon"] + else: + rendered = None + + return rendered + +def mqtt_desthash(desthash): + if type(desthash) == bytes: + return RNS.prettyhexrep(desthash) + else: + return None \ No newline at end of file From 9bb4f3cc8b69db2a49b27aa0acf682d5df27dd49 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Jan 2025 22:31:16 +0100 Subject: [PATCH 35/76] Added MQTT library --- sbapp/mqtt/__init__.py | 5 + sbapp/mqtt/client.py | 5004 ++++++++++++++++++++++++++++++++ sbapp/mqtt/enums.py | 113 + sbapp/mqtt/matcher.py | 78 + sbapp/mqtt/packettypes.py | 43 + sbapp/mqtt/properties.py | 421 +++ sbapp/mqtt/publish.py | 306 ++ sbapp/mqtt/py.typed | 0 sbapp/mqtt/reasoncodes.py | 223 ++ sbapp/mqtt/subscribe.py | 281 ++ sbapp/mqtt/subscribeoptions.py | 113 + 11 files changed, 6587 insertions(+) create mode 100644 sbapp/mqtt/__init__.py create mode 100644 sbapp/mqtt/client.py create mode 100644 sbapp/mqtt/enums.py create mode 100644 sbapp/mqtt/matcher.py create mode 100644 sbapp/mqtt/packettypes.py create mode 100644 sbapp/mqtt/properties.py create mode 100644 sbapp/mqtt/publish.py create mode 100644 sbapp/mqtt/py.typed create mode 100644 sbapp/mqtt/reasoncodes.py create mode 100644 sbapp/mqtt/subscribe.py create mode 100644 sbapp/mqtt/subscribeoptions.py diff --git a/sbapp/mqtt/__init__.py b/sbapp/mqtt/__init__.py new file mode 100644 index 0000000..9372c8f --- /dev/null +++ b/sbapp/mqtt/__init__.py @@ -0,0 +1,5 @@ +__version__ = "2.1.1.dev0" + + +class MQTTException(Exception): + pass diff --git a/sbapp/mqtt/client.py b/sbapp/mqtt/client.py new file mode 100644 index 0000000..4ccc869 --- /dev/null +++ b/sbapp/mqtt/client.py @@ -0,0 +1,5004 @@ +# Copyright (c) 2012-2019 Roger Light and others +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Roger Light - initial API and implementation +# Ian Craggs - MQTT V5 support +""" +This is an MQTT client module. MQTT is a lightweight pub/sub messaging +protocol that is easy to implement and suitable for low powered devices. +""" +from __future__ import annotations + +import base64 +import collections +import errno +import hashlib +import logging +import os +import platform +import select +import socket +import string +import struct +import threading +import time +import urllib.parse +import urllib.request +import uuid +import warnings +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, NamedTuple, Sequence, Tuple, Union, cast + +from paho.mqtt.packettypes import PacketTypes + +from .enums import CallbackAPIVersion, ConnackCode, LogLevel, MessageState, MessageType, MQTTErrorCode, MQTTProtocolVersion, PahoClientMode, _ConnectionState +from .matcher import MQTTMatcher +from .properties import Properties +from .reasoncodes import ReasonCode, ReasonCodes +from .subscribeoptions import SubscribeOptions + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + +if TYPE_CHECKING: + try: + from typing import TypedDict # type: ignore + except ImportError: + from typing_extensions import TypedDict + + try: + from typing import Protocol # type: ignore + except ImportError: + from typing_extensions import Protocol # type: ignore + + class _InPacket(TypedDict): + command: int + have_remaining: int + remaining_count: list[int] + remaining_mult: int + remaining_length: int + packet: bytearray + to_process: int + pos: int + + + class _OutPacket(TypedDict): + command: int + mid: int + qos: int + pos: int + to_process: int + packet: bytes + info: MQTTMessageInfo | None + + class SocketLike(Protocol): + def recv(self, buffer_size: int) -> bytes: + ... + def send(self, buffer: bytes) -> int: + ... + def close(self) -> None: + ... + def fileno(self) -> int: + ... + def setblocking(self, flag: bool) -> None: + ... + + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +try: + import socks # type: ignore[import-untyped] +except ImportError: + socks = None # type: ignore[assignment] + + +try: + # Use monotonic clock if available + time_func = time.monotonic +except AttributeError: + time_func = time.time + +try: + import dns.resolver + + HAVE_DNS = True +except ImportError: + HAVE_DNS = False + + +if platform.system() == 'Windows': + EAGAIN = errno.WSAEWOULDBLOCK # type: ignore[attr-defined] +else: + EAGAIN = errno.EAGAIN + +# Avoid linter complain. We kept importing it as ReasonCodes (plural) for compatibility +_ = ReasonCodes + +# Keep copy of enums values for compatibility. +CONNECT = MessageType.CONNECT +CONNACK = MessageType.CONNACK +PUBLISH = MessageType.PUBLISH +PUBACK = MessageType.PUBACK +PUBREC = MessageType.PUBREC +PUBREL = MessageType.PUBREL +PUBCOMP = MessageType.PUBCOMP +SUBSCRIBE = MessageType.SUBSCRIBE +SUBACK = MessageType.SUBACK +UNSUBSCRIBE = MessageType.UNSUBSCRIBE +UNSUBACK = MessageType.UNSUBACK +PINGREQ = MessageType.PINGREQ +PINGRESP = MessageType.PINGRESP +DISCONNECT = MessageType.DISCONNECT +AUTH = MessageType.AUTH + +# Log levels +MQTT_LOG_INFO = LogLevel.MQTT_LOG_INFO +MQTT_LOG_NOTICE = LogLevel.MQTT_LOG_NOTICE +MQTT_LOG_WARNING = LogLevel.MQTT_LOG_WARNING +MQTT_LOG_ERR = LogLevel.MQTT_LOG_ERR +MQTT_LOG_DEBUG = LogLevel.MQTT_LOG_DEBUG +LOGGING_LEVEL = { + LogLevel.MQTT_LOG_DEBUG: logging.DEBUG, + LogLevel.MQTT_LOG_INFO: logging.INFO, + LogLevel.MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level + LogLevel.MQTT_LOG_WARNING: logging.WARNING, + LogLevel.MQTT_LOG_ERR: logging.ERROR, +} + +# CONNACK codes +CONNACK_ACCEPTED = ConnackCode.CONNACK_ACCEPTED +CONNACK_REFUSED_PROTOCOL_VERSION = ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION +CONNACK_REFUSED_IDENTIFIER_REJECTED = ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED +CONNACK_REFUSED_SERVER_UNAVAILABLE = ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE +CONNACK_REFUSED_BAD_USERNAME_PASSWORD = ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD +CONNACK_REFUSED_NOT_AUTHORIZED = ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED + +# Message state +mqtt_ms_invalid = MessageState.MQTT_MS_INVALID +mqtt_ms_publish = MessageState.MQTT_MS_PUBLISH +mqtt_ms_wait_for_puback = MessageState.MQTT_MS_WAIT_FOR_PUBACK +mqtt_ms_wait_for_pubrec = MessageState.MQTT_MS_WAIT_FOR_PUBREC +mqtt_ms_resend_pubrel = MessageState.MQTT_MS_RESEND_PUBREL +mqtt_ms_wait_for_pubrel = MessageState.MQTT_MS_WAIT_FOR_PUBREL +mqtt_ms_resend_pubcomp = MessageState.MQTT_MS_RESEND_PUBCOMP +mqtt_ms_wait_for_pubcomp = MessageState.MQTT_MS_WAIT_FOR_PUBCOMP +mqtt_ms_send_pubrec = MessageState.MQTT_MS_SEND_PUBREC +mqtt_ms_queued = MessageState.MQTT_MS_QUEUED + +MQTT_ERR_AGAIN = MQTTErrorCode.MQTT_ERR_AGAIN +MQTT_ERR_SUCCESS = MQTTErrorCode.MQTT_ERR_SUCCESS +MQTT_ERR_NOMEM = MQTTErrorCode.MQTT_ERR_NOMEM +MQTT_ERR_PROTOCOL = MQTTErrorCode.MQTT_ERR_PROTOCOL +MQTT_ERR_INVAL = MQTTErrorCode.MQTT_ERR_INVAL +MQTT_ERR_NO_CONN = MQTTErrorCode.MQTT_ERR_NO_CONN +MQTT_ERR_CONN_REFUSED = MQTTErrorCode.MQTT_ERR_CONN_REFUSED +MQTT_ERR_NOT_FOUND = MQTTErrorCode.MQTT_ERR_NOT_FOUND +MQTT_ERR_CONN_LOST = MQTTErrorCode.MQTT_ERR_CONN_LOST +MQTT_ERR_TLS = MQTTErrorCode.MQTT_ERR_TLS +MQTT_ERR_PAYLOAD_SIZE = MQTTErrorCode.MQTT_ERR_PAYLOAD_SIZE +MQTT_ERR_NOT_SUPPORTED = MQTTErrorCode.MQTT_ERR_NOT_SUPPORTED +MQTT_ERR_AUTH = MQTTErrorCode.MQTT_ERR_AUTH +MQTT_ERR_ACL_DENIED = MQTTErrorCode.MQTT_ERR_ACL_DENIED +MQTT_ERR_UNKNOWN = MQTTErrorCode.MQTT_ERR_UNKNOWN +MQTT_ERR_ERRNO = MQTTErrorCode.MQTT_ERR_ERRNO +MQTT_ERR_QUEUE_SIZE = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE +MQTT_ERR_KEEPALIVE = MQTTErrorCode.MQTT_ERR_KEEPALIVE + +MQTTv31 = MQTTProtocolVersion.MQTTv31 +MQTTv311 = MQTTProtocolVersion.MQTTv311 +MQTTv5 = MQTTProtocolVersion.MQTTv5 + +MQTT_CLIENT = PahoClientMode.MQTT_CLIENT +MQTT_BRIDGE = PahoClientMode.MQTT_BRIDGE + +# For MQTT V5, use the clean start flag only on the first successful connect +MQTT_CLEAN_START_FIRST_ONLY: CleanStartOption = 3 + +sockpair_data = b"0" + +# Payload support all those type and will be converted to bytes: +# * str are utf8 encoded +# * int/float are converted to string and utf8 encoded (e.g. 1 is converted to b"1") +# * None is converted to a zero-length payload (i.e. b"") +PayloadType = Union[str, bytes, bytearray, int, float, None] + +HTTPHeader = Dict[str, str] +WebSocketHeaders = Union[Callable[[HTTPHeader], HTTPHeader], HTTPHeader] + +CleanStartOption = Union[bool, Literal[3]] + + +class ConnectFlags(NamedTuple): + """Contains additional information passed to `on_connect` callback""" + + session_present: bool + """ + this flag is useful for clients that are + using clean session set to False only (MQTTv3) or clean_start = False (MQTTv5). + In that case, if client that reconnects to a broker that it has previously + connected to, this flag indicates whether the broker still has the + session information for the client. If true, the session still exists. + """ + + +class DisconnectFlags(NamedTuple): + """Contains additional information passed to `on_disconnect` callback""" + + is_disconnect_packet_from_server: bool + """ + tells whether this on_disconnect call is the result + of receiving an DISCONNECT packet from the broker or if the on_disconnect is only + generated by the client library. + When true, the reason code is generated by the broker. + """ + + +CallbackOnConnect_v1_mqtt3 = Callable[["Client", Any, Dict[str, Any], MQTTErrorCode], None] +CallbackOnConnect_v1_mqtt5 = Callable[["Client", Any, Dict[str, Any], ReasonCode, Union[Properties, None]], None] +CallbackOnConnect_v1 = Union[CallbackOnConnect_v1_mqtt5, CallbackOnConnect_v1_mqtt3] +CallbackOnConnect_v2 = Callable[["Client", Any, ConnectFlags, ReasonCode, Union[Properties, None]], None] +CallbackOnConnect = Union[CallbackOnConnect_v1, CallbackOnConnect_v2] +CallbackOnConnectFail = Callable[["Client", Any], None] +CallbackOnDisconnect_v1_mqtt3 = Callable[["Client", Any, MQTTErrorCode], None] +CallbackOnDisconnect_v1_mqtt5 = Callable[["Client", Any, Union[ReasonCode, int, None], Union[Properties, None]], None] +CallbackOnDisconnect_v1 = Union[CallbackOnDisconnect_v1_mqtt3, CallbackOnDisconnect_v1_mqtt5] +CallbackOnDisconnect_v2 = Callable[["Client", Any, DisconnectFlags, ReasonCode, Union[Properties, None]], None] +CallbackOnDisconnect = Union[CallbackOnDisconnect_v1, CallbackOnDisconnect_v2] +CallbackOnLog = Callable[["Client", Any, int, str], None] +CallbackOnMessage = Callable[["Client", Any, "MQTTMessage"], None] +CallbackOnPreConnect = Callable[["Client", Any], None] +CallbackOnPublish_v1 = Callable[["Client", Any, int], None] +CallbackOnPublish_v2 = Callable[["Client", Any, int, ReasonCode, Properties], None] +CallbackOnPublish = Union[CallbackOnPublish_v1, CallbackOnPublish_v2] +CallbackOnSocket = Callable[["Client", Any, "SocketLike"], None] +CallbackOnSubscribe_v1_mqtt3 = Callable[["Client", Any, int, Tuple[int, ...]], None] +CallbackOnSubscribe_v1_mqtt5 = Callable[["Client", Any, int, List[ReasonCode], Properties], None] +CallbackOnSubscribe_v1 = Union[CallbackOnSubscribe_v1_mqtt3, CallbackOnSubscribe_v1_mqtt5] +CallbackOnSubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None] +CallbackOnSubscribe = Union[CallbackOnSubscribe_v1, CallbackOnSubscribe_v2] +CallbackOnUnsubscribe_v1_mqtt3 = Callable[["Client", Any, int], None] +CallbackOnUnsubscribe_v1_mqtt5 = Callable[["Client", Any, int, Properties, Union[ReasonCode, List[ReasonCode]]], None] +CallbackOnUnsubscribe_v1 = Union[CallbackOnUnsubscribe_v1_mqtt3, CallbackOnUnsubscribe_v1_mqtt5] +CallbackOnUnsubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None] +CallbackOnUnsubscribe = Union[CallbackOnUnsubscribe_v1, CallbackOnUnsubscribe_v2] + +# This is needed for typing because class Client redefined the name "socket" +_socket = socket + + +class WebsocketConnectionError(ConnectionError): + """ WebsocketConnectionError is a subclass of ConnectionError. + + It's raised when unable to perform the Websocket handshake. + """ + pass + + +def error_string(mqtt_errno: MQTTErrorCode | int) -> str: + """Return the error string associated with an mqtt error number.""" + if mqtt_errno == MQTT_ERR_SUCCESS: + return "No error." + elif mqtt_errno == MQTT_ERR_NOMEM: + return "Out of memory." + elif mqtt_errno == MQTT_ERR_PROTOCOL: + return "A network protocol error occurred when communicating with the broker." + elif mqtt_errno == MQTT_ERR_INVAL: + return "Invalid function arguments provided." + elif mqtt_errno == MQTT_ERR_NO_CONN: + return "The client is not currently connected." + elif mqtt_errno == MQTT_ERR_CONN_REFUSED: + return "The connection was refused." + elif mqtt_errno == MQTT_ERR_NOT_FOUND: + return "Message not found (internal error)." + elif mqtt_errno == MQTT_ERR_CONN_LOST: + return "The connection was lost." + elif mqtt_errno == MQTT_ERR_TLS: + return "A TLS error occurred." + elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE: + return "Payload too large." + elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED: + return "This feature is not supported." + elif mqtt_errno == MQTT_ERR_AUTH: + return "Authorisation failed." + elif mqtt_errno == MQTT_ERR_ACL_DENIED: + return "Access denied by ACL." + elif mqtt_errno == MQTT_ERR_UNKNOWN: + return "Unknown error." + elif mqtt_errno == MQTT_ERR_ERRNO: + return "Error defined by errno." + elif mqtt_errno == MQTT_ERR_QUEUE_SIZE: + return "Message queue full." + elif mqtt_errno == MQTT_ERR_KEEPALIVE: + return "Client or broker did not communicate in the keepalive interval." + else: + return "Unknown error." + + +def connack_string(connack_code: int|ReasonCode) -> str: + """Return the string associated with a CONNACK result or CONNACK reason code.""" + if isinstance(connack_code, ReasonCode): + return str(connack_code) + + if connack_code == CONNACK_ACCEPTED: + return "Connection Accepted." + elif connack_code == CONNACK_REFUSED_PROTOCOL_VERSION: + return "Connection Refused: unacceptable protocol version." + elif connack_code == CONNACK_REFUSED_IDENTIFIER_REJECTED: + return "Connection Refused: identifier rejected." + elif connack_code == CONNACK_REFUSED_SERVER_UNAVAILABLE: + return "Connection Refused: broker unavailable." + elif connack_code == CONNACK_REFUSED_BAD_USERNAME_PASSWORD: + return "Connection Refused: bad user name or password." + elif connack_code == CONNACK_REFUSED_NOT_AUTHORIZED: + return "Connection Refused: not authorised." + else: + return "Connection Refused: unknown reason." + + +def convert_connack_rc_to_reason_code(connack_code: ConnackCode) -> ReasonCode: + """Convert a MQTTv3 / MQTTv3.1.1 connack result to `ReasonCode`. + + This is used in `on_connect` callback to have a consistent API. + + Be careful that the numeric value isn't the same, for example: + + >>> ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE == 3 + >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == 136 + + It's recommended to compare by names + + >>> code_to_test = ReasonCode(PacketTypes.CONNACK, "Server unavailable") + >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == code_to_test + """ + if connack_code == ConnackCode.CONNACK_ACCEPTED: + return ReasonCode(PacketTypes.CONNACK, "Success") + if connack_code == ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION: + return ReasonCode(PacketTypes.CONNACK, "Unsupported protocol version") + if connack_code == ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED: + return ReasonCode(PacketTypes.CONNACK, "Client identifier not valid") + if connack_code == ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE: + return ReasonCode(PacketTypes.CONNACK, "Server unavailable") + if connack_code == ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD: + return ReasonCode(PacketTypes.CONNACK, "Bad user name or password") + if connack_code == ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED: + return ReasonCode(PacketTypes.CONNACK, "Not authorized") + + return ReasonCode(PacketTypes.CONNACK, "Unspecified error") + + +def convert_disconnect_error_code_to_reason_code(rc: MQTTErrorCode) -> ReasonCode: + """Convert an MQTTErrorCode to Reason code. + + This is used in `on_disconnect` callback to have a consistent API. + + Be careful that the numeric value isn't the same, for example: + + >>> MQTTErrorCode.MQTT_ERR_PROTOCOL == 2 + >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == 130 + + It's recommended to compare by names + + >>> code_to_test = ReasonCode(PacketTypes.DISCONNECT, "Protocol error") + >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == code_to_test + """ + if rc == MQTTErrorCode.MQTT_ERR_SUCCESS: + return ReasonCode(PacketTypes.DISCONNECT, "Success") + if rc == MQTTErrorCode.MQTT_ERR_KEEPALIVE: + return ReasonCode(PacketTypes.DISCONNECT, "Keep alive timeout") + if rc == MQTTErrorCode.MQTT_ERR_CONN_LOST: + return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error") + return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error") + + +def _base62( + num: int, + base: str = string.digits + string.ascii_letters, + padding: int = 1, +) -> str: + """Convert a number to base-62 representation.""" + if num < 0: + raise ValueError("Number must be positive or zero") + digits = [] + while num: + num, rest = divmod(num, 62) + digits.append(base[rest]) + digits.extend(base[0] for _ in range(len(digits), padding)) + return ''.join(reversed(digits)) + + +def topic_matches_sub(sub: str, topic: str) -> bool: + """Check whether a topic matches a subscription. + + For example: + + * Topic "foo/bar" would match the subscription "foo/#" or "+/bar" + * Topic "non/matching" would not match the subscription "non/+/+" + """ + matcher = MQTTMatcher() + matcher[sub] = True + try: + next(matcher.iter_match(topic)) + return True + except StopIteration: + return False + + +def _socketpair_compat() -> tuple[socket.socket, socket.socket]: + """TCP/IP socketpair including Windows support""" + listensock = socket.socket( + socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) + listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listensock.bind(("127.0.0.1", 0)) + listensock.listen(1) + + iface, port = listensock.getsockname() + sock1 = socket.socket( + socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) + sock1.setblocking(False) + try: + sock1.connect(("127.0.0.1", port)) + except BlockingIOError: + pass + sock2, address = listensock.accept() + sock2.setblocking(False) + listensock.close() + return (sock1, sock2) + + +def _force_bytes(s: str | bytes) -> bytes: + if isinstance(s, str): + return s.encode("utf-8") + return s + + +def _encode_payload(payload: str | bytes | bytearray | int | float | None) -> bytes|bytearray: + if isinstance(payload, str): + return payload.encode("utf-8") + + if isinstance(payload, (int, float)): + return str(payload).encode("ascii") + + if payload is None: + return b"" + + if not isinstance(payload, (bytes, bytearray)): + raise TypeError( + "payload must be a string, bytearray, int, float or None." + ) + + return payload + + +class MQTTMessageInfo: + """This is a class returned from `Client.publish()` and can be used to find + out the mid of the message that was published, and to determine whether the + message has been published, and/or wait until it is published. + """ + + __slots__ = 'mid', '_published', '_condition', 'rc', '_iterpos' + + def __init__(self, mid: int): + self.mid = mid + """ The message Id (int)""" + self._published = False + self._condition = threading.Condition() + self.rc: MQTTErrorCode = MQTTErrorCode.MQTT_ERR_SUCCESS + """ The `MQTTErrorCode` that give status for this message. + This value could change until the message `is_published`""" + self._iterpos = 0 + + def __str__(self) -> str: + return str((self.rc, self.mid)) + + def __iter__(self) -> Iterator[MQTTErrorCode | int]: + self._iterpos = 0 + return self + + def __next__(self) -> MQTTErrorCode | int: + return self.next() + + def next(self) -> MQTTErrorCode | int: + if self._iterpos == 0: + self._iterpos = 1 + return self.rc + elif self._iterpos == 1: + self._iterpos = 2 + return self.mid + else: + raise StopIteration + + def __getitem__(self, index: int) -> MQTTErrorCode | int: + if index == 0: + return self.rc + elif index == 1: + return self.mid + else: + raise IndexError("index out of range") + + def _set_as_published(self) -> None: + with self._condition: + self._published = True + self._condition.notify() + + def wait_for_publish(self, timeout: float | None = None) -> None: + """Block until the message associated with this object is published, or + until the timeout occurs. If timeout is None, this will never time out. + Set timeout to a positive number of seconds, e.g. 1.2, to enable the + timeout. + + :raises ValueError: if the message was not queued due to the outgoing + queue being full. + + :raises RuntimeError: if the message was not published for another + reason. + """ + if self.rc == MQTT_ERR_QUEUE_SIZE: + raise ValueError('Message is not queued due to ERR_QUEUE_SIZE') + elif self.rc == MQTT_ERR_AGAIN: + pass + elif self.rc > 0: + raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') + + timeout_time = None if timeout is None else time_func() + timeout + timeout_tenth = None if timeout is None else timeout / 10. + def timed_out() -> bool: + return False if timeout_time is None else time_func() > timeout_time + + with self._condition: + while not self._published and not timed_out(): + self._condition.wait(timeout_tenth) + + if self.rc > 0: + raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') + + def is_published(self) -> bool: + """Returns True if the message associated with this object has been + published, else returns False. + + To wait for this to become true, look at `wait_for_publish`. + """ + if self.rc == MQTTErrorCode.MQTT_ERR_QUEUE_SIZE: + raise ValueError('Message is not queued due to ERR_QUEUE_SIZE') + elif self.rc == MQTTErrorCode.MQTT_ERR_AGAIN: + pass + elif self.rc > 0: + raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') + + with self._condition: + return self._published + + +class MQTTMessage: + """ This is a class that describes an incoming message. It is + passed to the `on_message` callback as the message parameter. + """ + __slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info', 'properties' + + def __init__(self, mid: int = 0, topic: bytes = b""): + self.timestamp = 0.0 + self.state = mqtt_ms_invalid + self.dup = False + self.mid = mid + """ The message id (int).""" + self._topic = topic + self.payload = b"" + """the message payload (bytes)""" + self.qos = 0 + """ The message Quality of Service (0, 1 or 2).""" + self.retain = False + """ If true, the message is a retained message and not fresh.""" + self.info = MQTTMessageInfo(mid) + self.properties: Properties | None = None + """ In MQTT v5.0, the properties associated with the message. (`Properties`)""" + + def __eq__(self, other: object) -> bool: + """Override the default Equals behavior""" + if isinstance(other, self.__class__): + return self.mid == other.mid + return False + + def __ne__(self, other: object) -> bool: + """Define a non-equality test""" + return not self.__eq__(other) + + @property + def topic(self) -> str: + """topic that the message was published on. + + This property is read-only. + """ + return self._topic.decode('utf-8') + + @topic.setter + def topic(self, value: bytes) -> None: + self._topic = value + + +class Client: + """MQTT version 3.1/3.1.1/5.0 client class. + + This is the main class for use communicating with an MQTT broker. + + General usage flow: + + * Use `connect()`, `connect_async()` or `connect_srv()` to connect to a broker + * Use `loop_start()` to set a thread running to call `loop()` for you. + * Or use `loop_forever()` to handle calling `loop()` for you in a blocking function. + * Or call `loop()` frequently to maintain network traffic flow with the broker + * Use `subscribe()` to subscribe to a topic and receive messages + * Use `publish()` to send messages + * Use `disconnect()` to disconnect from the broker + + Data returned from the broker is made available with the use of callback + functions as described below. + + :param CallbackAPIVersion callback_api_version: define the API version for user-callback (on_connect, on_publish,...). + This field is required and it's recommended to use the latest version (CallbackAPIVersion.API_VERSION2). + See each callback for description of API for each version. The file docs/migrations.rst contains details on + how to migrate between version. + + :param str client_id: the unique client id string used when connecting to the + broker. If client_id is zero length or None, then the behaviour is + defined by which protocol version is in use. If using MQTT v3.1.1, then + a zero length client id will be sent to the broker and the broker will + generate a random for the client. If using MQTT v3.1 then an id will be + randomly generated. In both cases, clean_session must be True. If this + is not the case a ValueError will be raised. + + :param bool clean_session: a boolean that determines the client type. If True, + the broker will remove all information about this client when it + disconnects. If False, the client is a persistent client and + subscription information and queued messages will be retained when the + client disconnects. + Note that a client will never discard its own outgoing messages on + disconnect. Calling connect() or reconnect() will cause the messages to + be resent. Use reinitialise() to reset a client to its original state. + The clean_session argument only applies to MQTT versions v3.1.1 and v3.1. + It is not accepted if the MQTT version is v5.0 - use the clean_start + argument on connect() instead. + + :param userdata: user defined data of any type that is passed as the "userdata" + parameter to callbacks. It may be updated at a later point with the + user_data_set() function. + + :param int protocol: allows explicit setting of the MQTT version to + use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1), + paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0), + with the default being v3.1.1. + + :param transport: use "websockets" to use WebSockets as the transport + mechanism. Set to "tcp" to use raw TCP, which is the default. + Use "unix" to use Unix sockets as the transport mechanism; note that + this option is only available on platforms that support Unix sockets, + and the "host" argument is interpreted as the path to the Unix socket + file in this case. + + :param bool manual_ack: normally, when a message is received, the library automatically + acknowledges after on_message callback returns. manual_ack=True allows the application to + acknowledge receipt after it has completed processing of a message + using a the ack() method. This addresses vulnerability to message loss + if applications fails while processing a message, or while it pending + locally. + + Callbacks + ========= + + A number of callback functions are available to receive data back from the + broker. To use a callback, define a function and then assign it to the + client:: + + def on_connect(client, userdata, flags, reason_code, properties): + print(f"Connected with result code {reason_code}") + + client.on_connect = on_connect + + Callbacks can also be attached using decorators:: + + mqttc = paho.mqtt.Client() + + @mqttc.connect_callback() + def on_connect(client, userdata, flags, reason_code, properties): + print(f"Connected with result code {reason_code}") + + All of the callbacks as described below have a "client" and an "userdata" + argument. "client" is the `Client` instance that is calling the callback. + userdata" is user data of any type and can be set when creating a new client + instance or with `user_data_set()`. + + If you wish to suppress exceptions within a callback, you should set + ``mqttc.suppress_exceptions = True`` + + The callbacks are listed below, documentation for each of them can be found + at the same function name: + + `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`, + `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`, + `on_socket_register_write`, `on_socket_unregister_write` + """ + + def __init__( + self, + callback_api_version: CallbackAPIVersion = CallbackAPIVersion.VERSION1, + client_id: str | None = "", + clean_session: bool | None = None, + userdata: Any = None, + protocol: MQTTProtocolVersion = MQTTv311, + transport: Literal["tcp", "websockets", "unix"] = "tcp", + reconnect_on_failure: bool = True, + manual_ack: bool = False, + ) -> None: + transport = transport.lower() # type: ignore + if transport == "unix" and not hasattr(socket, "AF_UNIX"): + raise ValueError('"unix" transport not supported') + elif transport not in ("websockets", "tcp", "unix"): + raise ValueError( + f'transport must be "websockets", "tcp" or "unix", not {transport}') + + self._manual_ack = manual_ack + self._transport = transport + self._protocol = protocol + self._userdata = userdata + self._sock: SocketLike | None = None + self._sockpairR: socket.socket | None = None + self._sockpairW: socket.socket | None = None + self._keepalive = 60 + self._connect_timeout = 5.0 + self._client_mode = MQTT_CLIENT + self._callback_api_version = callback_api_version + + if self._callback_api_version == CallbackAPIVersion.VERSION1: + warnings.warn( + "Callback API version 1 is deprecated, update to latest version", + category=DeprecationWarning, + stacklevel=2, + ) + if isinstance(self._callback_api_version, str): + # Help user to migrate, it probably provided a client id + # as first arguments + raise ValueError( + "Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details" + ) + if self._callback_api_version not in CallbackAPIVersion: + raise ValueError("Unsupported callback API version") + + self._clean_start: int = MQTT_CLEAN_START_FIRST_ONLY + + if protocol == MQTTv5: + if clean_session is not None: + raise ValueError('Clean session is not used for MQTT 5.0') + else: + if clean_session is None: + clean_session = True + if not clean_session and (client_id == "" or client_id is None): + raise ValueError( + 'A client id must be provided if clean session is False.') + self._clean_session = clean_session + + # [MQTT-3.1.3-4] Client Id must be UTF-8 encoded string. + if client_id == "" or client_id is None: + if protocol == MQTTv31: + self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8") + else: + self._client_id = b"" + else: + self._client_id = _force_bytes(client_id) + + self._username: bytes | None = None + self._password: bytes | None = None + self._in_packet: _InPacket = { + "command": 0, + "have_remaining": 0, + "remaining_count": [], + "remaining_mult": 1, + "remaining_length": 0, + "packet": bytearray(b""), + "to_process": 0, + "pos": 0, + } + self._out_packet: collections.deque[_OutPacket] = collections.deque() + self._last_msg_in = time_func() + self._last_msg_out = time_func() + self._reconnect_min_delay = 1 + self._reconnect_max_delay = 120 + self._reconnect_delay: int | None = None + self._reconnect_on_failure = reconnect_on_failure + self._ping_t = 0.0 + self._last_mid = 0 + self._state = _ConnectionState.MQTT_CS_NEW + self._out_messages: collections.OrderedDict[ + int, MQTTMessage + ] = collections.OrderedDict() + self._in_messages: collections.OrderedDict[ + int, MQTTMessage + ] = collections.OrderedDict() + self._max_inflight_messages = 20 + self._inflight_messages = 0 + self._max_queued_messages = 0 + self._connect_properties: Properties | None = None + self._will_properties: Properties | None = None + self._will = False + self._will_topic = b"" + self._will_payload = b"" + self._will_qos = 0 + self._will_retain = False + self._on_message_filtered = MQTTMatcher() + self._host = "" + self._port = 1883 + self._bind_address = "" + self._bind_port = 0 + self._proxy: Any = {} + self._in_callback_mutex = threading.Lock() + self._callback_mutex = threading.RLock() + self._msgtime_mutex = threading.Lock() + self._out_message_mutex = threading.RLock() + self._in_message_mutex = threading.Lock() + self._reconnect_delay_mutex = threading.Lock() + self._mid_generate_mutex = threading.Lock() + self._thread: threading.Thread | None = None + self._thread_terminate = False + self._ssl = False + self._ssl_context: ssl.SSLContext | None = None + # Only used when SSL context does not have check_hostname attribute + self._tls_insecure = False + self._logger: logging.Logger | None = None + self._registered_write = False + # No default callbacks + self._on_log: CallbackOnLog | None = None + self._on_pre_connect: CallbackOnPreConnect | None = None + self._on_connect: CallbackOnConnect | None = None + self._on_connect_fail: CallbackOnConnectFail | None = None + self._on_subscribe: CallbackOnSubscribe | None = None + self._on_message: CallbackOnMessage | None = None + self._on_publish: CallbackOnPublish | None = None + self._on_unsubscribe: CallbackOnUnsubscribe | None = None + self._on_disconnect: CallbackOnDisconnect | None = None + self._on_socket_open: CallbackOnSocket | None = None + self._on_socket_close: CallbackOnSocket | None = None + self._on_socket_register_write: CallbackOnSocket | None = None + self._on_socket_unregister_write: CallbackOnSocket | None = None + self._websocket_path = "/mqtt" + self._websocket_extra_headers: WebSocketHeaders | None = None + # for clean_start == MQTT_CLEAN_START_FIRST_ONLY + self._mqttv5_first_connect = True + self.suppress_exceptions = False # For callbacks + + def __del__(self) -> None: + self._reset_sockets() + + @property + def host(self) -> str: + """ + Host to connect to. If `connect()` hasn't been called yet, returns an empty string. + + This property may not be changed if the connection is already open. + """ + return self._host + + @host.setter + def host(self, value: str) -> None: + if not self._connection_closed(): + raise RuntimeError("updating host on established connection is not supported") + + if not value: + raise ValueError("Invalid host.") + self._host = value + + @property + def port(self) -> int: + """ + Broker TCP port to connect to. + + This property may not be changed if the connection is already open. + """ + return self._port + + @port.setter + def port(self, value: int) -> None: + if not self._connection_closed(): + raise RuntimeError("updating port on established connection is not supported") + + if value <= 0: + raise ValueError("Invalid port number.") + self._port = value + + @property + def keepalive(self) -> int: + """ + Client keepalive interval (in seconds). + + This property may not be changed if the connection is already open. + """ + return self._keepalive + + @keepalive.setter + def keepalive(self, value: int) -> None: + if not self._connection_closed(): + # The issue here is that the previous value of keepalive matter to possibly + # sent ping packet. + raise RuntimeError("updating keepalive on established connection is not supported") + + if value < 0: + raise ValueError("Keepalive must be >=0.") + + self._keepalive = value + + @property + def transport(self) -> Literal["tcp", "websockets", "unix"]: + """ + Transport method used for the connection ("tcp" or "websockets"). + + This property may not be changed if the connection is already open. + """ + return self._transport + + @transport.setter + def transport(self, value: Literal["tcp", "websockets"]) -> None: + if not self._connection_closed(): + raise RuntimeError("updating transport on established connection is not supported") + + self._transport = value + + @property + def protocol(self) -> MQTTProtocolVersion: + """ + Protocol version used (MQTT v3, MQTT v3.11, MQTTv5) + + This property is read-only. + """ + return self._protocol + + @property + def connect_timeout(self) -> float: + """ + Connection establishment timeout in seconds. + + This property may not be changed if the connection is already open. + """ + return self._connect_timeout + + @connect_timeout.setter + def connect_timeout(self, value: float) -> None: + if not self._connection_closed(): + raise RuntimeError("updating connect_timeout on established connection is not supported") + + if value <= 0.0: + raise ValueError("timeout must be a positive number") + + self._connect_timeout = value + + @property + def username(self) -> str | None: + """The username used to connect to the MQTT broker, or None if no username is used. + + This property may not be changed if the connection is already open. + """ + if self._username is None: + return None + return self._username.decode("utf-8") + + @username.setter + def username(self, value: str | None) -> None: + if not self._connection_closed(): + raise RuntimeError("updating username on established connection is not supported") + + if value is None: + self._username = None + else: + self._username = value.encode("utf-8") + + @property + def password(self) -> str | None: + """The password used to connect to the MQTT broker, or None if no password is used. + + This property may not be changed if the connection is already open. + """ + if self._password is None: + return None + return self._password.decode("utf-8") + + @password.setter + def password(self, value: str | None) -> None: + if not self._connection_closed(): + raise RuntimeError("updating password on established connection is not supported") + + if value is None: + self._password = None + else: + self._password = value.encode("utf-8") + + @property + def max_inflight_messages(self) -> int: + """ + Maximum number of messages with QoS > 0 that can be partway through the network flow at once + + This property may not be changed if the connection is already open. + """ + return self._max_inflight_messages + + @max_inflight_messages.setter + def max_inflight_messages(self, value: int) -> None: + if not self._connection_closed(): + # Not tested. Some doubt that everything is okay when max_inflight change between 0 + # and > 0 value because _update_inflight is skipped when _max_inflight_messages == 0 + raise RuntimeError("updating max_inflight_messages on established connection is not supported") + + if value < 0: + raise ValueError("Invalid inflight.") + + self._max_inflight_messages = value + + @property + def max_queued_messages(self) -> int: + """ + Maximum number of message in the outgoing message queue, 0 means unlimited + + This property may not be changed if the connection is already open. + """ + return self._max_queued_messages + + @max_queued_messages.setter + def max_queued_messages(self, value: int) -> None: + if not self._connection_closed(): + # Not tested. + raise RuntimeError("updating max_queued_messages on established connection is not supported") + + if value < 0: + raise ValueError("Invalid queue size.") + + self._max_queued_messages = value + + @property + def will_topic(self) -> str | None: + """ + The topic name a will message is sent to when disconnecting unexpectedly. None if a will shall not be sent. + + This property is read-only. Use `will_set()` to change its value. + """ + if self._will_topic is None: + return None + + return self._will_topic.decode("utf-8") + + @property + def will_payload(self) -> bytes | None: + """ + The payload for the will message that is sent when disconnecting unexpectedly. None if a will shall not be sent. + + This property is read-only. Use `will_set()` to change its value. + """ + return self._will_payload + + @property + def logger(self) -> logging.Logger | None: + return self._logger + + @logger.setter + def logger(self, value: logging.Logger | None) -> None: + self._logger = value + + def _sock_recv(self, bufsize: int) -> bytes: + if self._sock is None: + raise ConnectionError("self._sock is None") + try: + return self._sock.recv(bufsize) + except ssl.SSLWantReadError as err: + raise BlockingIOError() from err + except ssl.SSLWantWriteError as err: + self._call_socket_register_write() + raise BlockingIOError() from err + except AttributeError as err: + self._easy_log( + MQTT_LOG_DEBUG, "socket was None: %s", err) + raise ConnectionError() from err + + def _sock_send(self, buf: bytes) -> int: + if self._sock is None: + raise ConnectionError("self._sock is None") + + try: + return self._sock.send(buf) + except ssl.SSLWantReadError as err: + raise BlockingIOError() from err + except ssl.SSLWantWriteError as err: + self._call_socket_register_write() + raise BlockingIOError() from err + except BlockingIOError as err: + self._call_socket_register_write() + raise BlockingIOError() from err + + def _sock_close(self) -> None: + """Close the connection to the server.""" + if not self._sock: + return + + try: + sock = self._sock + self._sock = None + self._call_socket_unregister_write(sock) + self._call_socket_close(sock) + finally: + # In case a callback fails, still close the socket to avoid leaking the file descriptor. + sock.close() + + def _reset_sockets(self, sockpair_only: bool = False) -> None: + if not sockpair_only: + self._sock_close() + + if self._sockpairR: + self._sockpairR.close() + self._sockpairR = None + if self._sockpairW: + self._sockpairW.close() + self._sockpairW = None + + def reinitialise( + self, + client_id: str = "", + clean_session: bool = True, + userdata: Any = None, + ) -> None: + self._reset_sockets() + + self.__init__(client_id, clean_session, userdata) # type: ignore[misc] + + def ws_set_options( + self, + path: str = "/mqtt", + headers: WebSocketHeaders | None = None, + ) -> None: + """ Set the path and headers for a websocket connection + + :param str path: a string starting with / which should be the endpoint of the + mqtt connection on the remote server + + :param headers: can be either a dict or a callable object. If it is a dict then + the extra items in the dict are added to the websocket headers. If it is + a callable, then the default websocket headers are passed into this + function and the result is used as the new headers. + """ + self._websocket_path = path + + if headers is not None: + if isinstance(headers, dict) or callable(headers): + self._websocket_extra_headers = headers + else: + raise ValueError( + "'headers' option to ws_set_options has to be either a dictionary or callable") + + def tls_set_context( + self, + context: ssl.SSLContext | None = None, + ) -> None: + """Configure network encryption and authentication context. Enables SSL/TLS support. + + :param context: an ssl.SSLContext object. By default this is given by + ``ssl.create_default_context()``, if available. + + Must be called before `connect()`, `connect_async()` or `connect_srv()`.""" + if self._ssl_context is not None: + raise ValueError('SSL/TLS has already been configured.') + + if context is None: + context = ssl.create_default_context() + + self._ssl = True + self._ssl_context = context + + # Ensure _tls_insecure is consistent with check_hostname attribute + if hasattr(context, 'check_hostname'): + self._tls_insecure = not context.check_hostname + + def tls_set( + self, + ca_certs: str | None = None, + certfile: str | None = None, + keyfile: str | None = None, + cert_reqs: ssl.VerifyMode | None = None, + tls_version: int | None = None, + ciphers: str | None = None, + keyfile_password: str | None = None, + alpn_protocols: list[str] | None = None, + ) -> None: + """Configure network encryption and authentication options. Enables SSL/TLS support. + + :param str ca_certs: a string path to the Certificate Authority certificate files + that are to be treated as trusted by this client. If this is the only + option given then the client will operate in a similar manner to a web + browser. That is to say it will require the broker to have a + certificate signed by the Certificate Authorities in ca_certs and will + communicate using TLS v1,2, but will not attempt any form of + authentication. This provides basic network encryption but may not be + sufficient depending on how the broker is configured. + + By default, on Python 2.7.9+ or 3.4+, the default certification + authority of the system is used. On older Python version this parameter + is mandatory. + :param str certfile: PEM encoded client certificate filename. Used with + keyfile for client TLS based authentication. Support for this feature is + broker dependent. Note that if the files in encrypted and needs a password to + decrypt it, then this can be passed using the keyfile_password argument - you + should take precautions to ensure that your password is + not hard coded into your program by loading the password from a file + for example. If you do not provide keyfile_password, the password will + be requested to be typed in at a terminal window. + :param str keyfile: PEM encoded client private keys filename. Used with + certfile for client TLS based authentication. Support for this feature is + broker dependent. Note that if the files in encrypted and needs a password to + decrypt it, then this can be passed using the keyfile_password argument - you + should take precautions to ensure that your password is + not hard coded into your program by loading the password from a file + for example. If you do not provide keyfile_password, the password will + be requested to be typed in at a terminal window. + :param cert_reqs: the certificate requirements that the client imposes + on the broker to be changed. By default this is ssl.CERT_REQUIRED, + which means that the broker must provide a certificate. See the ssl + pydoc for more information on this parameter. + :param tls_version: the version of the SSL/TLS protocol used to be + specified. By default TLS v1.2 is used. Previous versions are allowed + but not recommended due to possible security problems. + :param str ciphers: encryption ciphers that are allowed + for this connection, or None to use the defaults. See the ssl pydoc for + more information. + + Must be called before `connect()`, `connect_async()` or `connect_srv()`.""" + if ssl is None: + raise ValueError('This platform has no SSL/TLS.') + + if not hasattr(ssl, 'SSLContext'): + # Require Python version that has SSL context support in standard library + raise ValueError( + 'Python 2.7.9 and 3.2 are the minimum supported versions for TLS.') + + if ca_certs is None and not hasattr(ssl.SSLContext, 'load_default_certs'): + raise ValueError('ca_certs must not be None.') + + # Create SSLContext object + if tls_version is None: + tls_version = ssl.PROTOCOL_TLSv1_2 + # If the python version supports it, use highest TLS version automatically + if hasattr(ssl, "PROTOCOL_TLS_CLIENT"): + # This also enables CERT_REQUIRED and check_hostname by default. + tls_version = ssl.PROTOCOL_TLS_CLIENT + elif hasattr(ssl, "PROTOCOL_TLS"): + tls_version = ssl.PROTOCOL_TLS + context = ssl.SSLContext(tls_version) + + # Configure context + if ciphers is not None: + context.set_ciphers(ciphers) + + if certfile is not None: + context.load_cert_chain(certfile, keyfile, keyfile_password) + + if cert_reqs == ssl.CERT_NONE and hasattr(context, 'check_hostname'): + context.check_hostname = False + + context.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if ca_certs is not None: + context.load_verify_locations(ca_certs) + else: + context.load_default_certs() + + if alpn_protocols is not None: + if not getattr(ssl, "HAS_ALPN", None): + raise ValueError("SSL library has no support for ALPN") + context.set_alpn_protocols(alpn_protocols) + + self.tls_set_context(context) + + if cert_reqs != ssl.CERT_NONE: + # Default to secure, sets context.check_hostname attribute + # if available + self.tls_insecure_set(False) + else: + # But with ssl.CERT_NONE, we can not check_hostname + self.tls_insecure_set(True) + + def tls_insecure_set(self, value: bool) -> None: + """Configure verification of the server hostname in the server certificate. + + If value is set to true, it is impossible to guarantee that the host + you are connecting to is not impersonating your server. This can be + useful in initial server testing, but makes it possible for a malicious + third party to impersonate your server through DNS spoofing, for + example. + + Do not use this function in a real system. Setting value to true means + there is no point using encryption. + + Must be called before `connect()` and after either `tls_set()` or + `tls_set_context()`.""" + + if self._ssl_context is None: + raise ValueError( + 'Must configure SSL context before using tls_insecure_set.') + + self._tls_insecure = value + + # Ensure check_hostname is consistent with _tls_insecure attribute + if hasattr(self._ssl_context, 'check_hostname'): + # Rely on SSLContext to check host name + # If verify_mode is CERT_NONE then the host name will never be checked + self._ssl_context.check_hostname = not value + + def proxy_set(self, **proxy_args: Any) -> None: + """Configure proxying of MQTT connection. Enables support for SOCKS or + HTTP proxies. + + Proxying is done through the PySocks library. Brief descriptions of the + proxy_args parameters are below; see the PySocks docs for more info. + + (Required) + + :param proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5} + :param proxy_addr: IP address or DNS name of proxy server + + (Optional) + + :param proxy_port: (int) port number of the proxy server. If not provided, + the PySocks package default value will be utilized, which differs by proxy_type. + :param proxy_rdns: boolean indicating whether proxy lookup should be performed + remotely (True, default) or locally (False) + :param proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy + :param proxy_password: password for SOCKS5 proxy + + Example:: + + mqttc.proxy_set(proxy_type=socks.HTTP, proxy_addr='1.2.3.4', proxy_port=4231) + """ + if socks is None: + raise ValueError("PySocks must be installed for proxy support.") + elif not self._proxy_is_valid(proxy_args): + raise ValueError("proxy_type and/or proxy_addr are invalid.") + else: + self._proxy = proxy_args + + def enable_logger(self, logger: logging.Logger | None = None) -> None: + """ + Enables a logger to send log messages to + + :param logging.Logger logger: if specified, that ``logging.Logger`` object will be used, otherwise + one will be created automatically. + + See `disable_logger` to undo this action. + """ + if logger is None: + if self._logger is not None: + # Do not replace existing logger + return + logger = logging.getLogger(__name__) + self.logger = logger + + def disable_logger(self) -> None: + """ + Disable logging using standard python logging package. This has no effect on the `on_log` callback. + """ + self._logger = None + + def connect( + self, + host: str, + port: int = 1883, + keepalive: int = 60, + bind_address: str = "", + bind_port: int = 0, + clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, + properties: Properties | None = None, + ) -> MQTTErrorCode: + """Connect to a remote broker. This is a blocking call that establishes + the underlying connection and transmits a CONNECT packet. + Note that the connection status will not be updated until a CONNACK is received and + processed (this requires a running network loop, see `loop_start`, `loop_forever`, `loop`...). + + :param str host: the hostname or IP address of the remote broker. + :param int port: the network port of the server host to connect to. Defaults to + 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you + are using `tls_set()` the port may need providing. + :param int keepalive: Maximum period in seconds between communications with the + broker. If no other messages are being exchanged, this controls the + rate at which the client will send ping messages to the broker. + :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. + Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, + respectively. MQTT session data (such as outstanding messages and subscriptions) + is cleared on successful connect when the clean_start flag is set. + For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar + result. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the + MQTT connect packet. + """ + + if self._protocol == MQTTv5: + self._mqttv5_first_connect = True + else: + if clean_start != MQTT_CLEAN_START_FIRST_ONLY: + raise ValueError("Clean start only applies to MQTT V5") + if properties: + raise ValueError("Properties only apply to MQTT V5") + + self.connect_async(host, port, keepalive, + bind_address, bind_port, clean_start, properties) + return self.reconnect() + + def connect_srv( + self, + domain: str | None = None, + keepalive: int = 60, + bind_address: str = "", + bind_port: int = 0, + clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, + properties: Properties | None = None, + ) -> MQTTErrorCode: + """Connect to a remote broker. + + :param str domain: the DNS domain to search for SRV records; if None, + try to determine local domain name. + :param keepalive, bind_address, clean_start and properties: see `connect()` + """ + + if HAVE_DNS is False: + raise ValueError( + 'No DNS resolver library found, try "pip install dnspython".') + + if domain is None: + domain = socket.getfqdn() + domain = domain[domain.find('.') + 1:] + + try: + rr = f'_mqtt._tcp.{domain}' + if self._ssl: + # IANA specifies secure-mqtt (not mqtts) for port 8883 + rr = f'_secure-mqtt._tcp.{domain}' + answers = [] + for answer in dns.resolver.query(rr, dns.rdatatype.SRV): + addr = answer.target.to_text()[:-1] + answers.append( + (addr, answer.port, answer.priority, answer.weight)) + except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers) as err: + raise ValueError(f"No answer/NXDOMAIN for SRV in {domain}") from err + + # FIXME: doesn't account for weight + for answer in answers: + host, port, prio, weight = answer + + try: + return self.connect(host, port, keepalive, bind_address, bind_port, clean_start, properties) + except Exception: # noqa: S110 + pass + + raise ValueError("No SRV hosts responded") + + def connect_async( + self, + host: str, + port: int = 1883, + keepalive: int = 60, + bind_address: str = "", + bind_port: int = 0, + clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, + properties: Properties | None = None, + ) -> None: + """Connect to a remote broker asynchronously. This is a non-blocking + connect call that can be used with `loop_start()` to provide very quick + start. + + Any already established connection will be terminated immediately. + + :param str host: the hostname or IP address of the remote broker. + :param int port: the network port of the server host to connect to. Defaults to + 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you + are using `tls_set()` the port may need providing. + :param int keepalive: Maximum period in seconds between communications with the + broker. If no other messages are being exchanged, this controls the + rate at which the client will send ping messages to the broker. + :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. + Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, + respectively. MQTT session data (such as outstanding messages and subscriptions) + is cleared on successful connect when the clean_start flag is set. + For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar + result. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the + MQTT connect packet. + """ + if bind_port < 0: + raise ValueError('Invalid bind port number.') + + # Switch to state NEW to allow update of host, port & co. + self._sock_close() + self._state = _ConnectionState.MQTT_CS_NEW + + self.host = host + self.port = port + self.keepalive = keepalive + self._bind_address = bind_address + self._bind_port = bind_port + self._clean_start = clean_start + self._connect_properties = properties + self._state = _ConnectionState.MQTT_CS_CONNECT_ASYNC + + def reconnect_delay_set(self, min_delay: int = 1, max_delay: int = 120) -> None: + """ Configure the exponential reconnect delay + + When connection is lost, wait initially min_delay seconds and + double this time every attempt. The wait is capped at max_delay. + Once the client is fully connected (e.g. not only TCP socket, but + received a success CONNACK), the wait timer is reset to min_delay. + """ + with self._reconnect_delay_mutex: + self._reconnect_min_delay = min_delay + self._reconnect_max_delay = max_delay + self._reconnect_delay = None + + def reconnect(self) -> MQTTErrorCode: + """Reconnect the client after a disconnect. Can only be called after + connect()/connect_async().""" + if len(self._host) == 0: + raise ValueError('Invalid host.') + if self._port <= 0: + raise ValueError('Invalid port number.') + + self._in_packet = { + "command": 0, + "have_remaining": 0, + "remaining_count": [], + "remaining_mult": 1, + "remaining_length": 0, + "packet": bytearray(b""), + "to_process": 0, + "pos": 0, + } + + self._ping_t = 0.0 + self._state = _ConnectionState.MQTT_CS_CONNECTING + + self._sock_close() + + # Mark all currently outgoing QoS = 0 packets as lost, + # or `wait_for_publish()` could hang forever + for pkt in self._out_packet: + if pkt["command"] & 0xF0 == PUBLISH and pkt["qos"] == 0 and pkt["info"] is not None: + pkt["info"].rc = MQTT_ERR_CONN_LOST + pkt["info"]._set_as_published() + + self._out_packet.clear() + + with self._msgtime_mutex: + self._last_msg_in = time_func() + self._last_msg_out = time_func() + + # Put messages in progress in a valid state. + self._messages_reconnect_reset() + + with self._callback_mutex: + on_pre_connect = self.on_pre_connect + + if on_pre_connect: + try: + on_pre_connect(self, self._userdata) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_pre_connect: %s', err) + if not self.suppress_exceptions: + raise + + self._sock = self._create_socket() + + self._sock.setblocking(False) # type: ignore[attr-defined] + self._registered_write = False + self._call_socket_open(self._sock) + + return self._send_connect(self._keepalive) + + def loop(self, timeout: float = 1.0) -> MQTTErrorCode: + """Process network events. + + It is strongly recommended that you use `loop_start()`, or + `loop_forever()`, or if you are using an external event loop using + `loop_read()`, `loop_write()`, and `loop_misc()`. Using loop() on it's own is + no longer recommended. + + This function must be called regularly to ensure communication with the + broker is carried out. It calls select() on the network socket to wait + for network events. If incoming data is present it will then be + processed. Outgoing commands, from e.g. `publish()`, are normally sent + immediately that their function is called, but this is not always + possible. loop() will also attempt to send any remaining outgoing + messages, which also includes commands that are part of the flow for + messages with QoS>0. + + :param int timeout: The time in seconds to wait for incoming/outgoing network + traffic before timing out and returning. + + Returns MQTT_ERR_SUCCESS on success. + Returns >0 on error. + + A ValueError will be raised if timeout < 0""" + + if self._sockpairR is None or self._sockpairW is None: + self._reset_sockets(sockpair_only=True) + self._sockpairR, self._sockpairW = _socketpair_compat() + + return self._loop(timeout) + + def _loop(self, timeout: float = 1.0) -> MQTTErrorCode: + if timeout < 0.0: + raise ValueError('Invalid timeout.') + + if self.want_write(): + wlist = [self._sock] + else: + wlist = [] + + # used to check if there are any bytes left in the (SSL) socket + pending_bytes = 0 + if hasattr(self._sock, 'pending'): + pending_bytes = self._sock.pending() # type: ignore[union-attr] + + # if bytes are pending do not wait in select + if pending_bytes > 0: + timeout = 0.0 + + # sockpairR is used to break out of select() before the timeout, on a + # call to publish() etc. + if self._sockpairR is None: + rlist = [self._sock] + else: + rlist = [self._sock, self._sockpairR] + + try: + socklist = select.select(rlist, wlist, [], timeout) + except TypeError: + # Socket isn't correct type, in likelihood connection is lost + # ... or we called disconnect(). In that case the socket will + # be closed but some loop (like loop_forever) will continue to + # call _loop(). We still want to break that loop by returning an + # rc != MQTT_ERR_SUCCESS and we don't want state to change from + # mqtt_cs_disconnecting. + if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + return MQTTErrorCode.MQTT_ERR_CONN_LOST + except ValueError: + # Can occur if we just reconnected but rlist/wlist contain a -1 for + # some reason. + if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + return MQTTErrorCode.MQTT_ERR_CONN_LOST + except Exception: + # Note that KeyboardInterrupt, etc. can still terminate since they + # are not derived from Exception + return MQTTErrorCode.MQTT_ERR_UNKNOWN + + if self._sock in socklist[0] or pending_bytes > 0: + rc = self.loop_read() + if rc or self._sock is None: + return rc + + if self._sockpairR and self._sockpairR in socklist[0]: + # Stimulate output write even though we didn't ask for it, because + # at that point the publish or other command wasn't present. + socklist[1].insert(0, self._sock) + # Clear sockpairR - only ever a single byte written. + try: + # Read many bytes at once - this allows up to 10000 calls to + # publish() inbetween calls to loop(). + self._sockpairR.recv(10000) + except BlockingIOError: + pass + + if self._sock in socklist[1]: + rc = self.loop_write() + if rc or self._sock is None: + return rc + + return self.loop_misc() + + def publish( + self, + topic: str, + payload: PayloadType = None, + qos: int = 0, + retain: bool = False, + properties: Properties | None = None, + ) -> MQTTMessageInfo: + """Publish a message on a topic. + + This causes a message to be sent to the broker and subsequently from + the broker to any clients subscribing to matching topics. + + :param str topic: The topic that the message should be published on. + :param payload: The actual message to send. If not given, or set to None a + zero length message will be used. Passing an int or float will result + in the payload being converted to a string representing that number. If + you wish to send a true int/float, use struct.pack() to create the + payload you require. + :param int qos: The quality of service level to use. + :param bool retain: If set to true, the message will be set as the "last known + good"/retained message for the topic. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included. + + Returns a `MQTTMessageInfo` class, which can be used to determine whether + the message has been delivered (using `is_published()`) or to block + waiting for the message to be delivered (`wait_for_publish()`). The + message ID and return code of the publish() call can be found at + :py:attr:`info.mid ` and :py:attr:`info.rc `. + + For backwards compatibility, the `MQTTMessageInfo` class is iterable so + the old construct of ``(rc, mid) = client.publish(...)`` is still valid. + + rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the + client is not currently connected. mid is the message ID for the + publish request. The mid value can be used to track the publish request + by checking against the mid argument in the on_publish() callback if it + is defined. + + :raises ValueError: if topic is None, has zero length or is + invalid (contains a wildcard), except if the MQTT version used is v5.0. + For v5.0, a zero length topic can be used when a Topic Alias has been set. + :raises ValueError: if qos is not one of 0, 1 or 2 + :raises ValueError: if the length of the payload is greater than 268435455 bytes. + """ + if self._protocol != MQTTv5: + if topic is None or len(topic) == 0: + raise ValueError('Invalid topic.') + + topic_bytes = topic.encode('utf-8') + + self._raise_for_invalid_topic(topic_bytes) + + if qos < 0 or qos > 2: + raise ValueError('Invalid QoS level.') + + local_payload = _encode_payload(payload) + + if len(local_payload) > 268435455: + raise ValueError('Payload too large.') + + local_mid = self._mid_generate() + + if qos == 0: + info = MQTTMessageInfo(local_mid) + rc = self._send_publish( + local_mid, topic_bytes, local_payload, qos, retain, False, info, properties) + info.rc = rc + return info + else: + message = MQTTMessage(local_mid, topic_bytes) + message.timestamp = time_func() + message.payload = local_payload + message.qos = qos + message.retain = retain + message.dup = False + message.properties = properties + + with self._out_message_mutex: + if self._max_queued_messages > 0 and len(self._out_messages) >= self._max_queued_messages: + message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE + return message.info + + if local_mid in self._out_messages: + message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE + return message.info + + self._out_messages[message.mid] = message + if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages: + self._inflight_messages += 1 + if qos == 1: + message.state = mqtt_ms_wait_for_puback + elif qos == 2: + message.state = mqtt_ms_wait_for_pubrec + + rc = self._send_publish(message.mid, topic_bytes, message.payload, message.qos, message.retain, + message.dup, message.info, message.properties) + + # remove from inflight messages so it will be send after a connection is made + if rc == MQTTErrorCode.MQTT_ERR_NO_CONN: + self._inflight_messages -= 1 + message.state = mqtt_ms_publish + + message.info.rc = rc + return message.info + else: + message.state = mqtt_ms_queued + message.info.rc = MQTTErrorCode.MQTT_ERR_SUCCESS + return message.info + + def username_pw_set( + self, username: str | None, password: str | None = None + ) -> None: + """Set a username and optionally a password for broker authentication. + + Must be called before connect() to have any effect. + Requires a broker that supports MQTT v3.1 or more. + + :param str username: The username to authenticate with. Need have no relationship to the client id. Must be str + [MQTT-3.1.3-11]. + Set to None to reset client back to not using username/password for broker authentication. + :param str password: The password to authenticate with. Optional, set to None if not required. If it is str, then it + will be encoded as UTF-8. + """ + + # [MQTT-3.1.3-11] User name must be UTF-8 encoded string + self._username = None if username is None else username.encode('utf-8') + if isinstance(password, str): + self._password = password.encode('utf-8') + else: + self._password = password + + def enable_bridge_mode(self) -> None: + """Sets the client in a bridge mode instead of client mode. + + Must be called before `connect()` to have any effect. + Requires brokers that support bridge mode. + + Under bridge mode, the broker will identify the client as a bridge and + not send it's own messages back to it. Hence a subsciption of # is + possible without message loops. This feature also correctly propagates + the retain flag on the messages. + + Currently Mosquitto and RSMB support this feature. This feature can + be used to create a bridge between multiple broker. + """ + self._client_mode = MQTT_BRIDGE + + def _connection_closed(self) -> bool: + """ + Return true if the connection is closed (and not trying to be opened). + """ + return ( + self._state == _ConnectionState.MQTT_CS_NEW + or (self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) and self._sock is None)) + + def is_connected(self) -> bool: + """Returns the current status of the connection + + True if connection exists + False if connection is closed + """ + return self._state == _ConnectionState.MQTT_CS_CONNECTED + + def disconnect( + self, + reasoncode: ReasonCode | None = None, + properties: Properties | None = None, + ) -> MQTTErrorCode: + """Disconnect a connected client from the broker. + + :param ReasonCode reasoncode: (MQTT v5.0 only) a ReasonCode instance setting the MQTT v5.0 + reasoncode to be sent with the disconnect packet. It is optional, the receiver + then assuming that 0 (success) is the value. + :param Properties properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + """ + if self._sock is None: + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + return MQTT_ERR_NO_CONN + else: + self._state = _ConnectionState.MQTT_CS_DISCONNECTING + + return self._send_disconnect(reasoncode, properties) + + def subscribe( + self, + topic: str | tuple[str, int] | tuple[str, SubscribeOptions] | list[tuple[str, int]] | list[tuple[str, SubscribeOptions]], + qos: int = 0, + options: SubscribeOptions | None = None, + properties: Properties | None = None, + ) -> tuple[MQTTErrorCode, int | None]: + """Subscribe the client to one or more topics. + + This function may be called in three different ways (and a further three for MQTT v5.0): + + Simple string and integer + ------------------------- + e.g. subscribe("my/topic", 2) + + :topic: A string specifying the subscription topic to subscribe to. + :qos: The desired quality of service level for the subscription. + Defaults to 0. + :options and properties: Not used. + + Simple string and subscribe options (MQTT v5.0 only) + ---------------------------------------------------- + e.g. subscribe("my/topic", options=SubscribeOptions(qos=2)) + + :topic: A string specifying the subscription topic to subscribe to. + :qos: Not used. + :options: The MQTT v5.0 subscribe options. + :properties: a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + String and integer tuple + ------------------------ + e.g. subscribe(("my/topic", 1)) + + :topic: A tuple of (topic, qos). Both topic and qos must be present in + the tuple. + :qos and options: Not used. + :properties: Only used for MQTT v5.0. A Properties instance setting the + MQTT v5.0 properties. Optional - if not set, no properties are sent. + + String and subscribe options tuple (MQTT v5.0 only) + --------------------------------------------------- + e.g. subscribe(("my/topic", SubscribeOptions(qos=1))) + + :topic: A tuple of (topic, SubscribeOptions). Both topic and subscribe + options must be present in the tuple. + :qos and options: Not used. + :properties: a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + List of string and integer tuples + --------------------------------- + e.g. subscribe([("my/topic", 0), ("another/topic", 2)]) + + This allows multiple topic subscriptions in a single SUBSCRIPTION + command, which is more efficient than using multiple calls to + subscribe(). + + :topic: A list of tuple of format (topic, qos). Both topic and qos must + be present in all of the tuples. + :qos, options and properties: Not used. + + List of string and subscribe option tuples (MQTT v5.0 only) + ----------------------------------------------------------- + e.g. subscribe([("my/topic", SubscribeOptions(qos=0), ("another/topic", SubscribeOptions(qos=2)]) + + This allows multiple topic subscriptions in a single SUBSCRIPTION + command, which is more efficient than using multiple calls to + subscribe(). + + :topic: A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe + options must be present in all of the tuples. + :qos and options: Not used. + :properties: a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + The function returns a tuple (result, mid), where result is + MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the + client is not currently connected. mid is the message ID for the + subscribe request. The mid value can be used to track the subscribe + request by checking against the mid argument in the on_subscribe() + callback if it is defined. + + Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has + zero string length, or if topic is not a string, tuple or list. + """ + topic_qos_list = None + + if isinstance(topic, tuple): + if self._protocol == MQTTv5: + topic, options = topic # type: ignore + if not isinstance(options, SubscribeOptions): + raise ValueError( + 'Subscribe options must be instance of SubscribeOptions class.') + else: + topic, qos = topic # type: ignore + + if isinstance(topic, (bytes, str)): + if qos < 0 or qos > 2: + raise ValueError('Invalid QoS level.') + if self._protocol == MQTTv5: + if options is None: + # if no options are provided, use the QoS passed instead + options = SubscribeOptions(qos=qos) + elif qos != 0: + raise ValueError( + 'Subscribe options and qos parameters cannot be combined.') + if not isinstance(options, SubscribeOptions): + raise ValueError( + 'Subscribe options must be instance of SubscribeOptions class.') + topic_qos_list = [(topic.encode('utf-8'), options)] + else: + if topic is None or len(topic) == 0: + raise ValueError('Invalid topic.') + topic_qos_list = [(topic.encode('utf-8'), qos)] # type: ignore + elif isinstance(topic, list): + if len(topic) == 0: + raise ValueError('Empty topic list') + topic_qos_list = [] + if self._protocol == MQTTv5: + for t, o in topic: + if not isinstance(o, SubscribeOptions): + # then the second value should be QoS + if o < 0 or o > 2: + raise ValueError('Invalid QoS level.') + o = SubscribeOptions(qos=o) + topic_qos_list.append((t.encode('utf-8'), o)) + else: + for t, q in topic: + if isinstance(q, SubscribeOptions) or q < 0 or q > 2: + raise ValueError('Invalid QoS level.') + if t is None or len(t) == 0 or not isinstance(t, (bytes, str)): + raise ValueError('Invalid topic.') + topic_qos_list.append((t.encode('utf-8'), q)) # type: ignore + + if topic_qos_list is None: + raise ValueError("No topic specified, or incorrect topic type.") + + if any(self._filter_wildcard_len_check(topic) != MQTT_ERR_SUCCESS for topic, _ in topic_qos_list): + raise ValueError('Invalid subscription filter.') + + if self._sock is None: + return (MQTT_ERR_NO_CONN, None) + + return self._send_subscribe(False, topic_qos_list, properties) + + def unsubscribe( + self, topic: str | list[str], properties: Properties | None = None + ) -> tuple[MQTTErrorCode, int | None]: + """Unsubscribe the client from one or more topics. + + :param topic: A single string, or list of strings that are the subscription + topics to unsubscribe from. + :param properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS + to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not + currently connected. + mid is the message ID for the unsubscribe request. The mid value can be + used to track the unsubscribe request by checking against the mid + argument in the on_unsubscribe() callback if it is defined. + + :raises ValueError: if topic is None or has zero string length, or is + not a string or list. + """ + topic_list = None + if topic is None: + raise ValueError('Invalid topic.') + if isinstance(topic, (bytes, str)): + if len(topic) == 0: + raise ValueError('Invalid topic.') + topic_list = [topic.encode('utf-8')] + elif isinstance(topic, list): + topic_list = [] + for t in topic: + if len(t) == 0 or not isinstance(t, (bytes, str)): + raise ValueError('Invalid topic.') + topic_list.append(t.encode('utf-8')) + + if topic_list is None: + raise ValueError("No topic specified, or incorrect topic type.") + + if self._sock is None: + return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) + + return self._send_unsubscribe(False, topic_list, properties) + + def loop_read(self, max_packets: int = 1) -> MQTTErrorCode: + """Process read network events. Use in place of calling `loop()` if you + wish to handle your client reads as part of your own application. + + Use `socket()` to obtain the client socket to call select() or equivalent + on. + + Do not use if you are using `loop_start()` or `loop_forever()`.""" + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + max_packets = len(self._out_messages) + len(self._in_messages) + if max_packets < 1: + max_packets = 1 + + for _ in range(0, max_packets): + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + rc = self._packet_read() + if rc > 0: + return self._loop_rc_handle(rc) + elif rc == MQTTErrorCode.MQTT_ERR_AGAIN: + return MQTTErrorCode.MQTT_ERR_SUCCESS + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def loop_write(self) -> MQTTErrorCode: + """Process write network events. Use in place of calling `loop()` if you + wish to handle your client writes as part of your own application. + + Use `socket()` to obtain the client socket to call select() or equivalent + on. + + Use `want_write()` to determine if there is data waiting to be written. + + Do not use if you are using `loop_start()` or `loop_forever()`.""" + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + try: + rc = self._packet_write() + if rc == MQTTErrorCode.MQTT_ERR_AGAIN: + return MQTTErrorCode.MQTT_ERR_SUCCESS + elif rc > 0: + return self._loop_rc_handle(rc) + else: + return MQTTErrorCode.MQTT_ERR_SUCCESS + finally: + if self.want_write(): + self._call_socket_register_write() + else: + self._call_socket_unregister_write() + + def want_write(self) -> bool: + """Call to determine if there is network data waiting to be written. + Useful if you are calling select() yourself rather than using `loop()`, `loop_start()` or `loop_forever()`. + """ + return len(self._out_packet) > 0 + + def loop_misc(self) -> MQTTErrorCode: + """Process miscellaneous network events. Use in place of calling `loop()` if you + wish to call select() or equivalent on. + + Do not use if you are using `loop_start()` or `loop_forever()`.""" + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + now = time_func() + self._check_keepalive() + + if self._ping_t > 0 and now - self._ping_t >= self._keepalive: + # client->ping_t != 0 means we are waiting for a pingresp. + # This hasn't happened in the keepalive time so we should disconnect. + self._sock_close() + + if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + else: + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE + + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=rc, + ) + + return MQTTErrorCode.MQTT_ERR_CONN_LOST + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def max_inflight_messages_set(self, inflight: int) -> None: + """Set the maximum number of messages with QoS>0 that can be part way + through their network flow at once. Defaults to 20.""" + self.max_inflight_messages = inflight + + def max_queued_messages_set(self, queue_size: int) -> Client: + """Set the maximum number of messages in the outgoing message queue. + 0 means unlimited.""" + if not isinstance(queue_size, int): + raise ValueError('Invalid type of queue size.') + self.max_queued_messages = queue_size + return self + + def user_data_set(self, userdata: Any) -> None: + """Set the user data variable passed to callbacks. May be any data type.""" + self._userdata = userdata + + def user_data_get(self) -> Any: + """Get the user data variable passed to callbacks. May be any data type.""" + return self._userdata + + def will_set( + self, + topic: str, + payload: PayloadType = None, + qos: int = 0, + retain: bool = False, + properties: Properties | None = None, + ) -> None: + """Set a Will to be sent by the broker in case the client disconnects unexpectedly. + + This must be called before connect() to have any effect. + + :param str topic: The topic that the will message should be published on. + :param payload: The message to send as a will. If not given, or set to None a + zero length message will be used as the will. Passing an int or float + will result in the payload being converted to a string representing + that number. If you wish to send a true int/float, use struct.pack() to + create the payload you require. + :param int qos: The quality of service level to use for the will. + :param bool retain: If set to true, the will message will be set as the "last known + good"/retained message for the topic. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties + to be included with the will message. Optional - if not set, no properties are sent. + + :raises ValueError: if qos is not 0, 1 or 2, or if topic is None or has + zero string length. + + See `will_clear` to clear will. Note that will are NOT send if the client disconnect cleanly + for example by calling `disconnect()`. + """ + if topic is None or len(topic) == 0: + raise ValueError('Invalid topic.') + + if qos < 0 or qos > 2: + raise ValueError('Invalid QoS level.') + + if properties and not isinstance(properties, Properties): + raise ValueError( + "The properties argument must be an instance of the Properties class.") + + self._will_payload = _encode_payload(payload) + self._will = True + self._will_topic = topic.encode('utf-8') + self._will_qos = qos + self._will_retain = retain + self._will_properties = properties + + def will_clear(self) -> None: + """ Removes a will that was previously configured with `will_set()`. + + Must be called before connect() to have any effect.""" + self._will = False + self._will_topic = b"" + self._will_payload = b"" + self._will_qos = 0 + self._will_retain = False + + def socket(self) -> SocketLike | None: + """Return the socket or ssl object for this client.""" + return self._sock + + def loop_forever( + self, + timeout: float = 1.0, + retry_first_connection: bool = False, + ) -> MQTTErrorCode: + """This function calls the network loop functions for you in an + infinite blocking loop. It is useful for the case where you only want + to run the MQTT client loop in your program. + + loop_forever() will handle reconnecting for you if reconnect_on_failure is + true (this is the default behavior). If you call `disconnect()` in a callback + it will return. + + :param int timeout: The time in seconds to wait for incoming/outgoing network + traffic before timing out and returning. + :param bool retry_first_connection: Should the first connection attempt be retried on failure. + This is independent of the reconnect_on_failure setting. + + :raises OSError: if the first connection fail unless retry_first_connection=True + """ + + run = True + + while run: + if self._thread_terminate is True: + break + + if self._state == _ConnectionState.MQTT_CS_CONNECT_ASYNC: + try: + self.reconnect() + except OSError: + self._handle_on_connect_fail() + if not retry_first_connection: + raise + self._easy_log( + MQTT_LOG_DEBUG, "Connection failed, retrying") + self._reconnect_wait() + else: + break + + while run: + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + while rc == MQTTErrorCode.MQTT_ERR_SUCCESS: + rc = self._loop(timeout) + # We don't need to worry about locking here, because we've + # either called loop_forever() when in single threaded mode, or + # in multi threaded mode when loop_stop() has been called and + # so no other threads can access _out_packet or _messages. + if (self._thread_terminate is True + and len(self._out_packet) == 0 + and len(self._out_messages) == 0): + rc = MQTTErrorCode.MQTT_ERR_NOMEM + run = False + + def should_exit() -> bool: + return ( + self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) or + run is False or # noqa: B023 (uses the run variable from the outer scope on purpose) + self._thread_terminate is True + ) + + if should_exit() or not self._reconnect_on_failure: + run = False + else: + self._reconnect_wait() + + if should_exit(): + run = False + else: + try: + self.reconnect() + except OSError: + self._handle_on_connect_fail() + self._easy_log( + MQTT_LOG_DEBUG, "Connection failed, retrying") + + return rc + + def loop_start(self) -> MQTTErrorCode: + """This is part of the threaded client interface. Call this once to + start a new thread to process network traffic. This provides an + alternative to repeatedly calling `loop()` yourself. + + Under the hood, this will call `loop_forever` in a thread, which means that + the thread will terminate if you call `disconnect()` + """ + if self._thread is not None: + return MQTTErrorCode.MQTT_ERR_INVAL + + self._sockpairR, self._sockpairW = _socketpair_compat() + self._thread_terminate = False + self._thread = threading.Thread(target=self._thread_main, name=f"paho-mqtt-client-{self._client_id.decode()}") + self._thread.daemon = True + self._thread.start() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def loop_stop(self) -> MQTTErrorCode: + """This is part of the threaded client interface. Call this once to + stop the network thread previously created with `loop_start()`. This call + will block until the network thread finishes. + + This don't guarantee that publish packet are sent, use `wait_for_publish` or + `on_publish` to ensure `publish` are sent. + """ + if self._thread is None: + return MQTTErrorCode.MQTT_ERR_INVAL + + self._thread_terminate = True + if threading.current_thread() != self._thread: + self._thread.join() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + @property + def callback_api_version(self) -> CallbackAPIVersion: + """ + Return the callback API version used for user-callback. See docstring for + each user-callback (`on_connect`, `on_publish`, ...) for details. + + This property is read-only. + """ + return self._callback_api_version + + @property + def on_log(self) -> CallbackOnLog | None: + """The callback called when the client has log information. + Defined to allow debugging. + + Expected signature is:: + + log_callback(client, userdata, level, buf) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param int level: gives the severity of the message and will be one of + MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, + MQTT_LOG_ERR, and MQTT_LOG_DEBUG. + :param str buf: the message itself + + Decorator: @client.log_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_log + + @on_log.setter + def on_log(self, func: CallbackOnLog | None) -> None: + self._on_log = func + + def log_callback(self) -> Callable[[CallbackOnLog], CallbackOnLog]: + def decorator(func: CallbackOnLog) -> CallbackOnLog: + self.on_log = func + return func + return decorator + + @property + def on_pre_connect(self) -> CallbackOnPreConnect | None: + """The callback called immediately prior to the connection is made + request. + + Expected signature (for all callback API version):: + + connect_callback(client, userdata) + + :parama Client client: the client instance for this callback + :parama userdata: the private user data as set in Client() or user_data_set() + + Decorator: @client.pre_connect_callback() (``client`` is the name of the + instance which this callback is being attached to) + + """ + return self._on_pre_connect + + @on_pre_connect.setter + def on_pre_connect(self, func: CallbackOnPreConnect | None) -> None: + with self._callback_mutex: + self._on_pre_connect = func + + def pre_connect_callback( + self, + ) -> Callable[[CallbackOnPreConnect], CallbackOnPreConnect]: + def decorator(func: CallbackOnPreConnect) -> CallbackOnPreConnect: + self.on_pre_connect = func + return func + return decorator + + @property + def on_connect(self) -> CallbackOnConnect | None: + """The callback called when the broker reponds to our connection request. + + Expected signature for callback API version 2:: + + connect_callback(client, userdata, connect_flags, reason_code, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + connect_callback(client, userdata, flags, rc) + + * For MQTT v5.0 it's:: + + connect_callback(client, userdata, flags, reason_code, properties) + + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param ConnectFlags connect_flags: the flags for this connection + :param ReasonCode reason_code: the connection reason code received from the broken. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3, we convert return code to a reason code, see + `convert_connack_rc_to_reason_code()`. + `ReasonCode` may be compared to integer. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param dict flags: response flags sent by the broker + :param int rc: the connection result, should have a value of `ConnackCode` + + flags is a dict that contains response flags from the broker: + flags['session present'] - this flag is useful for clients that are + using clean session set to 0 only. If a client with clean + session=0, that reconnects to a broker that it has previously + connected to, this flag indicates whether the broker still has the + session information for the client. If 1, the session still exists. + + The value of rc indicates success or not: + - 0: Connection successful + - 1: Connection refused - incorrect protocol version + - 2: Connection refused - invalid client identifier + - 3: Connection refused - server unavailable + - 4: Connection refused - bad username or password + - 5: Connection refused - not authorised + - 6-255: Currently unused. + + Decorator: @client.connect_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_connect + + @on_connect.setter + def on_connect(self, func: CallbackOnConnect | None) -> None: + with self._callback_mutex: + self._on_connect = func + + def connect_callback( + self, + ) -> Callable[[CallbackOnConnect], CallbackOnConnect]: + def decorator(func: CallbackOnConnect) -> CallbackOnConnect: + self.on_connect = func + return func + return decorator + + @property + def on_connect_fail(self) -> CallbackOnConnectFail | None: + """The callback called when the client failed to connect + to the broker. + + Expected signature is (for all callback_api_version):: + + connect_fail_callback(client, userdata) + + :param Client client: the client instance for this callback + :parama userdata: the private user data as set in Client() or user_data_set() + + Decorator: @client.connect_fail_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_connect_fail + + @on_connect_fail.setter + def on_connect_fail(self, func: CallbackOnConnectFail | None) -> None: + with self._callback_mutex: + self._on_connect_fail = func + + def connect_fail_callback( + self, + ) -> Callable[[CallbackOnConnectFail], CallbackOnConnectFail]: + def decorator(func: CallbackOnConnectFail) -> CallbackOnConnectFail: + self.on_connect_fail = func + return func + return decorator + + @property + def on_subscribe(self) -> CallbackOnSubscribe | None: + """The callback called when the broker responds to a subscribe + request. + + Expected signature for callback API version 2:: + + subscribe_callback(client, userdata, mid, reason_code_list, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + subscribe_callback(client, userdata, mid, granted_qos) + + * For MQTT v5.0 it's:: + + subscribe_callback(client, userdata, mid, reason_code_list, properties) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param int mid: matches the mid variable returned from the corresponding + subscribe() call. + :param list[ReasonCode] reason_code_list: reason codes received from the broker for each subscription. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3, we convert granted QoS to a reason code. + It's a list of ReasonCode instances. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param list[int] granted_qos: list of integers that give the QoS level the broker has + granted for each of the different subscription requests. + + Decorator: @client.subscribe_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_subscribe + + @on_subscribe.setter + def on_subscribe(self, func: CallbackOnSubscribe | None) -> None: + with self._callback_mutex: + self._on_subscribe = func + + def subscribe_callback( + self, + ) -> Callable[[CallbackOnSubscribe], CallbackOnSubscribe]: + def decorator(func: CallbackOnSubscribe) -> CallbackOnSubscribe: + self.on_subscribe = func + return func + return decorator + + @property + def on_message(self) -> CallbackOnMessage | None: + """The callback called when a message has been received on a topic + that the client subscribes to. + + This callback will be called for every message received unless a + `message_callback_add()` matched the message. + + Expected signature is (for all callback API version): + message_callback(client, userdata, message) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param MQTTMessage message: the received message. + This is a class with members topic, payload, qos, retain. + + Decorator: @client.message_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_message + + @on_message.setter + def on_message(self, func: CallbackOnMessage | None) -> None: + with self._callback_mutex: + self._on_message = func + + def message_callback( + self, + ) -> Callable[[CallbackOnMessage], CallbackOnMessage]: + def decorator(func: CallbackOnMessage) -> CallbackOnMessage: + self.on_message = func + return func + return decorator + + @property + def on_publish(self) -> CallbackOnPublish | None: + """The callback called when a message that was to be sent using the + `publish()` call has completed transmission to the broker. + + For messages with QoS levels 1 and 2, this means that the appropriate + handshakes have completed. For QoS 0, this simply means that the message + has left the client. + This callback is important because even if the `publish()` call returns + success, it does not always mean that the message has been sent. + + See also `wait_for_publish` which could be simpler to use. + + Expected signature for callback API version 2:: + + publish_callback(client, userdata, mid, reason_code, properties) + + Expected signature for callback API version 1:: + + publish_callback(client, userdata, mid) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param int mid: matches the mid variable returned from the corresponding + `publish()` call, to allow outgoing messages to be tracked. + :param ReasonCode reason_code: the connection reason code received from the broken. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3 it's always the reason code Success + :parama Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + + Note: for QoS = 0, the reason_code and the properties don't really exist, it's the client + library that generate them. It's always an empty properties and a success reason code. + Because the (MQTTv5) standard don't have reason code for PUBLISH packet, the library create them + at PUBACK packet, as if the message was sent with QoS = 1. + + Decorator: @client.publish_callback() (``client`` is the name of the + instance which this callback is being attached to) + + """ + return self._on_publish + + @on_publish.setter + def on_publish(self, func: CallbackOnPublish | None) -> None: + with self._callback_mutex: + self._on_publish = func + + def publish_callback( + self, + ) -> Callable[[CallbackOnPublish], CallbackOnPublish]: + def decorator(func: CallbackOnPublish) -> CallbackOnPublish: + self.on_publish = func + return func + return decorator + + @property + def on_unsubscribe(self) -> CallbackOnUnsubscribe | None: + """The callback called when the broker responds to an unsubscribe + request. + + Expected signature for callback API version 2:: + + unsubscribe_callback(client, userdata, mid, reason_code_list, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + unsubscribe_callback(client, userdata, mid) + + * For MQTT v5.0 it's:: + + unsubscribe_callback(client, userdata, mid, properties, v1_reason_codes) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param mid: matches the mid variable returned from the corresponding + unsubscribe() call. + :param list[ReasonCode] reason_code_list: reason codes received from the broker for each unsubscription. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3, there is not equivalent from broken and empty list + is always used. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param v1_reason_codes: the MQTT v5.0 reason codes received from the broker for each + unsubscribe topic. A list of ReasonCode instances OR a single + ReasonCode when we unsubscribe from a single topic. + + Decorator: @client.unsubscribe_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_unsubscribe + + @on_unsubscribe.setter + def on_unsubscribe(self, func: CallbackOnUnsubscribe | None) -> None: + with self._callback_mutex: + self._on_unsubscribe = func + + def unsubscribe_callback( + self, + ) -> Callable[[CallbackOnUnsubscribe], CallbackOnUnsubscribe]: + def decorator(func: CallbackOnUnsubscribe) -> CallbackOnUnsubscribe: + self.on_unsubscribe = func + return func + return decorator + + @property + def on_disconnect(self) -> CallbackOnDisconnect | None: + """The callback called when the client disconnects from the broker. + + Expected signature for callback API version 2:: + + disconnect_callback(client, userdata, disconnect_flags, reason_code, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + disconnect_callback(client, userdata, rc) + + * For MQTT v5.0 it's:: + + disconnect_callback(client, userdata, reason_code, properties) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param DisconnectFlag disconnect_flags: the flags for this disconnection. + :param ReasonCode reason_code: the disconnection reason code possibly received from the broker (see disconnect_flags). + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3 it's never received from the broker, we convert an MQTTErrorCode, + see `convert_disconnect_error_code_to_reason_code()`. + `ReasonCode` may be compared to integer. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param int rc: the disconnection result + The rc parameter indicates the disconnection state. If + MQTT_ERR_SUCCESS (0), the callback was called in response to + a disconnect() call. If any other value the disconnection + was unexpected, such as might be caused by a network error. + + Decorator: @client.disconnect_callback() (``client`` is the name of the + instance which this callback is being attached to) + + """ + return self._on_disconnect + + @on_disconnect.setter + def on_disconnect(self, func: CallbackOnDisconnect | None) -> None: + with self._callback_mutex: + self._on_disconnect = func + + def disconnect_callback( + self, + ) -> Callable[[CallbackOnDisconnect], CallbackOnDisconnect]: + def decorator(func: CallbackOnDisconnect) -> CallbackOnDisconnect: + self.on_disconnect = func + return func + return decorator + + @property + def on_socket_open(self) -> CallbackOnSocket | None: + """The callback called just after the socket was opend. + + This should be used to register the socket to an external event loop for reading. + + Expected signature is (for all callback API version):: + + socket_open_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which was just opened. + + Decorator: @client.socket_open_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_open + + @on_socket_open.setter + def on_socket_open(self, func: CallbackOnSocket | None) -> None: + with self._callback_mutex: + self._on_socket_open = func + + def socket_open_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator(func: CallbackOnSocket) -> CallbackOnSocket: + self.on_socket_open = func + return func + return decorator + + def _call_socket_open(self, sock: SocketLike) -> None: + """Call the socket_open callback with the just-opened socket""" + with self._callback_mutex: + on_socket_open = self.on_socket_open + + if on_socket_open: + with self._in_callback_mutex: + try: + on_socket_open(self, self._userdata, sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_open: %s', err) + if not self.suppress_exceptions: + raise + + @property + def on_socket_close(self) -> CallbackOnSocket | None: + """The callback called just before the socket is closed. + + This should be used to unregister the socket from an external event loop for reading. + + Expected signature is (for all callback API version):: + + socket_close_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which is about to be closed. + + Decorator: @client.socket_close_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_close + + @on_socket_close.setter + def on_socket_close(self, func: CallbackOnSocket | None) -> None: + with self._callback_mutex: + self._on_socket_close = func + + def socket_close_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator(func: CallbackOnSocket) -> CallbackOnSocket: + self.on_socket_close = func + return func + return decorator + + def _call_socket_close(self, sock: SocketLike) -> None: + """Call the socket_close callback with the about-to-be-closed socket""" + with self._callback_mutex: + on_socket_close = self.on_socket_close + + if on_socket_close: + with self._in_callback_mutex: + try: + on_socket_close(self, self._userdata, sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_close: %s', err) + if not self.suppress_exceptions: + raise + + @property + def on_socket_register_write(self) -> CallbackOnSocket | None: + """The callback called when the socket needs writing but can't. + + This should be used to register the socket with an external event loop for writing. + + Expected signature is (for all callback API version):: + + socket_register_write_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which should be registered for writing + + Decorator: @client.socket_register_write_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_register_write + + @on_socket_register_write.setter + def on_socket_register_write(self, func: CallbackOnSocket | None) -> None: + with self._callback_mutex: + self._on_socket_register_write = func + + def socket_register_write_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator(func: CallbackOnSocket) -> CallbackOnSocket: + self._on_socket_register_write = func + return func + return decorator + + def _call_socket_register_write(self) -> None: + """Call the socket_register_write callback with the unwritable socket""" + if not self._sock or self._registered_write: + return + self._registered_write = True + with self._callback_mutex: + on_socket_register_write = self.on_socket_register_write + + if on_socket_register_write: + try: + on_socket_register_write( + self, self._userdata, self._sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_register_write: %s', err) + if not self.suppress_exceptions: + raise + + @property + def on_socket_unregister_write( + self, + ) -> CallbackOnSocket | None: + """The callback called when the socket doesn't need writing anymore. + + This should be used to unregister the socket from an external event loop for writing. + + Expected signature is (for all callback API version):: + + socket_unregister_write_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which should be unregistered for writing + + Decorator: @client.socket_unregister_write_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_unregister_write + + @on_socket_unregister_write.setter + def on_socket_unregister_write( + self, func: CallbackOnSocket | None + ) -> None: + with self._callback_mutex: + self._on_socket_unregister_write = func + + def socket_unregister_write_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator( + func: CallbackOnSocket, + ) -> CallbackOnSocket: + self._on_socket_unregister_write = func + return func + return decorator + + def _call_socket_unregister_write( + self, sock: SocketLike | None = None + ) -> None: + """Call the socket_unregister_write callback with the writable socket""" + sock = sock or self._sock + if not sock or not self._registered_write: + return + self._registered_write = False + + with self._callback_mutex: + on_socket_unregister_write = self.on_socket_unregister_write + + if on_socket_unregister_write: + try: + on_socket_unregister_write(self, self._userdata, sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_unregister_write: %s', err) + if not self.suppress_exceptions: + raise + + def message_callback_add(self, sub: str, callback: CallbackOnMessage) -> None: + """Register a message callback for a specific topic. + Messages that match 'sub' will be passed to 'callback'. Any + non-matching messages will be passed to the default `on_message` + callback. + + Call multiple times with different 'sub' to define multiple topic + specific callbacks. + + Topic specific callbacks may be removed with + `message_callback_remove()`. + + See `on_message` for the expected signature of the callback. + + Decorator: @client.topic_callback(sub) (``client`` is the name of the + instance which this callback is being attached to) + + Example:: + + @client.topic_callback("mytopic/#") + def handle_mytopic(client, userdata, message): + ... + """ + if callback is None or sub is None: + raise ValueError("sub and callback must both be defined.") + + with self._callback_mutex: + self._on_message_filtered[sub] = callback + + def topic_callback( + self, sub: str + ) -> Callable[[CallbackOnMessage], CallbackOnMessage]: + def decorator(func: CallbackOnMessage) -> CallbackOnMessage: + self.message_callback_add(sub, func) + return func + return decorator + + def message_callback_remove(self, sub: str) -> None: + """Remove a message callback previously registered with + `message_callback_add()`.""" + if sub is None: + raise ValueError("sub must defined.") + + with self._callback_mutex: + try: + del self._on_message_filtered[sub] + except KeyError: # no such subscription + pass + + # ============================================================ + # Private functions + # ============================================================ + + def _loop_rc_handle( + self, + rc: MQTTErrorCode, + ) -> MQTTErrorCode: + if rc: + self._sock_close() + + if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + + self._do_on_disconnect(packet_from_broker=False, v1_rc=rc) + + if rc == MQTT_ERR_CONN_LOST: + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + + return rc + + def _packet_read(self) -> MQTTErrorCode: + # This gets called if pselect() indicates that there is network data + # available - ie. at least one byte. What we do depends on what data we + # already have. + # If we've not got a command, attempt to read one and save it. This should + # always work because it's only a single byte. + # Then try to read the remaining length. This may fail because it is may + # be more than one byte - will need to save data pending next read if it + # does fail. + # Then try to read the remaining payload, where 'payload' here means the + # combined variable header and actual payload. This is the most likely to + # fail due to longer length, so save current data and current position. + # After all data is read, send to _mqtt_handle_packet() to deal with. + # Finally, free the memory and reset everything to starting conditions. + if self._in_packet['command'] == 0: + try: + command = self._sock_recv(1) + except BlockingIOError: + return MQTTErrorCode.MQTT_ERR_AGAIN + except TimeoutError as err: + self._easy_log( + MQTT_LOG_ERR, 'timeout on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + except OSError as err: + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + else: + if len(command) == 0: + return MQTTErrorCode.MQTT_ERR_CONN_LOST + self._in_packet['command'] = command[0] + + if self._in_packet['have_remaining'] == 0: + # Read remaining + # Algorithm for decoding taken from pseudo code at + # http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm + while True: + try: + byte = self._sock_recv(1) + except BlockingIOError: + return MQTTErrorCode.MQTT_ERR_AGAIN + except OSError as err: + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + else: + if len(byte) == 0: + return MQTTErrorCode.MQTT_ERR_CONN_LOST + byte_value = byte[0] + self._in_packet['remaining_count'].append(byte_value) + # Max 4 bytes length for remaining length as defined by protocol. + # Anything more likely means a broken/malicious client. + if len(self._in_packet['remaining_count']) > 4: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + self._in_packet['remaining_length'] += ( + byte_value & 127) * self._in_packet['remaining_mult'] + self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128 + + if (byte_value & 128) == 0: + break + + self._in_packet['have_remaining'] = 1 + self._in_packet['to_process'] = self._in_packet['remaining_length'] + + count = 100 # Don't get stuck in this loop if we have a huge message. + while self._in_packet['to_process'] > 0: + try: + data = self._sock_recv(self._in_packet['to_process']) + except BlockingIOError: + return MQTTErrorCode.MQTT_ERR_AGAIN + except OSError as err: + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + else: + if len(data) == 0: + return MQTTErrorCode.MQTT_ERR_CONN_LOST + self._in_packet['to_process'] -= len(data) + self._in_packet['packet'] += data + count -= 1 + if count == 0: + with self._msgtime_mutex: + self._last_msg_in = time_func() + return MQTTErrorCode.MQTT_ERR_AGAIN + + # All data for this packet is read. + self._in_packet['pos'] = 0 + rc = self._packet_handle() + + # Free data and reset values + self._in_packet = { + "command": 0, + "have_remaining": 0, + "remaining_count": [], + "remaining_mult": 1, + "remaining_length": 0, + "packet": bytearray(b""), + "to_process": 0, + "pos": 0, + } + + with self._msgtime_mutex: + self._last_msg_in = time_func() + return rc + + def _packet_write(self) -> MQTTErrorCode: + while True: + try: + packet = self._out_packet.popleft() + except IndexError: + return MQTTErrorCode.MQTT_ERR_SUCCESS + + try: + write_length = self._sock_send( + packet['packet'][packet['pos']:]) + except (AttributeError, ValueError): + self._out_packet.appendleft(packet) + return MQTTErrorCode.MQTT_ERR_SUCCESS + except BlockingIOError: + self._out_packet.appendleft(packet) + return MQTTErrorCode.MQTT_ERR_AGAIN + except OSError as err: + self._out_packet.appendleft(packet) + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + + if write_length > 0: + packet['to_process'] -= write_length + packet['pos'] += write_length + + if packet['to_process'] == 0: + if (packet['command'] & 0xF0) == PUBLISH and packet['qos'] == 0: + with self._callback_mutex: + on_publish = self.on_publish + + if on_publish: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + on_publish = cast(CallbackOnPublish_v1, on_publish) + + on_publish(self, self._userdata, packet["mid"]) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_publish = cast(CallbackOnPublish_v2, on_publish) + + on_publish( + self, + self._userdata, + packet["mid"], + ReasonCode(PacketTypes.PUBACK), + Properties(PacketTypes.PUBACK), + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err) + if not self.suppress_exceptions: + raise + + # TODO: Something is odd here. I don't see why packet["info"] can't be None. + # A packet could be produced by _handle_connack with qos=0 and no info + # (around line 3645). Ignore the mypy check for now but I feel there is a bug + # somewhere. + packet['info']._set_as_published() # type: ignore + + if (packet['command'] & 0xF0) == DISCONNECT: + with self._msgtime_mutex: + self._last_msg_out = time_func() + + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, + ) + self._sock_close() + # Only change to disconnected if the disconnection was wanted + # by the client (== state was disconnecting). If the broker disconnected + # use unilaterally don't change the state and client may reconnect. + if self._state == _ConnectionState.MQTT_CS_DISCONNECTING: + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + return MQTTErrorCode.MQTT_ERR_SUCCESS + + else: + # We haven't finished with this packet + self._out_packet.appendleft(packet) + else: + break + + with self._msgtime_mutex: + self._last_msg_out = time_func() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _easy_log(self, level: LogLevel, fmt: str, *args: Any) -> None: + if self.on_log is not None: + buf = fmt % args + try: + self.on_log(self, self._userdata, level, buf) + except Exception: # noqa: S110 + # Can't _easy_log this, as we'll recurse until we break + pass # self._logger will pick this up, so we're fine + if self._logger is not None: + level_std = LOGGING_LEVEL[level] + self._logger.log(level_std, fmt, *args) + + def _check_keepalive(self) -> None: + if self._keepalive == 0: + return + + now = time_func() + + with self._msgtime_mutex: + last_msg_out = self._last_msg_out + last_msg_in = self._last_msg_in + + if self._sock is not None and (now - last_msg_out >= self._keepalive or now - last_msg_in >= self._keepalive): + if self._state == _ConnectionState.MQTT_CS_CONNECTED and self._ping_t == 0: + try: + self._send_pingreq() + except Exception: + self._sock_close() + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=MQTTErrorCode.MQTT_ERR_CONN_LOST, + ) + else: + with self._msgtime_mutex: + self._last_msg_out = now + self._last_msg_in = now + else: + self._sock_close() + + if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + else: + rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE + + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=rc, + ) + + def _mid_generate(self) -> int: + with self._mid_generate_mutex: + self._last_mid += 1 + if self._last_mid == 65536: + self._last_mid = 1 + return self._last_mid + + @staticmethod + def _raise_for_invalid_topic(topic: bytes) -> None: + """ Check if the topic is a topic without wildcard and valid length. + + Raise ValueError if the topic isn't valid. + """ + if b'+' in topic or b'#' in topic: + raise ValueError('Publish topic cannot contain wildcards.') + if len(topic) > 65535: + raise ValueError('Publish topic is too long.') + + @staticmethod + def _filter_wildcard_len_check(sub: bytes) -> MQTTErrorCode: + if (len(sub) == 0 or len(sub) > 65535 + or any(b'+' in p or b'#' in p for p in sub.split(b'/') if len(p) > 1) + or b'#/' in sub): + return MQTTErrorCode.MQTT_ERR_INVAL + else: + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _send_pingreq(self) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PINGREQ") + rc = self._send_simple_command(PINGREQ) + if rc == MQTTErrorCode.MQTT_ERR_SUCCESS: + self._ping_t = time_func() + return rc + + def _send_pingresp(self) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PINGRESP") + return self._send_simple_command(PINGRESP) + + def _send_puback(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBACK (Mid: %d)", mid) + return self._send_command_with_mid(PUBACK, mid, False) + + def _send_pubcomp(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBCOMP (Mid: %d)", mid) + return self._send_command_with_mid(PUBCOMP, mid, False) + + def _pack_remaining_length( + self, packet: bytearray, remaining_length: int + ) -> bytearray: + remaining_bytes = [] + while True: + byte = remaining_length % 128 + remaining_length = remaining_length // 128 + # If there are more digits to encode, set the top bit of this digit + if remaining_length > 0: + byte |= 0x80 + + remaining_bytes.append(byte) + packet.append(byte) + if remaining_length == 0: + # FIXME - this doesn't deal with incorrectly large payloads + return packet + + def _pack_str16(self, packet: bytearray, data: bytes | str) -> None: + data = _force_bytes(data) + packet.extend(struct.pack("!H", len(data))) + packet.extend(data) + + def _send_publish( + self, + mid: int, + topic: bytes, + payload: bytes|bytearray = b"", + qos: int = 0, + retain: bool = False, + dup: bool = False, + info: MQTTMessageInfo | None = None, + properties: Properties | None = None, + ) -> MQTTErrorCode: + # we assume that topic and payload are already properly encoded + if not isinstance(topic, bytes): + raise TypeError('topic must be bytes, not str') + if payload and not isinstance(payload, (bytes, bytearray)): + raise TypeError('payload must be bytes if set') + + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain + packet = bytearray() + packet.append(command) + + payloadlen = len(payload) + remaining_length = 2 + len(topic) + payloadlen + + if payloadlen == 0: + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s (NULL payload)", + dup, qos, retain, mid, topic, properties + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s' (NULL payload)", + dup, qos, retain, mid, topic + ) + else: + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)", + dup, qos, retain, mid, topic, properties, payloadlen + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)", + dup, qos, retain, mid, topic, payloadlen + ) + + if qos > 0: + # For message id + remaining_length += 2 + + if self._protocol == MQTTv5: + if properties is None: + packed_properties = b'\x00' + else: + packed_properties = properties.pack() + remaining_length += len(packed_properties) + + self._pack_remaining_length(packet, remaining_length) + self._pack_str16(packet, topic) + + if qos > 0: + # For message id + packet.extend(struct.pack("!H", mid)) + + if self._protocol == MQTTv5: + packet.extend(packed_properties) + + packet.extend(payload) + + return self._packet_queue(PUBLISH, packet, mid, qos, info) + + def _send_pubrec(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREC (Mid: %d)", mid) + return self._send_command_with_mid(PUBREC, mid, False) + + def _send_pubrel(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREL (Mid: %d)", mid) + return self._send_command_with_mid(PUBREL | 2, mid, False) + + def _send_command_with_mid(self, command: int, mid: int, dup: int) -> MQTTErrorCode: + # For PUBACK, PUBCOMP, PUBREC, and PUBREL + if dup: + command |= 0x8 + + remaining_length = 2 + packet = struct.pack('!BBH', command, remaining_length, mid) + return self._packet_queue(command, packet, mid, 1) + + def _send_simple_command(self, command: int) -> MQTTErrorCode: + # For DISCONNECT, PINGREQ and PINGRESP + remaining_length = 0 + packet = struct.pack('!BB', command, remaining_length) + return self._packet_queue(command, packet, 0, 0) + + def _send_connect(self, keepalive: int) -> MQTTErrorCode: + proto_ver = int(self._protocol) + # hard-coded UTF-8 encoded string + protocol = b"MQTT" if proto_ver >= MQTTv311 else b"MQIsdp" + + remaining_length = 2 + len(protocol) + 1 + \ + 1 + 2 + 2 + len(self._client_id) + + connect_flags = 0 + if self._protocol == MQTTv5: + if self._clean_start is True: + connect_flags |= 0x02 + elif self._clean_start == MQTT_CLEAN_START_FIRST_ONLY and self._mqttv5_first_connect: + connect_flags |= 0x02 + elif self._clean_session: + connect_flags |= 0x02 + + if self._will: + remaining_length += 2 + \ + len(self._will_topic) + 2 + len(self._will_payload) + connect_flags |= 0x04 | ((self._will_qos & 0x03) << 3) | ( + (self._will_retain & 0x01) << 5) + + if self._username is not None: + remaining_length += 2 + len(self._username) + connect_flags |= 0x80 + if self._password is not None: + connect_flags |= 0x40 + remaining_length += 2 + len(self._password) + + if self._protocol == MQTTv5: + if self._connect_properties is None: + packed_connect_properties = b'\x00' + else: + packed_connect_properties = self._connect_properties.pack() + remaining_length += len(packed_connect_properties) + if self._will: + if self._will_properties is None: + packed_will_properties = b'\x00' + else: + packed_will_properties = self._will_properties.pack() + remaining_length += len(packed_will_properties) + + command = CONNECT + packet = bytearray() + packet.append(command) + + # as per the mosquitto broker, if the MSB of this version is set + # to 1, then it treats the connection as a bridge + if self._client_mode == MQTT_BRIDGE: + proto_ver |= 0x80 + + self._pack_remaining_length(packet, remaining_length) + packet.extend(struct.pack( + f"!H{len(protocol)}sBBH", + len(protocol), protocol, proto_ver, connect_flags, keepalive, + )) + + if self._protocol == MQTTv5: + packet += packed_connect_properties + + self._pack_str16(packet, self._client_id) + + if self._will: + if self._protocol == MQTTv5: + packet += packed_will_properties + self._pack_str16(packet, self._will_topic) + self._pack_str16(packet, self._will_payload) + + if self._username is not None: + self._pack_str16(packet, self._username) + + if self._password is not None: + self._pack_str16(packet, self._password) + + self._keepalive = keepalive + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%s", + (connect_flags & 0x80) >> 7, + (connect_flags & 0x40) >> 6, + (connect_flags & 0x20) >> 5, + (connect_flags & 0x18) >> 3, + (connect_flags & 0x4) >> 2, + (connect_flags & 0x2) >> 1, + keepalive, + self._client_id, + self._connect_properties + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s", + (connect_flags & 0x80) >> 7, + (connect_flags & 0x40) >> 6, + (connect_flags & 0x20) >> 5, + (connect_flags & 0x18) >> 3, + (connect_flags & 0x4) >> 2, + (connect_flags & 0x2) >> 1, + keepalive, + self._client_id + ) + return self._packet_queue(command, packet, 0, 0) + + def _send_disconnect( + self, + reasoncode: ReasonCode | None = None, + properties: Properties | None = None, + ) -> MQTTErrorCode: + if self._protocol == MQTTv5: + self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT reasonCode=%s properties=%s", + reasoncode, + properties + ) + else: + self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT") + + remaining_length = 0 + + command = DISCONNECT + packet = bytearray() + packet.append(command) + + if self._protocol == MQTTv5: + if properties is not None or reasoncode is not None: + if reasoncode is None: + reasoncode = ReasonCode(DISCONNECT >> 4, identifier=0) + remaining_length += 1 + if properties is not None: + packed_props = properties.pack() + remaining_length += len(packed_props) + + self._pack_remaining_length(packet, remaining_length) + + if self._protocol == MQTTv5: + if reasoncode is not None: + packet += reasoncode.pack() + if properties is not None: + packet += packed_props + + return self._packet_queue(command, packet, 0, 0) + + def _send_subscribe( + self, + dup: int, + topics: Sequence[tuple[bytes, SubscribeOptions | int]], + properties: Properties | None = None, + ) -> tuple[MQTTErrorCode, int]: + remaining_length = 2 + if self._protocol == MQTTv5: + if properties is None: + packed_subscribe_properties = b'\x00' + else: + packed_subscribe_properties = properties.pack() + remaining_length += len(packed_subscribe_properties) + for t, _ in topics: + remaining_length += 2 + len(t) + 1 + + command = SUBSCRIBE | (dup << 3) | 0x2 + packet = bytearray() + packet.append(command) + self._pack_remaining_length(packet, remaining_length) + local_mid = self._mid_generate() + packet.extend(struct.pack("!H", local_mid)) + + if self._protocol == MQTTv5: + packet += packed_subscribe_properties + + for t, q in topics: + self._pack_str16(packet, t) + if self._protocol == MQTTv5: + packet += q.pack() # type: ignore + else: + packet.append(q) # type: ignore + + self._easy_log( + MQTT_LOG_DEBUG, + "Sending SUBSCRIBE (d%d, m%d) %s", + dup, + local_mid, + topics, + ) + return (self._packet_queue(command, packet, local_mid, 1), local_mid) + + def _send_unsubscribe( + self, + dup: int, + topics: list[bytes], + properties: Properties | None = None, + ) -> tuple[MQTTErrorCode, int]: + remaining_length = 2 + if self._protocol == MQTTv5: + if properties is None: + packed_unsubscribe_properties = b'\x00' + else: + packed_unsubscribe_properties = properties.pack() + remaining_length += len(packed_unsubscribe_properties) + for t in topics: + remaining_length += 2 + len(t) + + command = UNSUBSCRIBE | (dup << 3) | 0x2 + packet = bytearray() + packet.append(command) + self._pack_remaining_length(packet, remaining_length) + local_mid = self._mid_generate() + packet.extend(struct.pack("!H", local_mid)) + + if self._protocol == MQTTv5: + packet += packed_unsubscribe_properties + + for t in topics: + self._pack_str16(packet, t) + + # topics_repr = ", ".join("'"+topic.decode('utf8')+"'" for topic in topics) + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending UNSUBSCRIBE (d%d, m%d) %s %s", + dup, + local_mid, + properties, + topics, + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending UNSUBSCRIBE (d%d, m%d) %s", + dup, + local_mid, + topics, + ) + return (self._packet_queue(command, packet, local_mid, 1), local_mid) + + def _check_clean_session(self) -> bool: + if self._protocol == MQTTv5: + if self._clean_start == MQTT_CLEAN_START_FIRST_ONLY: + return self._mqttv5_first_connect + else: + return self._clean_start # type: ignore + else: + return self._clean_session + + def _messages_reconnect_reset_out(self) -> None: + with self._out_message_mutex: + self._inflight_messages = 0 + for m in self._out_messages.values(): + m.timestamp = 0 + if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages: + if m.qos == 0: + m.state = mqtt_ms_publish + elif m.qos == 1: + # self._inflight_messages = self._inflight_messages + 1 + if m.state == mqtt_ms_wait_for_puback: + m.dup = True + m.state = mqtt_ms_publish + elif m.qos == 2: + # self._inflight_messages = self._inflight_messages + 1 + if self._check_clean_session(): + if m.state != mqtt_ms_publish: + m.dup = True + m.state = mqtt_ms_publish + else: + if m.state == mqtt_ms_wait_for_pubcomp: + m.state = mqtt_ms_resend_pubrel + else: + if m.state == mqtt_ms_wait_for_pubrec: + m.dup = True + m.state = mqtt_ms_publish + else: + m.state = mqtt_ms_queued + + def _messages_reconnect_reset_in(self) -> None: + with self._in_message_mutex: + if self._check_clean_session(): + self._in_messages = collections.OrderedDict() + return + for m in self._in_messages.values(): + m.timestamp = 0 + if m.qos != 2: + self._in_messages.pop(m.mid) + else: + # Preserve current state + pass + + def _messages_reconnect_reset(self) -> None: + self._messages_reconnect_reset_out() + self._messages_reconnect_reset_in() + + def _packet_queue( + self, + command: int, + packet: bytes, + mid: int, + qos: int, + info: MQTTMessageInfo | None = None, + ) -> MQTTErrorCode: + mpkt: _OutPacket = { + "command": command, + "mid": mid, + "qos": qos, + "pos": 0, + "to_process": len(packet), + "packet": packet, + "info": info, + } + + self._out_packet.append(mpkt) + + # Write a single byte to sockpairW (connected to sockpairR) to break + # out of select() if in threaded mode. + if self._sockpairW is not None: + try: + self._sockpairW.send(sockpair_data) + except BlockingIOError: + pass + + # If we have an external event loop registered, use that instead + # of calling loop_write() directly. + if self._thread is None and self._on_socket_register_write is None: + if self._in_callback_mutex.acquire(False): + self._in_callback_mutex.release() + return self.loop_write() + + self._call_socket_register_write() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _packet_handle(self) -> MQTTErrorCode: + cmd = self._in_packet['command'] & 0xF0 + if cmd == PINGREQ: + return self._handle_pingreq() + elif cmd == PINGRESP: + return self._handle_pingresp() + elif cmd == PUBACK: + return self._handle_pubackcomp("PUBACK") + elif cmd == PUBCOMP: + return self._handle_pubackcomp("PUBCOMP") + elif cmd == PUBLISH: + return self._handle_publish() + elif cmd == PUBREC: + return self._handle_pubrec() + elif cmd == PUBREL: + return self._handle_pubrel() + elif cmd == CONNACK: + return self._handle_connack() + elif cmd == SUBACK: + self._handle_suback() + return MQTTErrorCode.MQTT_ERR_SUCCESS + elif cmd == UNSUBACK: + return self._handle_unsuback() + elif cmd == DISCONNECT and self._protocol == MQTTv5: # only allowed in MQTT 5.0 + self._handle_disconnect() + return MQTTErrorCode.MQTT_ERR_SUCCESS + else: + # If we don't recognise the command, return an error straight away. + self._easy_log(MQTT_LOG_ERR, "Error: Unrecognised command %s", cmd) + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + def _handle_pingreq(self) -> MQTTErrorCode: + if self._in_packet['remaining_length'] != 0: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + self._easy_log(MQTT_LOG_DEBUG, "Received PINGREQ") + return self._send_pingresp() + + def _handle_pingresp(self) -> MQTTErrorCode: + if self._in_packet['remaining_length'] != 0: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + # No longer waiting for a PINGRESP. + self._ping_t = 0 + self._easy_log(MQTT_LOG_DEBUG, "Received PINGRESP") + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_connack(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + if self._protocol == MQTTv5: + (flags, result) = struct.unpack( + "!BB", self._in_packet['packet'][:2]) + if result == 1: + # This is probably a failure from a broker that doesn't support + # MQTT v5. + reason = ReasonCode(CONNACK >> 4, aName="Unsupported protocol version") + properties = None + else: + reason = ReasonCode(CONNACK >> 4, identifier=result) + properties = Properties(CONNACK >> 4) + properties.unpack(self._in_packet['packet'][2:]) + else: + (flags, result) = struct.unpack("!BB", self._in_packet['packet']) + reason = convert_connack_rc_to_reason_code(result) + properties = None + if self._protocol == MQTTv311: + if result == CONNACK_REFUSED_PROTOCOL_VERSION: + if not self._reconnect_on_failure: + return MQTT_ERR_PROTOCOL + self._easy_log( + MQTT_LOG_DEBUG, + "Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.", + flags, result + ) + # Downgrade to MQTT v3.1 + self._protocol = MQTTv31 + return self.reconnect() + elif (result == CONNACK_REFUSED_IDENTIFIER_REJECTED + and self._client_id == b''): + if not self._reconnect_on_failure: + return MQTT_ERR_PROTOCOL + self._easy_log( + MQTT_LOG_DEBUG, + "Received CONNACK (%s, %s), attempting to use non-empty CID", + flags, result, + ) + self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8") + return self.reconnect() + + if result == 0: + self._state = _ConnectionState.MQTT_CS_CONNECTED + self._reconnect_delay = None + + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, "Received CONNACK (%s, %s) properties=%s", flags, reason, properties) + else: + self._easy_log( + MQTT_LOG_DEBUG, "Received CONNACK (%s, %s)", flags, result) + + # it won't be the first successful connect any more + self._mqttv5_first_connect = False + + with self._callback_mutex: + on_connect = self.on_connect + + if on_connect: + flags_dict = {} + flags_dict['session present'] = flags & 0x01 + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_connect = cast(CallbackOnConnect_v1_mqtt5, on_connect) + + on_connect(self, self._userdata, + flags_dict, reason, properties) + else: + on_connect = cast(CallbackOnConnect_v1_mqtt3, on_connect) + + on_connect( + self, self._userdata, flags_dict, result) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_connect = cast(CallbackOnConnect_v2, on_connect) + + connect_flags = ConnectFlags( + session_present=flags_dict['session present'] > 0 + ) + + if properties is None: + properties = Properties(PacketTypes.CONNACK) + + on_connect( + self, + self._userdata, + connect_flags, + reason, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_connect: %s', err) + if not self.suppress_exceptions: + raise + + if result == 0: + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + with self._out_message_mutex: + for m in self._out_messages.values(): + m.timestamp = time_func() + if m.state == mqtt_ms_queued: + self.loop_write() # Process outgoing messages that have just been queued up + return MQTT_ERR_SUCCESS + + if m.qos == 0: + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + elif m.qos == 1: + if m.state == mqtt_ms_publish: + self._inflight_messages += 1 + m.state = mqtt_ms_wait_for_puback + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + elif m.qos == 2: + if m.state == mqtt_ms_publish: + self._inflight_messages += 1 + m.state = mqtt_ms_wait_for_pubrec + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + elif m.state == mqtt_ms_resend_pubrel: + self._inflight_messages += 1 + m.state = mqtt_ms_wait_for_pubcomp + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_pubrel(m.mid) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + self.loop_write() # Process outgoing messages that have just been queued up + + return rc + elif result > 0 and result < 6: + return MQTTErrorCode.MQTT_ERR_CONN_REFUSED + else: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + def _handle_disconnect(self) -> None: + packet_type = DISCONNECT >> 4 + reasonCode = properties = None + if self._in_packet['remaining_length'] > 2: + reasonCode = ReasonCode(packet_type) + reasonCode.unpack(self._in_packet['packet']) + if self._in_packet['remaining_length'] > 3: + properties = Properties(packet_type) + props, props_len = properties.unpack( + self._in_packet['packet'][1:]) + self._easy_log(MQTT_LOG_DEBUG, "Received DISCONNECT %s %s", + reasonCode, + properties + ) + + self._sock_close() + self._do_on_disconnect( + packet_from_broker=True, + v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, # If reason is absent (remaining length < 1), it means normal disconnection + reason=reasonCode, + properties=properties, + ) + + def _handle_suback(self) -> None: + self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK") + pack_format = f"!H{len(self._in_packet['packet']) - 2}s" + (mid, packet) = struct.unpack(pack_format, self._in_packet['packet']) + + if self._protocol == MQTTv5: + properties = Properties(SUBACK >> 4) + props, props_len = properties.unpack(packet) + reasoncodes = [ReasonCode(SUBACK >> 4, identifier=c) for c in packet[props_len:]] + else: + pack_format = f"!{'B' * len(packet)}" + granted_qos = struct.unpack(pack_format, packet) + reasoncodes = [ReasonCode(SUBACK >> 4, identifier=c) for c in granted_qos] + properties = Properties(SUBACK >> 4) + + with self._callback_mutex: + on_subscribe = self.on_subscribe + + if on_subscribe: + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_subscribe = cast(CallbackOnSubscribe_v1_mqtt5, on_subscribe) + + on_subscribe( + self, self._userdata, mid, reasoncodes, properties) + else: + on_subscribe = cast(CallbackOnSubscribe_v1_mqtt3, on_subscribe) + + on_subscribe( + self, self._userdata, mid, granted_qos) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_subscribe = cast(CallbackOnSubscribe_v2, on_subscribe) + + on_subscribe( + self, + self._userdata, + mid, + reasoncodes, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_subscribe: %s', err) + if not self.suppress_exceptions: + raise + + def _handle_publish(self) -> MQTTErrorCode: + header = self._in_packet['command'] + message = MQTTMessage() + message.dup = ((header & 0x08) >> 3) != 0 + message.qos = (header & 0x06) >> 1 + message.retain = (header & 0x01) != 0 + + pack_format = f"!H{len(self._in_packet['packet']) - 2}s" + (slen, packet) = struct.unpack(pack_format, self._in_packet['packet']) + pack_format = f"!{slen}s{len(packet) - slen}s" + (topic, packet) = struct.unpack(pack_format, packet) + + if self._protocol != MQTTv5 and len(topic) == 0: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + # Handle topics with invalid UTF-8 + # This replaces an invalid topic with a message and the hex + # representation of the topic for logging. When the user attempts to + # access message.topic in the callback, an exception will be raised. + try: + print_topic = topic.decode('utf-8') + except UnicodeDecodeError: + print_topic = f"TOPIC WITH INVALID UTF-8: {topic!r}" + + message.topic = topic + + if message.qos > 0: + pack_format = f"!H{len(packet) - 2}s" + (message.mid, packet) = struct.unpack(pack_format, packet) + + if self._protocol == MQTTv5: + message.properties = Properties(PUBLISH >> 4) + props, props_len = message.properties.unpack(packet) + packet = packet[props_len:] + + message.payload = packet + + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)", + message.dup, message.qos, message.retain, message.mid, + print_topic, message.properties, len(message.payload) + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)", + message.dup, message.qos, message.retain, message.mid, + print_topic, len(message.payload) + ) + + message.timestamp = time_func() + if message.qos == 0: + self._handle_on_message(message) + return MQTTErrorCode.MQTT_ERR_SUCCESS + elif message.qos == 1: + self._handle_on_message(message) + if self._manual_ack: + return MQTTErrorCode.MQTT_ERR_SUCCESS + else: + return self._send_puback(message.mid) + elif message.qos == 2: + + rc = self._send_pubrec(message.mid) + + message.state = mqtt_ms_wait_for_pubrel + with self._in_message_mutex: + self._in_messages[message.mid] = message + + return rc + else: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + def ack(self, mid: int, qos: int) -> MQTTErrorCode: + """ + send an acknowledgement for a given message id (stored in :py:attr:`message.mid `). + only useful in QoS>=1 and ``manual_ack=True`` (option of `Client`) + """ + if self._manual_ack : + if qos == 1: + return self._send_puback(mid) + elif qos == 2: + return self._send_pubcomp(mid) + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def manual_ack_set(self, on: bool) -> None: + """ + The paho library normally acknowledges messages as soon as they are delivered to the caller. + If manual_ack is turned on, then the caller MUST manually acknowledge every message once + application processing is complete using `ack()` + """ + self._manual_ack = on + + + def _handle_pubrel(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] > 2: + reasonCode = ReasonCode(PUBREL >> 4) + reasonCode.unpack(self._in_packet['packet'][2:]) + if self._in_packet['remaining_length'] > 3: + properties = Properties(PUBREL >> 4) + props, props_len = properties.unpack( + self._in_packet['packet'][3:]) + self._easy_log(MQTT_LOG_DEBUG, "Received PUBREL (Mid: %d)", mid) + + with self._in_message_mutex: + if mid in self._in_messages: + # Only pass the message on if we have removed it from the queue - this + # prevents multiple callbacks for the same message. + message = self._in_messages.pop(mid) + self._handle_on_message(message) + self._inflight_messages -= 1 + if self._max_inflight_messages > 0: + with self._out_message_mutex: + rc = self._update_inflight() + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + + # FIXME: this should only be done if the message is known + # If unknown it's a protocol error and we should close the connection. + # But since we don't have (on disk) persistence for the session, it + # is possible that we must known about this message. + # Choose to acknowledge this message (thus losing a message) but + # avoid hanging. See #284. + if self._manual_ack: + return MQTTErrorCode.MQTT_ERR_SUCCESS + else: + return self._send_pubcomp(mid) + + def _update_inflight(self) -> MQTTErrorCode: + # Dont lock message_mutex here + for m in self._out_messages.values(): + if self._inflight_messages < self._max_inflight_messages: + if m.qos > 0 and m.state == mqtt_ms_queued: + self._inflight_messages += 1 + if m.qos == 1: + m.state = mqtt_ms_wait_for_puback + elif m.qos == 2: + m.state = mqtt_ms_wait_for_pubrec + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties, + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + else: + return MQTTErrorCode.MQTT_ERR_SUCCESS + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_pubrec(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] > 2: + reasonCode = ReasonCode(PUBREC >> 4) + reasonCode.unpack(self._in_packet['packet'][2:]) + if self._in_packet['remaining_length'] > 3: + properties = Properties(PUBREC >> 4) + props, props_len = properties.unpack( + self._in_packet['packet'][3:]) + self._easy_log(MQTT_LOG_DEBUG, "Received PUBREC (Mid: %d)", mid) + + with self._out_message_mutex: + if mid in self._out_messages: + msg = self._out_messages[mid] + msg.state = mqtt_ms_wait_for_pubcomp + msg.timestamp = time_func() + return self._send_pubrel(mid) + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_unsuback(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 4: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + if self._protocol == MQTTv5: + packet = self._in_packet['packet'][2:] + properties = Properties(UNSUBACK >> 4) + props, props_len = properties.unpack(packet) + reasoncodes_list = [ + ReasonCode(UNSUBACK >> 4, identifier=c) + for c in packet[props_len:] + ] + else: + reasoncodes_list = [] + properties = Properties(UNSUBACK >> 4) + + self._easy_log(MQTT_LOG_DEBUG, "Received UNSUBACK (Mid: %d)", mid) + with self._callback_mutex: + on_unsubscribe = self.on_unsubscribe + + if on_unsubscribe: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt5, on_unsubscribe) + + reasoncodes: ReasonCode | list[ReasonCode] = reasoncodes_list + if len(reasoncodes_list) == 1: + reasoncodes = reasoncodes_list[0] + + on_unsubscribe( + self, self._userdata, mid, properties, reasoncodes) + else: + on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt3, on_unsubscribe) + + on_unsubscribe(self, self._userdata, mid) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_unsubscribe = cast(CallbackOnUnsubscribe_v2, on_unsubscribe) + + if properties is None: + properties = Properties(PacketTypes.CONNACK) + + on_unsubscribe( + self, + self._userdata, + mid, + reasoncodes_list, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_unsubscribe: %s', err) + if not self.suppress_exceptions: + raise + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _do_on_disconnect( + self, + packet_from_broker: bool, + v1_rc: MQTTErrorCode, + reason: ReasonCode | None = None, + properties: Properties | None = None, + ) -> None: + with self._callback_mutex: + on_disconnect = self.on_disconnect + + if on_disconnect: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_disconnect = cast(CallbackOnDisconnect_v1_mqtt5, on_disconnect) + + if packet_from_broker: + on_disconnect(self, self._userdata, reason, properties) + else: + on_disconnect(self, self._userdata, v1_rc, None) + else: + on_disconnect = cast(CallbackOnDisconnect_v1_mqtt3, on_disconnect) + + on_disconnect(self, self._userdata, v1_rc) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_disconnect = cast(CallbackOnDisconnect_v2, on_disconnect) + + disconnect_flags = DisconnectFlags( + is_disconnect_packet_from_server=packet_from_broker + ) + + if reason is None: + reason = convert_disconnect_error_code_to_reason_code(v1_rc) + + if properties is None: + properties = Properties(PacketTypes.DISCONNECT) + + on_disconnect( + self, + self._userdata, + disconnect_flags, + reason, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_disconnect: %s', err) + if not self.suppress_exceptions: + raise + + def _do_on_publish(self, mid: int, reason_code: ReasonCode, properties: Properties) -> MQTTErrorCode: + with self._callback_mutex: + on_publish = self.on_publish + + if on_publish: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + on_publish = cast(CallbackOnPublish_v1, on_publish) + + on_publish(self, self._userdata, mid) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_publish = cast(CallbackOnPublish_v2, on_publish) + + on_publish( + self, + self._userdata, + mid, + reason_code, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err) + if not self.suppress_exceptions: + raise + + msg = self._out_messages.pop(mid) + msg.info._set_as_published() + if msg.qos > 0: + self._inflight_messages -= 1 + if self._max_inflight_messages > 0: + rc = self._update_inflight() + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_pubackcomp( + self, cmd: Literal['PUBACK'] | Literal['PUBCOMP'] + ) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + packet_type_enum = PUBACK if cmd == "PUBACK" else PUBCOMP + packet_type = packet_type_enum.value >> 4 + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + reasonCode = ReasonCode(packet_type) + properties = Properties(packet_type) + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] > 2: + reasonCode.unpack(self._in_packet['packet'][2:]) + if self._in_packet['remaining_length'] > 3: + props, props_len = properties.unpack( + self._in_packet['packet'][3:]) + self._easy_log(MQTT_LOG_DEBUG, "Received %s (Mid: %d)", cmd, mid) + + with self._out_message_mutex: + if mid in self._out_messages: + # Only inform the client the message has been sent once. + rc = self._do_on_publish(mid, reasonCode, properties) + return rc + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_on_message(self, message: MQTTMessage) -> None: + + try: + topic = message.topic + except UnicodeDecodeError: + topic = None + + on_message_callbacks = [] + with self._callback_mutex: + if topic is not None: + on_message_callbacks = list(self._on_message_filtered.iter_match(message.topic)) + + if len(on_message_callbacks) == 0: + on_message = self.on_message + else: + on_message = None + + for callback in on_message_callbacks: + with self._in_callback_mutex: + try: + callback(self, self._userdata, message) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, + 'Caught exception in user defined callback function %s: %s', + callback.__name__, + err + ) + if not self.suppress_exceptions: + raise + + if on_message: + with self._in_callback_mutex: + try: + on_message(self, self._userdata, message) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_message: %s', err) + if not self.suppress_exceptions: + raise + + + def _handle_on_connect_fail(self) -> None: + with self._callback_mutex: + on_connect_fail = self.on_connect_fail + + if on_connect_fail: + with self._in_callback_mutex: + try: + on_connect_fail(self, self._userdata) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_connect_fail: %s', err) + + def _thread_main(self) -> None: + try: + self.loop_forever(retry_first_connection=True) + finally: + self._thread = None + + def _reconnect_wait(self) -> None: + # See reconnect_delay_set for details + now = time_func() + with self._reconnect_delay_mutex: + if self._reconnect_delay is None: + self._reconnect_delay = self._reconnect_min_delay + else: + self._reconnect_delay = min( + self._reconnect_delay * 2, + self._reconnect_max_delay, + ) + + target_time = now + self._reconnect_delay + + remaining = target_time - now + while (self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) + and not self._thread_terminate + and remaining > 0): + + time.sleep(min(remaining, 1)) + remaining = target_time - time_func() + + @staticmethod + def _proxy_is_valid(p) -> bool: # type: ignore[no-untyped-def] + def check(t, a) -> bool: # type: ignore[no-untyped-def] + return (socks is not None and + t in {socks.HTTP, socks.SOCKS4, socks.SOCKS5} and a) + + if isinstance(p, dict): + return check(p.get("proxy_type"), p.get("proxy_addr")) + elif isinstance(p, (list, tuple)): + return len(p) == 6 and check(p[0], p[1]) + else: + return False + + def _get_proxy(self) -> dict[str, Any] | None: + if socks is None: + return None + + # First, check if the user explicitly passed us a proxy to use + if self._proxy_is_valid(self._proxy): + return self._proxy + + # Next, check for an mqtt_proxy environment variable as long as the host + # we're trying to connect to isn't listed under the no_proxy environment + # variable (matches built-in module urllib's behavior) + if not (hasattr(urllib.request, "proxy_bypass") and + urllib.request.proxy_bypass(self._host)): + env_proxies = urllib.request.getproxies() + if "mqtt" in env_proxies: + parts = urllib.parse.urlparse(env_proxies["mqtt"]) + if parts.scheme == "http": + proxy = { + "proxy_type": socks.HTTP, + "proxy_addr": parts.hostname, + "proxy_port": parts.port + } + return proxy + elif parts.scheme == "socks": + proxy = { + "proxy_type": socks.SOCKS5, + "proxy_addr": parts.hostname, + "proxy_port": parts.port + } + return proxy + + # Finally, check if the user has monkeypatched the PySocks library with + # a default proxy + socks_default = socks.get_default_proxy() + if self._proxy_is_valid(socks_default): + proxy_keys = ("proxy_type", "proxy_addr", "proxy_port", + "proxy_rdns", "proxy_username", "proxy_password") + return dict(zip(proxy_keys, socks_default)) + + # If we didn't find a proxy through any of the above methods, return + # None to indicate that the connection should be handled normally + return None + + def _create_socket(self) -> SocketLike: + if self._transport == "unix": + sock = self._create_unix_socket_connection() + else: + sock = self._create_socket_connection() + + if self._ssl: + sock = self._ssl_wrap_socket(sock) + + if self._transport == "websockets": + sock.settimeout(self._keepalive) + return _WebsocketWrapper( + socket=sock, + host=self._host, + port=self._port, + is_ssl=self._ssl, + path=self._websocket_path, + extra_headers=self._websocket_extra_headers, + ) + + return sock + + def _create_unix_socket_connection(self) -> _socket.socket: + unix_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + unix_socket.connect(self._host) + return unix_socket + + def _create_socket_connection(self) -> _socket.socket: + proxy = self._get_proxy() + addr = (self._host, self._port) + source = (self._bind_address, self._bind_port) + + if proxy: + return socks.create_connection(addr, timeout=self._connect_timeout, source_address=source, **proxy) + else: + return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source) + + def _ssl_wrap_socket(self, tcp_sock: _socket.socket) -> ssl.SSLSocket: + if self._ssl_context is None: + raise ValueError( + "Impossible condition. _ssl_context should never be None if _ssl is True" + ) + + verify_host = not self._tls_insecure + try: + # Try with server_hostname, even it's not supported in certain scenarios + ssl_sock = self._ssl_context.wrap_socket( + tcp_sock, + server_hostname=self._host, + do_handshake_on_connect=False, + ) + except ssl.CertificateError: + # CertificateError is derived from ValueError + raise + except ValueError: + # Python version requires SNI in order to handle server_hostname, but SNI is not available + ssl_sock = self._ssl_context.wrap_socket( + tcp_sock, + do_handshake_on_connect=False, + ) + else: + # If SSL context has already checked hostname, then don't need to do it again + if getattr(self._ssl_context, 'check_hostname', False): # type: ignore + verify_host = False + + ssl_sock.settimeout(self._keepalive) + ssl_sock.do_handshake() + + if verify_host: + # TODO: this type error is a true error: + # error: Module has no attribute "match_hostname" [attr-defined] + # Python 3.12 no longer have this method. + ssl.match_hostname(ssl_sock.getpeercert(), self._host) # type: ignore + + return ssl_sock + +class _WebsocketWrapper: + OPCODE_CONTINUATION = 0x0 + OPCODE_TEXT = 0x1 + OPCODE_BINARY = 0x2 + OPCODE_CONNCLOSE = 0x8 + OPCODE_PING = 0x9 + OPCODE_PONG = 0xa + + def __init__( + self, + socket: socket.socket | ssl.SSLSocket, + host: str, + port: int, + is_ssl: bool, + path: str, + extra_headers: WebSocketHeaders | None, + ): + self.connected = False + + self._ssl = is_ssl + self._host = host + self._port = port + self._socket = socket + self._path = path + + self._sendbuffer = bytearray() + self._readbuffer = bytearray() + + self._requested_size = 0 + self._payload_head = 0 + self._readbuffer_head = 0 + + self._do_handshake(extra_headers) + + def __del__(self) -> None: + self._sendbuffer = bytearray() + self._readbuffer = bytearray() + + def _do_handshake(self, extra_headers: WebSocketHeaders | None) -> None: + + sec_websocket_key = uuid.uuid4().bytes + sec_websocket_key = base64.b64encode(sec_websocket_key) + + if self._ssl: + default_port = 443 + http_schema = "https" + else: + default_port = 80 + http_schema = "http" + + if default_port == self._port: + host_port = f"{self._host}" + else: + host_port = f"{self._host}:{self._port}" + + websocket_headers = { + "Host": host_port, + "Upgrade": "websocket", + "Connection": "Upgrade", + "Origin": f"{http_schema}://{host_port}", + "Sec-WebSocket-Key": sec_websocket_key.decode("utf8"), + "Sec-Websocket-Version": "13", + "Sec-Websocket-Protocol": "mqtt", + } + + # This is checked in ws_set_options so it will either be None, a + # dictionary, or a callable + if isinstance(extra_headers, dict): + websocket_headers.update(extra_headers) + elif callable(extra_headers): + websocket_headers = extra_headers(websocket_headers) + + header = "\r\n".join([ + f"GET {self._path} HTTP/1.1", + "\r\n".join(f"{i}: {j}" for i, j in websocket_headers.items()), + "\r\n", + ]).encode("utf8") + + self._socket.send(header) + + has_secret = False + has_upgrade = False + + while True: + # read HTTP response header as lines + try: + byte = self._socket.recv(1) + except ConnectionResetError: + byte = b"" + + self._readbuffer.extend(byte) + + # line end + if byte == b"\n": + if len(self._readbuffer) > 2: + # check upgrade + if b"connection" in str(self._readbuffer).lower().encode('utf-8'): + if b"upgrade" not in str(self._readbuffer).lower().encode('utf-8'): + raise WebsocketConnectionError( + "WebSocket handshake error, connection not upgraded") + else: + has_upgrade = True + + # check key hash + if b"sec-websocket-accept" in str(self._readbuffer).lower().encode('utf-8'): + GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + server_hash_str = self._readbuffer.decode( + 'utf-8').split(": ", 1)[1] + server_hash = server_hash_str.strip().encode('utf-8') + + client_hash_key = sec_websocket_key.decode('utf-8') + GUID + # Use of SHA-1 is OK here; it's according to the Websocket spec. + client_hash_digest = hashlib.sha1(client_hash_key.encode('utf-8')) # noqa: S324 + client_hash = base64.b64encode(client_hash_digest.digest()) + + if server_hash != client_hash: + raise WebsocketConnectionError( + "WebSocket handshake error, invalid secret key") + else: + has_secret = True + else: + # ending linebreak + break + + # reset linebuffer + self._readbuffer = bytearray() + + # connection reset + elif not byte: + raise WebsocketConnectionError("WebSocket handshake error") + + if not has_upgrade or not has_secret: + raise WebsocketConnectionError("WebSocket handshake error") + + self._readbuffer = bytearray() + self.connected = True + + def _create_frame( + self, opcode: int, data: bytearray, do_masking: int = 1 + ) -> bytearray: + header = bytearray() + length = len(data) + + mask_key = bytearray(os.urandom(4)) + mask_flag = do_masking + + # 1 << 7 is the final flag, we don't send continuated data + header.append(1 << 7 | opcode) + + if length < 126: + header.append(mask_flag << 7 | length) + + elif length < 65536: + header.append(mask_flag << 7 | 126) + header += struct.pack("!H", length) + + elif length < 0x8000000000000001: + header.append(mask_flag << 7 | 127) + header += struct.pack("!Q", length) + + else: + raise ValueError("Maximum payload size is 2^63") + + if mask_flag == 1: + for index in range(length): + data[index] ^= mask_key[index % 4] + data = mask_key + data + + return header + data + + def _buffered_read(self, length: int) -> bytearray: + + # try to recv and store needed bytes + wanted_bytes = length - (len(self._readbuffer) - self._readbuffer_head) + if wanted_bytes > 0: + + data = self._socket.recv(wanted_bytes) + + if not data: + raise ConnectionAbortedError + else: + self._readbuffer.extend(data) + + if len(data) < wanted_bytes: + raise BlockingIOError + + self._readbuffer_head += length + return self._readbuffer[self._readbuffer_head - length:self._readbuffer_head] + + def _recv_impl(self, length: int) -> bytes: + + # try to decode websocket payload part from data + try: + + self._readbuffer_head = 0 + + result = b"" + + chunk_startindex = self._payload_head + chunk_endindex = self._payload_head + length + + header1 = self._buffered_read(1) + header2 = self._buffered_read(1) + + opcode = (header1[0] & 0x0f) + maskbit = (header2[0] & 0x80) == 0x80 + lengthbits = (header2[0] & 0x7f) + payload_length = lengthbits + mask_key = None + + # read length + if lengthbits == 0x7e: + + value = self._buffered_read(2) + payload_length, = struct.unpack("!H", value) + + elif lengthbits == 0x7f: + + value = self._buffered_read(8) + payload_length, = struct.unpack("!Q", value) + + # read mask + if maskbit: + mask_key = self._buffered_read(4) + + # if frame payload is shorter than the requested data, read only the possible part + readindex = chunk_endindex + if payload_length < readindex: + readindex = payload_length + + if readindex > 0: + # get payload chunk + payload = self._buffered_read(readindex) + + # unmask only the needed part + if mask_key is not None: + for index in range(chunk_startindex, readindex): + payload[index] ^= mask_key[index % 4] + + result = payload[chunk_startindex:readindex] + self._payload_head = readindex + else: + payload = bytearray() + + # check if full frame arrived and reset readbuffer and payloadhead if needed + if readindex == payload_length: + self._readbuffer = bytearray() + self._payload_head = 0 + + # respond to non-binary opcodes, their arrival is not guaranteed because of non-blocking sockets + if opcode == _WebsocketWrapper.OPCODE_CONNCLOSE: + frame = self._create_frame( + _WebsocketWrapper.OPCODE_CONNCLOSE, payload, 0) + self._socket.send(frame) + + if opcode == _WebsocketWrapper.OPCODE_PING: + frame = self._create_frame( + _WebsocketWrapper.OPCODE_PONG, payload, 0) + self._socket.send(frame) + + # This isn't *proper* handling of continuation frames, but given + # that we only support binary frames, it is *probably* good enough. + if (opcode == _WebsocketWrapper.OPCODE_BINARY or opcode == _WebsocketWrapper.OPCODE_CONTINUATION) \ + and payload_length > 0: + return result + else: + raise BlockingIOError + + except ConnectionError: + self.connected = False + return b'' + + def _send_impl(self, data: bytes) -> int: + + # if previous frame was sent successfully + if len(self._sendbuffer) == 0: + # create websocket frame + frame = self._create_frame( + _WebsocketWrapper.OPCODE_BINARY, bytearray(data)) + self._sendbuffer.extend(frame) + self._requested_size = len(data) + + # try to write out as much as possible + length = self._socket.send(self._sendbuffer) + + self._sendbuffer = self._sendbuffer[length:] + + if len(self._sendbuffer) == 0: + # buffer sent out completely, return with payload's size + return self._requested_size + else: + # couldn't send whole data, request the same data again with 0 as sent length + return 0 + + def recv(self, length: int) -> bytes: + return self._recv_impl(length) + + def read(self, length: int) -> bytes: + return self._recv_impl(length) + + def send(self, data: bytes) -> int: + return self._send_impl(data) + + def write(self, data: bytes) -> int: + return self._send_impl(data) + + def close(self) -> None: + self._socket.close() + + def fileno(self) -> int: + return self._socket.fileno() + + def pending(self) -> int: + # Fix for bug #131: a SSL socket may still have data available + # for reading without select() being aware of it. + if self._ssl: + return self._socket.pending() # type: ignore[union-attr] + else: + # normal socket rely only on select() + return 0 + + def setblocking(self, flag: bool) -> None: + self._socket.setblocking(flag) diff --git a/sbapp/mqtt/enums.py b/sbapp/mqtt/enums.py new file mode 100644 index 0000000..5428769 --- /dev/null +++ b/sbapp/mqtt/enums.py @@ -0,0 +1,113 @@ +import enum + + +class MQTTErrorCode(enum.IntEnum): + MQTT_ERR_AGAIN = -1 + MQTT_ERR_SUCCESS = 0 + MQTT_ERR_NOMEM = 1 + MQTT_ERR_PROTOCOL = 2 + MQTT_ERR_INVAL = 3 + MQTT_ERR_NO_CONN = 4 + MQTT_ERR_CONN_REFUSED = 5 + MQTT_ERR_NOT_FOUND = 6 + MQTT_ERR_CONN_LOST = 7 + MQTT_ERR_TLS = 8 + MQTT_ERR_PAYLOAD_SIZE = 9 + MQTT_ERR_NOT_SUPPORTED = 10 + MQTT_ERR_AUTH = 11 + MQTT_ERR_ACL_DENIED = 12 + MQTT_ERR_UNKNOWN = 13 + MQTT_ERR_ERRNO = 14 + MQTT_ERR_QUEUE_SIZE = 15 + MQTT_ERR_KEEPALIVE = 16 + + +class MQTTProtocolVersion(enum.IntEnum): + MQTTv31 = 3 + MQTTv311 = 4 + MQTTv5 = 5 + + +class CallbackAPIVersion(enum.Enum): + """Defined the arguments passed to all user-callback. + + See each callbacks for details: `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`, + `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`, + `on_socket_register_write`, `on_socket_unregister_write` + """ + VERSION1 = 1 + """The version used with paho-mqtt 1.x before introducing CallbackAPIVersion. + + This version had different arguments depending if MQTTv5 or MQTTv3 was used. `Properties` & `ReasonCode` were missing + on some callback (apply only to MQTTv5). + + This version is deprecated and will be removed in version 3.0. + """ + VERSION2 = 2 + """ This version fix some of the shortcoming of previous version. + + Callback have the same signature if using MQTTv5 or MQTTv3. `ReasonCode` are used in MQTTv3. + """ + + +class MessageType(enum.IntEnum): + CONNECT = 0x10 + CONNACK = 0x20 + PUBLISH = 0x30 + PUBACK = 0x40 + PUBREC = 0x50 + PUBREL = 0x60 + PUBCOMP = 0x70 + SUBSCRIBE = 0x80 + SUBACK = 0x90 + UNSUBSCRIBE = 0xA0 + UNSUBACK = 0xB0 + PINGREQ = 0xC0 + PINGRESP = 0xD0 + DISCONNECT = 0xE0 + AUTH = 0xF0 + + +class LogLevel(enum.IntEnum): + MQTT_LOG_INFO = 0x01 + MQTT_LOG_NOTICE = 0x02 + MQTT_LOG_WARNING = 0x04 + MQTT_LOG_ERR = 0x08 + MQTT_LOG_DEBUG = 0x10 + + +class ConnackCode(enum.IntEnum): + CONNACK_ACCEPTED = 0 + CONNACK_REFUSED_PROTOCOL_VERSION = 1 + CONNACK_REFUSED_IDENTIFIER_REJECTED = 2 + CONNACK_REFUSED_SERVER_UNAVAILABLE = 3 + CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4 + CONNACK_REFUSED_NOT_AUTHORIZED = 5 + + +class _ConnectionState(enum.Enum): + MQTT_CS_NEW = enum.auto() + MQTT_CS_CONNECT_ASYNC = enum.auto() + MQTT_CS_CONNECTING = enum.auto() + MQTT_CS_CONNECTED = enum.auto() + MQTT_CS_CONNECTION_LOST = enum.auto() + MQTT_CS_DISCONNECTING = enum.auto() + MQTT_CS_DISCONNECTED = enum.auto() + + +class MessageState(enum.IntEnum): + MQTT_MS_INVALID = 0 + MQTT_MS_PUBLISH = 1 + MQTT_MS_WAIT_FOR_PUBACK = 2 + MQTT_MS_WAIT_FOR_PUBREC = 3 + MQTT_MS_RESEND_PUBREL = 4 + MQTT_MS_WAIT_FOR_PUBREL = 5 + MQTT_MS_RESEND_PUBCOMP = 6 + MQTT_MS_WAIT_FOR_PUBCOMP = 7 + MQTT_MS_SEND_PUBREC = 8 + MQTT_MS_QUEUED = 9 + + +class PahoClientMode(enum.IntEnum): + MQTT_CLIENT = 0 + MQTT_BRIDGE = 1 diff --git a/sbapp/mqtt/matcher.py b/sbapp/mqtt/matcher.py new file mode 100644 index 0000000..b73c13a --- /dev/null +++ b/sbapp/mqtt/matcher.py @@ -0,0 +1,78 @@ +class MQTTMatcher: + """Intended to manage topic filters including wildcards. + + Internally, MQTTMatcher use a prefix tree (trie) to store + values associated with filters, and has an iter_match() + method to iterate efficiently over all filters that match + some topic name.""" + + class Node: + __slots__ = '_children', '_content' + + def __init__(self): + self._children = {} + self._content = None + + def __init__(self): + self._root = self.Node() + + def __setitem__(self, key, value): + """Add a topic filter :key to the prefix tree + and associate it to :value""" + node = self._root + for sym in key.split('/'): + node = node._children.setdefault(sym, self.Node()) + node._content = value + + def __getitem__(self, key): + """Retrieve the value associated with some topic filter :key""" + try: + node = self._root + for sym in key.split('/'): + node = node._children[sym] + if node._content is None: + raise KeyError(key) + return node._content + except KeyError as ke: + raise KeyError(key) from ke + + def __delitem__(self, key): + """Delete the value associated with some topic filter :key""" + lst = [] + try: + parent, node = None, self._root + for k in key.split('/'): + parent, node = node, node._children[k] + lst.append((parent, k, node)) + # TODO + node._content = None + except KeyError as ke: + raise KeyError(key) from ke + else: # cleanup + for parent, k, node in reversed(lst): + if node._children or node._content is not None: + break + del parent._children[k] + + def iter_match(self, topic): + """Return an iterator on all values associated with filters + that match the :topic""" + lst = topic.split('/') + normal = not topic.startswith('$') + def rec(node, i=0): + if i == len(lst): + if node._content is not None: + yield node._content + else: + part = lst[i] + if part in node._children: + for content in rec(node._children[part], i + 1): + yield content + if '+' in node._children and (normal or i > 0): + for content in rec(node._children['+'], i + 1): + yield content + if '#' in node._children and (normal or i > 0): + content = node._children['#']._content + if content is not None: + yield content + return rec(self._root) diff --git a/sbapp/mqtt/packettypes.py b/sbapp/mqtt/packettypes.py new file mode 100644 index 0000000..d205149 --- /dev/null +++ b/sbapp/mqtt/packettypes.py @@ -0,0 +1,43 @@ +""" +******************************************************************* + Copyright (c) 2017, 2019 IBM Corp. + + All rights reserved. This program and the accompanying materials + are made available under the terms of the Eclipse Public License v2.0 + and Eclipse Distribution License v1.0 which accompany this distribution. + + The Eclipse Public License is available at + http://www.eclipse.org/legal/epl-v20.html + and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + + Contributors: + Ian Craggs - initial implementation and/or documentation +******************************************************************* +""" + + +class PacketTypes: + + """ + Packet types class. Includes the AUTH packet for MQTT v5.0. + + Holds constants for each packet type such as PacketTypes.PUBLISH + and packet name strings: PacketTypes.Names[PacketTypes.PUBLISH]. + + """ + + indexes = range(1, 16) + + # Packet types + CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, \ + PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, \ + PINGREQ, PINGRESP, DISCONNECT, AUTH = indexes + + # Dummy packet type for properties use - will delay only applies to will + WILLMESSAGE = 99 + + Names = ( "reserved", \ + "Connect", "Connack", "Publish", "Puback", "Pubrec", "Pubrel", \ + "Pubcomp", "Subscribe", "Suback", "Unsubscribe", "Unsuback", \ + "Pingreq", "Pingresp", "Disconnect", "Auth") diff --git a/sbapp/mqtt/properties.py b/sbapp/mqtt/properties.py new file mode 100644 index 0000000..f307b86 --- /dev/null +++ b/sbapp/mqtt/properties.py @@ -0,0 +1,421 @@ +# ******************************************************************* +# Copyright (c) 2017, 2019 IBM Corp. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Ian Craggs - initial implementation and/or documentation +# ******************************************************************* + +import struct + +from .packettypes import PacketTypes + + +class MQTTException(Exception): + pass + + +class MalformedPacket(MQTTException): + pass + + +def writeInt16(length): + # serialize a 16 bit integer to network format + return bytearray(struct.pack("!H", length)) + + +def readInt16(buf): + # deserialize a 16 bit integer from network format + return struct.unpack("!H", buf[:2])[0] + + +def writeInt32(length): + # serialize a 32 bit integer to network format + return bytearray(struct.pack("!L", length)) + + +def readInt32(buf): + # deserialize a 32 bit integer from network format + return struct.unpack("!L", buf[:4])[0] + + +def writeUTF(data): + # data could be a string, or bytes. If string, encode into bytes with utf-8 + if not isinstance(data, bytes): + data = bytes(data, "utf-8") + return writeInt16(len(data)) + data + + +def readUTF(buffer, maxlen): + if maxlen >= 2: + length = readInt16(buffer) + else: + raise MalformedPacket("Not enough data to read string length") + maxlen -= 2 + if length > maxlen: + raise MalformedPacket("Length delimited string too long") + buf = buffer[2:2+length].decode("utf-8") + # look for chars which are invalid for MQTT + for c in buf: # look for D800-DFFF in the UTF string + ord_c = ord(c) + if ord_c >= 0xD800 and ord_c <= 0xDFFF: + raise MalformedPacket("[MQTT-1.5.4-1] D800-DFFF found in UTF-8 data") + if ord_c == 0x00: # look for null in the UTF string + raise MalformedPacket("[MQTT-1.5.4-2] Null found in UTF-8 data") + if ord_c == 0xFEFF: + raise MalformedPacket("[MQTT-1.5.4-3] U+FEFF in UTF-8 data") + return buf, length+2 + + +def writeBytes(buffer): + return writeInt16(len(buffer)) + buffer + + +def readBytes(buffer): + length = readInt16(buffer) + return buffer[2:2+length], length+2 + + +class VariableByteIntegers: # Variable Byte Integer + """ + MQTT variable byte integer helper class. Used + in several places in MQTT v5.0 properties. + + """ + + @staticmethod + def encode(x): + """ + Convert an integer 0 <= x <= 268435455 into multi-byte format. + Returns the buffer converted from the integer. + """ + if not 0 <= x <= 268435455: + raise ValueError(f"Value {x!r} must be in range 0-268435455") + buffer = b'' + while 1: + digit = x % 128 + x //= 128 + if x > 0: + digit |= 0x80 + buffer += bytes([digit]) + if x == 0: + break + return buffer + + @staticmethod + def decode(buffer): + """ + Get the value of a multi-byte integer from a buffer + Return the value, and the number of bytes used. + + [MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value + """ + multiplier = 1 + value = 0 + bytes = 0 + while 1: + bytes += 1 + digit = buffer[0] + buffer = buffer[1:] + value += (digit & 127) * multiplier + if digit & 128 == 0: + break + multiplier *= 128 + return (value, bytes) + + +class Properties: + """MQTT v5.0 properties class. + + See Properties.names for a list of accepted property names along with their numeric values. + + See Properties.properties for the data type of each property. + + Example of use:: + + publish_properties = Properties(PacketTypes.PUBLISH) + publish_properties.UserProperty = ("a", "2") + publish_properties.UserProperty = ("c", "3") + + First the object is created with packet type as argument, no properties will be present at + this point. Then properties are added as attributes, the name of which is the string property + name without the spaces. + + """ + + def __init__(self, packetType): + self.packetType = packetType + self.types = ["Byte", "Two Byte Integer", "Four Byte Integer", "Variable Byte Integer", + "Binary Data", "UTF-8 Encoded String", "UTF-8 String Pair"] + + self.names = { + "Payload Format Indicator": 1, + "Message Expiry Interval": 2, + "Content Type": 3, + "Response Topic": 8, + "Correlation Data": 9, + "Subscription Identifier": 11, + "Session Expiry Interval": 17, + "Assigned Client Identifier": 18, + "Server Keep Alive": 19, + "Authentication Method": 21, + "Authentication Data": 22, + "Request Problem Information": 23, + "Will Delay Interval": 24, + "Request Response Information": 25, + "Response Information": 26, + "Server Reference": 28, + "Reason String": 31, + "Receive Maximum": 33, + "Topic Alias Maximum": 34, + "Topic Alias": 35, + "Maximum QoS": 36, + "Retain Available": 37, + "User Property": 38, + "Maximum Packet Size": 39, + "Wildcard Subscription Available": 40, + "Subscription Identifier Available": 41, + "Shared Subscription Available": 42 + } + + self.properties = { + # id: type, packets + # payload format indicator + 1: (self.types.index("Byte"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 2: (self.types.index("Four Byte Integer"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 3: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 8: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 9: (self.types.index("Binary Data"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 11: (self.types.index("Variable Byte Integer"), + [PacketTypes.PUBLISH, PacketTypes.SUBSCRIBE]), + 17: (self.types.index("Four Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.DISCONNECT]), + 18: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), + 19: (self.types.index("Two Byte Integer"), [PacketTypes.CONNACK]), + 21: (self.types.index("UTF-8 Encoded String"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), + 22: (self.types.index("Binary Data"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), + 23: (self.types.index("Byte"), + [PacketTypes.CONNECT]), + 24: (self.types.index("Four Byte Integer"), [PacketTypes.WILLMESSAGE]), + 25: (self.types.index("Byte"), [PacketTypes.CONNECT]), + 26: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), + 28: (self.types.index("UTF-8 Encoded String"), + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]), + 31: (self.types.index("UTF-8 Encoded String"), + [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, + PacketTypes.PUBREL, PacketTypes.PUBCOMP, PacketTypes.SUBACK, + PacketTypes.UNSUBACK, PacketTypes.DISCONNECT, PacketTypes.AUTH]), + 33: (self.types.index("Two Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK]), + 34: (self.types.index("Two Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK]), + 35: (self.types.index("Two Byte Integer"), [PacketTypes.PUBLISH]), + 36: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 37: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 38: (self.types.index("UTF-8 String Pair"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, + PacketTypes.PUBLISH, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, + PacketTypes.SUBSCRIBE, PacketTypes.SUBACK, + PacketTypes.UNSUBSCRIBE, PacketTypes.UNSUBACK, + PacketTypes.DISCONNECT, PacketTypes.AUTH, PacketTypes.WILLMESSAGE]), + 39: (self.types.index("Four Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK]), + 40: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 41: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 42: (self.types.index("Byte"), [PacketTypes.CONNACK]), + } + + def allowsMultiple(self, compressedName): + return self.getIdentFromName(compressedName) in [11, 38] + + def getIdentFromName(self, compressedName): + # return the identifier corresponding to the property name + result = -1 + for name in self.names.keys(): + if compressedName == name.replace(' ', ''): + result = self.names[name] + break + return result + + def __setattr__(self, name, value): + name = name.replace(' ', '') + privateVars = ["packetType", "types", "names", "properties"] + if name in privateVars: + object.__setattr__(self, name, value) + else: + # the name could have spaces in, or not. Remove spaces before assignment + if name not in [aname.replace(' ', '') for aname in self.names.keys()]: + raise MQTTException( + f"Property name must be one of {self.names.keys()}") + # check that this attribute applies to the packet type + if self.packetType not in self.properties[self.getIdentFromName(name)][1]: + raise MQTTException(f"Property {name} does not apply to packet type {PacketTypes.Names[self.packetType]}") + + # Check for forbidden values + if not isinstance(value, list): + if name in ["ReceiveMaximum", "TopicAlias"] \ + and (value < 1 or value > 65535): + + raise MQTTException(f"{name} property value must be in the range 1-65535") + elif name in ["TopicAliasMaximum"] \ + and (value < 0 or value > 65535): + + raise MQTTException(f"{name} property value must be in the range 0-65535") + elif name in ["MaximumPacketSize", "SubscriptionIdentifier"] \ + and (value < 1 or value > 268435455): + + raise MQTTException(f"{name} property value must be in the range 1-268435455") + elif name in ["RequestResponseInformation", "RequestProblemInformation", "PayloadFormatIndicator"] \ + and (value != 0 and value != 1): + + raise MQTTException( + f"{name} property value must be 0 or 1") + + if self.allowsMultiple(name): + if not isinstance(value, list): + value = [value] + if hasattr(self, name): + value = object.__getattribute__(self, name) + value + object.__setattr__(self, name, value) + + def __str__(self): + buffer = "[" + first = True + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + if not first: + buffer += ", " + buffer += f"{compressedName} : {getattr(self, compressedName)}" + first = False + buffer += "]" + return buffer + + def json(self): + data = {} + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + val = getattr(self, compressedName) + if compressedName == 'CorrelationData' and isinstance(val, bytes): + data[compressedName] = val.hex() + else: + data[compressedName] = val + return data + + def isEmpty(self): + rc = True + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + rc = False + break + return rc + + def clear(self): + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + delattr(self, compressedName) + + def writeProperty(self, identifier, type, value): + buffer = b"" + buffer += VariableByteIntegers.encode(identifier) # identifier + if type == self.types.index("Byte"): # value + buffer += bytes([value]) + elif type == self.types.index("Two Byte Integer"): + buffer += writeInt16(value) + elif type == self.types.index("Four Byte Integer"): + buffer += writeInt32(value) + elif type == self.types.index("Variable Byte Integer"): + buffer += VariableByteIntegers.encode(value) + elif type == self.types.index("Binary Data"): + buffer += writeBytes(value) + elif type == self.types.index("UTF-8 Encoded String"): + buffer += writeUTF(value) + elif type == self.types.index("UTF-8 String Pair"): + buffer += writeUTF(value[0]) + writeUTF(value[1]) + return buffer + + def pack(self): + # serialize properties into buffer for sending over network + buffer = b"" + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + identifier = self.getIdentFromName(compressedName) + attr_type = self.properties[identifier][0] + if self.allowsMultiple(compressedName): + for prop in getattr(self, compressedName): + buffer += self.writeProperty(identifier, + attr_type, prop) + else: + buffer += self.writeProperty(identifier, attr_type, + getattr(self, compressedName)) + return VariableByteIntegers.encode(len(buffer)) + buffer + + def readProperty(self, buffer, type, propslen): + if type == self.types.index("Byte"): + value = buffer[0] + valuelen = 1 + elif type == self.types.index("Two Byte Integer"): + value = readInt16(buffer) + valuelen = 2 + elif type == self.types.index("Four Byte Integer"): + value = readInt32(buffer) + valuelen = 4 + elif type == self.types.index("Variable Byte Integer"): + value, valuelen = VariableByteIntegers.decode(buffer) + elif type == self.types.index("Binary Data"): + value, valuelen = readBytes(buffer) + elif type == self.types.index("UTF-8 Encoded String"): + value, valuelen = readUTF(buffer, propslen) + elif type == self.types.index("UTF-8 String Pair"): + value, valuelen = readUTF(buffer, propslen) + buffer = buffer[valuelen:] # strip the bytes used by the value + value1, valuelen1 = readUTF(buffer, propslen - valuelen) + value = (value, value1) + valuelen += valuelen1 + return value, valuelen + + def getNameFromIdent(self, identifier): + rc = None + for name in self.names: + if self.names[name] == identifier: + rc = name + return rc + + def unpack(self, buffer): + self.clear() + # deserialize properties into attributes from buffer received from network + propslen, VBIlen = VariableByteIntegers.decode(buffer) + buffer = buffer[VBIlen:] # strip the bytes used by the VBI + propslenleft = propslen + while propslenleft > 0: # properties length is 0 if there are none + identifier, VBIlen2 = VariableByteIntegers.decode( + buffer) # property identifier + buffer = buffer[VBIlen2:] # strip the bytes used by the VBI + propslenleft -= VBIlen2 + attr_type = self.properties[identifier][0] + value, valuelen = self.readProperty( + buffer, attr_type, propslenleft) + buffer = buffer[valuelen:] # strip the bytes used by the value + propslenleft -= valuelen + propname = self.getNameFromIdent(identifier) + compressedName = propname.replace(' ', '') + if not self.allowsMultiple(compressedName) and hasattr(self, compressedName): + raise MQTTException( + f"Property '{property}' must not exist more than once") + setattr(self, propname, value) + return self, propslen + VBIlen diff --git a/sbapp/mqtt/publish.py b/sbapp/mqtt/publish.py new file mode 100644 index 0000000..333c190 --- /dev/null +++ b/sbapp/mqtt/publish.py @@ -0,0 +1,306 @@ +# Copyright (c) 2014 Roger Light +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Roger Light - initial API and implementation + +""" +This module provides some helper functions to allow straightforward publishing +of messages in a one-shot manner. In other words, they are useful for the +situation where you have a single/multiple messages you want to publish to a +broker, then disconnect and nothing else is required. +""" +from __future__ import annotations + +import collections +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any, List, Tuple, Union + +from paho.mqtt.enums import CallbackAPIVersion, MQTTProtocolVersion +from paho.mqtt.properties import Properties +from paho.mqtt.reasoncodes import ReasonCode + +from .. import mqtt +from . import client as paho + +if TYPE_CHECKING: + try: + from typing import NotRequired, Required, TypedDict # type: ignore + except ImportError: + from typing_extensions import NotRequired, Required, TypedDict + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal # type: ignore + + + + class AuthParameter(TypedDict, total=False): + username: Required[str] + password: NotRequired[str] + + + class TLSParameter(TypedDict, total=False): + ca_certs: Required[str] + certfile: NotRequired[str] + keyfile: NotRequired[str] + tls_version: NotRequired[int] + ciphers: NotRequired[str] + insecure: NotRequired[bool] + + + class MessageDict(TypedDict, total=False): + topic: Required[str] + payload: NotRequired[paho.PayloadType] + qos: NotRequired[int] + retain: NotRequired[bool] + + MessageTuple = Tuple[str, paho.PayloadType, int, bool] + + MessagesList = List[Union[MessageDict, MessageTuple]] + + +def _do_publish(client: paho.Client): + """Internal function""" + + message = client._userdata.popleft() + + if isinstance(message, dict): + client.publish(**message) + elif isinstance(message, (tuple, list)): + client.publish(*message) + else: + raise TypeError('message must be a dict, tuple, or list') + + +def _on_connect(client: paho.Client, userdata: MessagesList, flags, reason_code, properties): + """Internal v5 callback""" + if reason_code == 0: + if len(userdata) > 0: + _do_publish(client) + else: + raise mqtt.MQTTException(paho.connack_string(reason_code)) + + +def _on_publish( + client: paho.Client, userdata: collections.deque[MessagesList], mid: int, reason_codes: ReasonCode, properties: Properties, +) -> None: + """Internal callback""" + #pylint: disable=unused-argument + + if len(userdata) == 0: + client.disconnect() + else: + _do_publish(client) + + +def multiple( + msgs: MessagesList, + hostname: str = "localhost", + port: int = 1883, + client_id: str = "", + keepalive: int = 60, + will: MessageDict | None = None, + auth: AuthParameter | None = None, + tls: TLSParameter | None = None, + protocol: MQTTProtocolVersion = paho.MQTTv311, + transport: Literal["tcp", "websockets"] = "tcp", + proxy_args: Any | None = None, +) -> None: + """Publish multiple messages to a broker, then disconnect cleanly. + + This function creates an MQTT client, connects to a broker and publishes a + list of messages. Once the messages have been delivered, it disconnects + cleanly from the broker. + + :param msgs: a list of messages to publish. Each message is either a dict or a + tuple. + + If a dict, only the topic must be present. Default values will be + used for any missing arguments. The dict must be of the form: + + msg = {'topic':"", 'payload':"", 'qos':, + 'retain':} + topic must be present and may not be empty. + If payload is "", None or not present then a zero length payload + will be published. + If qos is not present, the default of 0 is used. + If retain is not present, the default of False is used. + + If a tuple, then it must be of the form: + ("", "", qos, retain) + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + auth = {'username':"", 'password':""} + Username is required, password is optional and will default to None + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + Defaults to None, which indicates that TLS should not be used. + + :param str transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param proxy_args: a dictionary that will be given to the client. + """ + + if not isinstance(msgs, Iterable): + raise TypeError('msgs must be an iterable') + if len(msgs) == 0: + raise ValueError('msgs is empty') + + client = paho.Client( + CallbackAPIVersion.VERSION2, + client_id=client_id, + userdata=collections.deque(msgs), + protocol=protocol, + transport=transport, + ) + + client.enable_logger() + client.on_publish = _on_publish + client.on_connect = _on_connect # type: ignore + + if proxy_args is not None: + client.proxy_set(**proxy_args) + + if auth: + username = auth.get('username') + if username: + password = auth.get('password') + client.username_pw_set(username, password) + else: + raise KeyError("The 'username' key was not found, this is " + "required for auth") + + if will is not None: + client.will_set(**will) + + if tls is not None: + if isinstance(tls, dict): + insecure = tls.pop('insecure', False) + # mypy don't get that tls no longer contains the key insecure + client.tls_set(**tls) # type: ignore[misc] + if insecure: + # Must be set *after* the `client.tls_set()` call since it sets + # up the SSL context that `client.tls_insecure_set` alters. + client.tls_insecure_set(insecure) + else: + # Assume input is SSLContext object + client.tls_set_context(tls) + + client.connect(hostname, port, keepalive) + client.loop_forever() + + +def single( + topic: str, + payload: paho.PayloadType = None, + qos: int = 0, + retain: bool = False, + hostname: str = "localhost", + port: int = 1883, + client_id: str = "", + keepalive: int = 60, + will: MessageDict | None = None, + auth: AuthParameter | None = None, + tls: TLSParameter | None = None, + protocol: MQTTProtocolVersion = paho.MQTTv311, + transport: Literal["tcp", "websockets"] = "tcp", + proxy_args: Any | None = None, +) -> None: + """Publish a single message to a broker, then disconnect cleanly. + + This function creates an MQTT client, connects to a broker and publishes a + single message. Once the message has been delivered, it disconnects cleanly + from the broker. + + :param str topic: the only required argument must be the topic string to which the + payload will be published. + + :param payload: the payload to be published. If "" or None, a zero length payload + will be published. + + :param int qos: the qos to use when publishing, default to 0. + + :param bool retain: set the message to be retained (True) or not (False). + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + Username is required, password is optional and will default to None + auth = {'username':"", 'password':""} + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Defaults to None, which indicates that TLS should not be used. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + + :param transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param proxy_args: a dictionary that will be given to the client. + """ + + msg: MessageDict = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain} + + multiple([msg], hostname, port, client_id, keepalive, will, auth, tls, + protocol, transport, proxy_args) diff --git a/sbapp/mqtt/py.typed b/sbapp/mqtt/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/sbapp/mqtt/reasoncodes.py b/sbapp/mqtt/reasoncodes.py new file mode 100644 index 0000000..243ac96 --- /dev/null +++ b/sbapp/mqtt/reasoncodes.py @@ -0,0 +1,223 @@ +# ******************************************************************* +# Copyright (c) 2017, 2019 IBM Corp. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Ian Craggs - initial implementation and/or documentation +# ******************************************************************* + +import functools +import warnings +from typing import Any + +from .packettypes import PacketTypes + + +@functools.total_ordering +class ReasonCode: + """MQTT version 5.0 reason codes class. + + See ReasonCode.names for a list of possible numeric values along with their + names and the packets to which they apply. + + """ + + def __init__(self, packetType: int, aName: str ="Success", identifier: int =-1): + """ + packetType: the type of the packet, such as PacketTypes.CONNECT that + this reason code will be used with. Some reason codes have different + names for the same identifier when used a different packet type. + + aName: the String name of the reason code to be created. Ignored + if the identifier is set. + + identifier: an integer value of the reason code to be created. + + """ + + self.packetType = packetType + self.names = { + 0: {"Success": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, + PacketTypes.UNSUBACK, PacketTypes.AUTH], + "Normal disconnection": [PacketTypes.DISCONNECT], + "Granted QoS 0": [PacketTypes.SUBACK]}, + 1: {"Granted QoS 1": [PacketTypes.SUBACK]}, + 2: {"Granted QoS 2": [PacketTypes.SUBACK]}, + 4: {"Disconnect with will message": [PacketTypes.DISCONNECT]}, + 16: {"No matching subscribers": + [PacketTypes.PUBACK, PacketTypes.PUBREC]}, + 17: {"No subscription found": [PacketTypes.UNSUBACK]}, + 24: {"Continue authentication": [PacketTypes.AUTH]}, + 25: {"Re-authenticate": [PacketTypes.AUTH]}, + 128: {"Unspecified error": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, + PacketTypes.DISCONNECT], }, + 129: {"Malformed packet": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 130: {"Protocol error": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 131: {"Implementation specific error": [PacketTypes.CONNACK, + PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, + PacketTypes.UNSUBACK, PacketTypes.DISCONNECT], }, + 132: {"Unsupported protocol version": [PacketTypes.CONNACK]}, + 133: {"Client identifier not valid": [PacketTypes.CONNACK]}, + 134: {"Bad user name or password": [PacketTypes.CONNACK]}, + 135: {"Not authorized": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, + PacketTypes.DISCONNECT], }, + 136: {"Server unavailable": [PacketTypes.CONNACK]}, + 137: {"Server busy": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 138: {"Banned": [PacketTypes.CONNACK]}, + 139: {"Server shutting down": [PacketTypes.DISCONNECT]}, + 140: {"Bad authentication method": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 141: {"Keep alive timeout": [PacketTypes.DISCONNECT]}, + 142: {"Session taken over": [PacketTypes.DISCONNECT]}, + 143: {"Topic filter invalid": + [PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT]}, + 144: {"Topic name invalid": + [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, + 145: {"Packet identifier in use": + [PacketTypes.PUBACK, PacketTypes.PUBREC, + PacketTypes.SUBACK, PacketTypes.UNSUBACK]}, + 146: {"Packet identifier not found": + [PacketTypes.PUBREL, PacketTypes.PUBCOMP]}, + 147: {"Receive maximum exceeded": [PacketTypes.DISCONNECT]}, + 148: {"Topic alias invalid": [PacketTypes.DISCONNECT]}, + 149: {"Packet too large": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 150: {"Message rate too high": [PacketTypes.DISCONNECT]}, + 151: {"Quota exceeded": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.DISCONNECT], }, + 152: {"Administrative action": [PacketTypes.DISCONNECT]}, + 153: {"Payload format invalid": + [PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, + 154: {"Retain not supported": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 155: {"QoS not supported": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 156: {"Use another server": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 157: {"Server moved": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 158: {"Shared subscription not supported": + [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, + 159: {"Connection rate exceeded": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 160: {"Maximum connect time": + [PacketTypes.DISCONNECT]}, + 161: {"Subscription identifiers not supported": + [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, + 162: {"Wildcard subscription not supported": + [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, + } + if identifier == -1: + if packetType == PacketTypes.DISCONNECT and aName == "Success": + aName = "Normal disconnection" + self.set(aName) + else: + self.value = identifier + self.getName() # check it's good + + def __getName__(self, packetType, identifier): + """ + Get the reason code string name for a specific identifier. + The name can vary by packet type for the same identifier, which + is why the packet type is also required. + + Used when displaying the reason code. + """ + if identifier not in self.names: + raise KeyError(identifier) + names = self.names[identifier] + namelist = [name for name in names.keys() if packetType in names[name]] + if len(namelist) != 1: + raise ValueError(f"Expected exactly one name, found {namelist!r}") + return namelist[0] + + def getId(self, name): + """ + Get the numeric id corresponding to a reason code name. + + Used when setting the reason code for a packetType + check that only valid codes for the packet are set. + """ + for code in self.names.keys(): + if name in self.names[code].keys(): + if self.packetType in self.names[code][name]: + return code + raise KeyError(f"Reason code name not found: {name}") + + def set(self, name): + self.value = self.getId(name) + + def unpack(self, buffer): + c = buffer[0] + name = self.__getName__(self.packetType, c) + self.value = self.getId(name) + return 1 + + def getName(self): + """Returns the reason code name corresponding to the numeric value which is set. + """ + return self.__getName__(self.packetType, self.value) + + def __eq__(self, other): + if isinstance(other, int): + return self.value == other + if isinstance(other, str): + return other == str(self) + if isinstance(other, ReasonCode): + return self.value == other.value + return False + + def __lt__(self, other): + if isinstance(other, int): + return self.value < other + if isinstance(other, ReasonCode): + return self.value < other.value + return NotImplemented + + def __repr__(self): + try: + packet_name = PacketTypes.Names[self.packetType] + except IndexError: + packet_name = "Unknown" + + return f"ReasonCode({packet_name}, {self.getName()!r})" + + def __str__(self): + return self.getName() + + def json(self): + return self.getName() + + def pack(self): + return bytearray([self.value]) + + @property + def is_failure(self) -> bool: + return self.value >= 0x80 + + +class _CompatibilityIsInstance(type): + def __instancecheck__(self, other: Any) -> bool: + return isinstance(other, ReasonCode) + + +class ReasonCodes(ReasonCode, metaclass=_CompatibilityIsInstance): + def __init__(self, *args, **kwargs): + warnings.warn("ReasonCodes is deprecated, use ReasonCode (singular) instead", + category=DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/sbapp/mqtt/subscribe.py b/sbapp/mqtt/subscribe.py new file mode 100644 index 0000000..b6c80f4 --- /dev/null +++ b/sbapp/mqtt/subscribe.py @@ -0,0 +1,281 @@ +# Copyright (c) 2016 Roger Light +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Roger Light - initial API and implementation + +""" +This module provides some helper functions to allow straightforward subscribing +to topics and retrieving messages. The two functions are simple(), which +returns one or messages matching a set of topics, and callback() which allows +you to pass a callback for processing of messages. +""" + +from .. import mqtt +from . import client as paho + + +def _on_connect(client, userdata, flags, reason_code, properties): + """Internal callback""" + if reason_code != 0: + raise mqtt.MQTTException(paho.connack_string(reason_code)) + + if isinstance(userdata['topics'], list): + for topic in userdata['topics']: + client.subscribe(topic, userdata['qos']) + else: + client.subscribe(userdata['topics'], userdata['qos']) + + +def _on_message_callback(client, userdata, message): + """Internal callback""" + userdata['callback'](client, userdata['userdata'], message) + + +def _on_message_simple(client, userdata, message): + """Internal callback""" + + if userdata['msg_count'] == 0: + return + + # Don't process stale retained messages if 'retained' was false + if message.retain and not userdata['retained']: + return + + userdata['msg_count'] = userdata['msg_count'] - 1 + + if userdata['messages'] is None and userdata['msg_count'] == 0: + userdata['messages'] = message + client.disconnect() + return + + userdata['messages'].append(message) + if userdata['msg_count'] == 0: + client.disconnect() + + +def callback(callback, topics, qos=0, userdata=None, hostname="localhost", + port=1883, client_id="", keepalive=60, will=None, auth=None, + tls=None, protocol=paho.MQTTv311, transport="tcp", + clean_session=True, proxy_args=None): + """Subscribe to a list of topics and process them in a callback function. + + This function creates an MQTT client, connects to a broker and subscribes + to a list of topics. Incoming messages are processed by the user provided + callback. This is a blocking function and will never return. + + :param callback: function with the same signature as `on_message` for + processing the messages received. + + :param topics: either a string containing a single topic to subscribe to, or a + list of topics to subscribe to. + + :param int qos: the qos to use when subscribing. This is applied to all topics. + + :param userdata: passed to the callback + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + auth = {'username':"", 'password':""} + Username is required, password is optional and will default to None + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + Defaults to None, which indicates that TLS should not be used. + + :param str transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param clean_session: a boolean that determines the client type. If True, + the broker will remove all information about this client + when it disconnects. If False, the client is a persistent + client and subscription information and queued messages + will be retained when the client disconnects. + Defaults to True. + + :param proxy_args: a dictionary that will be given to the client. + """ + + if qos < 0 or qos > 2: + raise ValueError('qos must be in the range 0-2') + + callback_userdata = { + 'callback':callback, + 'topics':topics, + 'qos':qos, + 'userdata':userdata} + + client = paho.Client( + paho.CallbackAPIVersion.VERSION2, + client_id=client_id, + userdata=callback_userdata, + protocol=protocol, + transport=transport, + clean_session=clean_session, + ) + client.enable_logger() + + client.on_message = _on_message_callback + client.on_connect = _on_connect + + if proxy_args is not None: + client.proxy_set(**proxy_args) + + if auth: + username = auth.get('username') + if username: + password = auth.get('password') + client.username_pw_set(username, password) + else: + raise KeyError("The 'username' key was not found, this is " + "required for auth") + + if will is not None: + client.will_set(**will) + + if tls is not None: + if isinstance(tls, dict): + insecure = tls.pop('insecure', False) + client.tls_set(**tls) + if insecure: + # Must be set *after* the `client.tls_set()` call since it sets + # up the SSL context that `client.tls_insecure_set` alters. + client.tls_insecure_set(insecure) + else: + # Assume input is SSLContext object + client.tls_set_context(tls) + + client.connect(hostname, port, keepalive) + client.loop_forever() + + +def simple(topics, qos=0, msg_count=1, retained=True, hostname="localhost", + port=1883, client_id="", keepalive=60, will=None, auth=None, + tls=None, protocol=paho.MQTTv311, transport="tcp", + clean_session=True, proxy_args=None): + """Subscribe to a list of topics and return msg_count messages. + + This function creates an MQTT client, connects to a broker and subscribes + to a list of topics. Once "msg_count" messages have been received, it + disconnects cleanly from the broker and returns the messages. + + :param topics: either a string containing a single topic to subscribe to, or a + list of topics to subscribe to. + + :param int qos: the qos to use when subscribing. This is applied to all topics. + + :param int msg_count: the number of messages to retrieve from the broker. + if msg_count == 1 then a single MQTTMessage will be returned. + if msg_count > 1 then a list of MQTTMessages will be returned. + + :param bool retained: If set to True, retained messages will be processed the same as + non-retained messages. If set to False, retained messages will + be ignored. This means that with retained=False and msg_count=1, + the function will return the first message received that does + not have the retained flag set. + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + auth = {'username':"", 'password':""} + Username is required, password is optional and will default to None + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + Defaults to None, which indicates that TLS should not be used. + + :param protocol: the MQTT protocol version to use. Defaults to MQTTv311. + + :param transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param clean_session: a boolean that determines the client type. If True, + the broker will remove all information about this client + when it disconnects. If False, the client is a persistent + client and subscription information and queued messages + will be retained when the client disconnects. + Defaults to True. If protocol is MQTTv50, clean_session + is ignored. + + :param proxy_args: a dictionary that will be given to the client. + """ + + if msg_count < 1: + raise ValueError('msg_count must be > 0') + + # Set ourselves up to return a single message if msg_count == 1, or a list + # if > 1. + if msg_count == 1: + messages = None + else: + messages = [] + + # Ignore clean_session if protocol is MQTTv50, otherwise Client will raise + if protocol == paho.MQTTv5: + clean_session = None + + userdata = {'retained':retained, 'msg_count':msg_count, 'messages':messages} + + callback(_on_message_simple, topics, qos, userdata, hostname, port, + client_id, keepalive, will, auth, tls, protocol, transport, + clean_session, proxy_args) + + return userdata['messages'] diff --git a/sbapp/mqtt/subscribeoptions.py b/sbapp/mqtt/subscribeoptions.py new file mode 100644 index 0000000..7e0605d --- /dev/null +++ b/sbapp/mqtt/subscribeoptions.py @@ -0,0 +1,113 @@ +""" +******************************************************************* + Copyright (c) 2017, 2019 IBM Corp. + + All rights reserved. This program and the accompanying materials + are made available under the terms of the Eclipse Public License v2.0 + and Eclipse Distribution License v1.0 which accompany this distribution. + + The Eclipse Public License is available at + http://www.eclipse.org/legal/epl-v20.html + and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + + Contributors: + Ian Craggs - initial implementation and/or documentation +******************************************************************* +""" + + + +class MQTTException(Exception): + pass + + +class SubscribeOptions: + """The MQTT v5.0 subscribe options class. + + The options are: + qos: As in MQTT v3.1.1. + noLocal: True or False. If set to True, the subscriber will not receive its own publications. + retainAsPublished: True or False. If set to True, the retain flag on received publications will be as set + by the publisher. + retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND + Controls when the broker should send retained messages: + - RETAIN_SEND_ON_SUBSCRIBE: on any successful subscribe request + - RETAIN_SEND_IF_NEW_SUB: only if the subscribe request is new + - RETAIN_DO_NOT_SEND: never send retained messages + """ + + # retain handling options + RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB, RETAIN_DO_NOT_SEND = range( + 0, 3) + + def __init__( + self, + qos: int = 0, + noLocal: bool = False, + retainAsPublished: bool = False, + retainHandling: int = RETAIN_SEND_ON_SUBSCRIBE, + ): + """ + qos: 0, 1 or 2. 0 is the default. + noLocal: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. + retainAsPublished: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. + retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND + RETAIN_SEND_ON_SUBSCRIBE is the default and corresponds to MQTT v3.1.1 behavior. + """ + object.__setattr__(self, "names", + ["QoS", "noLocal", "retainAsPublished", "retainHandling"]) + self.QoS = qos # bits 0,1 + self.noLocal = noLocal # bit 2 + self.retainAsPublished = retainAsPublished # bit 3 + self.retainHandling = retainHandling # bits 4 and 5: 0, 1 or 2 + if self.retainHandling not in (0, 1, 2): + raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") + if self.QoS not in (0, 1, 2): + raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") + + def __setattr__(self, name, value): + if name not in self.names: + raise MQTTException( + f"{name} Attribute name must be one of {self.names}") + object.__setattr__(self, name, value) + + def pack(self): + if self.retainHandling not in (0, 1, 2): + raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") + if self.QoS not in (0, 1, 2): + raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") + noLocal = 1 if self.noLocal else 0 + retainAsPublished = 1 if self.retainAsPublished else 0 + data = [(self.retainHandling << 4) | (retainAsPublished << 3) | + (noLocal << 2) | self.QoS] + return bytes(data) + + def unpack(self, buffer): + b0 = buffer[0] + self.retainHandling = ((b0 >> 4) & 0x03) + self.retainAsPublished = True if ((b0 >> 3) & 0x01) == 1 else False + self.noLocal = True if ((b0 >> 2) & 0x01) == 1 else False + self.QoS = (b0 & 0x03) + if self.retainHandling not in (0, 1, 2): + raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") + if self.QoS not in (0, 1, 2): + raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") + return 1 + + def __repr__(self): + return str(self) + + def __str__(self): + return "{QoS="+str(self.QoS)+", noLocal="+str(self.noLocal) +\ + ", retainAsPublished="+str(self.retainAsPublished) +\ + ", retainHandling="+str(self.retainHandling)+"}" + + def json(self): + data = { + "QoS": self.QoS, + "noLocal": self.noLocal, + "retainAsPublished": self.retainAsPublished, + "retainHandling": self.retainHandling, + } + return data From 74ba296fa60a36ed24ca058dbfcf76f40ad58f37 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Jan 2025 22:32:21 +0100 Subject: [PATCH 36/76] Added MQTT library credits to info --- sbapp/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 46d4947..9e1042f 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2807,10 +2807,10 @@ class SidebandApp(MDApp): self.information_screen.ids.information_scrollview.effect_cls = ScrollEffect self.information_screen.ids.information_logo.icon = self.sideband.asset_dir+"/rns_256.png" - str_comps = " - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" + str_comps = " - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)" str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]MD2bbcode[/b] (GPL3 License)" - str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Python[/b] (PSF License)" + str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Paho MQTT[/b] (EPL2 License)\n - [b]Python[/b] (PSF License)" str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright Β© 2025 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY" info = "This is "+self.root.ids.app_version_info.text+", on RNS v"+RNS.__version__+" and LXMF v"+LXMF.__version__+".\n\nHumbly build using the following open components:\n\n"+str_comps self.information_screen.ids.information_info.text = info From 3441bd9dba4499ecc039c91783f57bce035e1f43 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Jan 2025 22:35:47 +0100 Subject: [PATCH 37/76] Added basic MQTT handler --- sbapp/sideband/mqtt.py | 67 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 sbapp/sideband/mqtt.py diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py new file mode 100644 index 0000000..3023966 --- /dev/null +++ b/sbapp/sideband/mqtt.py @@ -0,0 +1,67 @@ +import RNS +import threading +from sbapp.mqtt import client as mqtt +from .sense import Telemeter, Commands + +class MQTT(): + def __init__(self): + self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) + self.host = None + self.port = None + self.waiting_telemetry = set() + self.unacked_msgs = set() + self.client.user_data_set(self.unacked_msgs) + # TODO: Add handling + # self.client.on_connect_fail = mqtt_connection_failed + # self.client.on_disconnect = disconnect_callback + + def set_server(self, host, port): + self.host = host + self.port = port or 1883 + + def set_auth(self, username, password): + self.client.username_pw_set(username, password) + + def connect(self): + RNS.log(f"Connecting MQTT server {self.host}:{self.port}", RNS.LOG_DEBUG) # TODO: Remove debug + cs = self.client.connect(self.host, self.port) + self.client.loop_start() + + def disconnect(self): + self.client.disconnect() + self.client.loop_stop() + + def post_message(self, topic, data): + mqtt_msg = self.client.publish(topic, data, qos=1) + self.unacked_msgs.add(mqtt_msg.mid) + self.waiting_telemetry.add(mqtt_msg) + + def handle(self, context_dest, telemetry): + remote_telemeter = Telemeter.from_packed(telemetry) + read_telemetry = remote_telemeter.read_all() + telemetry_timestamp = read_telemetry["time"]["utc"] + + from rich.pretty import pprint + pprint(read_telemetry) + + def mqtt_job(): + self.connect() + root_path = f"lxmf/telemetry/{RNS.prettyhexrep(context_dest)}" + for sensor in remote_telemeter.sensors: + s = remote_telemeter.sensors[sensor] + topics = s.render_mqtt() + RNS.log(topics) + + if topics != None: + for topic in topics: + topic_path = f"{root_path}/{topic}" + data = topics[topic] + RNS.log(f" {topic_path}: {data}") + self.post_message(topic_path, data) + + for msg in self.waiting_telemetry: + msg.wait_for_publish() + + self.disconnect() + + threading.Thread(target=mqtt_job, daemon=True).start() \ No newline at end of file From 8899d820310e2d65b489daa16f4d4623260849f3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Jan 2025 22:37:49 +0100 Subject: [PATCH 38/76] Added telemetry to MQTT option --- sbapp/sideband/core.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index c4c3669..a5dc2cf 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -21,6 +21,7 @@ from collections import deque from .res import sideband_fb_data from .sense import Telemeter, Commands from .plugins import SidebandCommandPlugin, SidebandServicePlugin, SidebandTelemetryPlugin +from .mqtt import MQTT if RNS.vendor.platformutils.get_platform() == "android": import plyer @@ -258,6 +259,8 @@ class SidebandCore(): self.webshare_ssl_key_path = self.app_dir+"/app_storage/ssl_key.pem" self.webshare_ssl_cert_path = self.app_dir+"/app_storage/ssl_cert.pem" + + self.mqtt = None self.first_run = True self.saving_configuration = False @@ -725,6 +728,18 @@ class SidebandCore(): self.config["telemetry_request_interval"] = 43200 if not "telemetry_collector_enabled" in self.config: self.config["telemetry_collector_enabled"] = False + if not "telemetry_to_mqtt" in self.config: + self.config["telemetry_to_mqtt"] = False + if not "telemetry_mqtt_host" in self.config: + self.config["telemetry_mqtt_host"] = None + if not "telemetry_mqtt_port" in self.config: + self.config["telemetry_mqtt_port"] = None + if not "telemetry_mqtt_user" in self.config: + self.config["telemetry_mqtt_user"] = None + if not "telemetry_mqtt_pass" in self.config: + self.config["telemetry_mqtt_pass"] = None + if not "telemetry_mqtt_validate_ssl" in self.config: + self.config["telemetry_mqtt_validate_ssl"] = False if not "telemetry_icon" in self.config: self.config["telemetry_icon"] = SidebandCore.DEFAULT_APPEARANCE[0] @@ -2267,6 +2282,9 @@ class SidebandCore(): self.setstate("app.flags.last_telemetry", time.time()) + if self.config["telemetry_to_mqtt"] == True: + self.mqtt_handle_telemetry(context_dest, telemetry) + return telemetry except Exception as e: @@ -3083,6 +3101,14 @@ class SidebandCore(): self.update_telemeter_config() self.setstate("app.flags.last_telemetry", time.time()) + def mqtt_handle_telemetry(self, context_dest, telemetry): + if self.mqtt == None: + self.mqtt = MQTT() + + self.mqtt.set_server(self.config["telemetry_mqtt_host"], self.config["telemetry_mqtt_port"]) + self.mqtt.set_auth(self.config["telemetry_mqtt_user"], self.config["telemetry_mqtt_pass"]) + self.mqtt.handle(context_dest, telemetry) + def update_telemetry(self): try: try: From 9ef43ecef6cc8447f52edd8d2a75357a53f8ec23 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 23 Jan 2025 00:30:45 +0100 Subject: [PATCH 39/76] Implemented scheduler for MQTT handler --- sbapp/sideband/mqtt.py | 105 ++++++++++++++++++++++++++++++----------- 1 file changed, 77 insertions(+), 28 deletions(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index 3023966..962f6b4 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -1,19 +1,60 @@ import RNS +import time import threading +from collections import deque from sbapp.mqtt import client as mqtt from .sense import Telemeter, Commands class MQTT(): + QUEUE_MAXLEN = 1024 + SCHEDULER_SLEEP = 1 + def __init__(self): self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) self.host = None self.port = None + self.run = False + self.is_connected = False + self.queue_lock = threading.Lock() + self.waiting_msgs = deque(maxlen=MQTT.QUEUE_MAXLEN) self.waiting_telemetry = set() self.unacked_msgs = set() self.client.user_data_set(self.unacked_msgs) - # TODO: Add handling - # self.client.on_connect_fail = mqtt_connection_failed - # self.client.on_disconnect = disconnect_callback + self.client.on_connect_fail = self.connect_failed + self.client.on_disconnect = self.disconnected + self.start() + + def start(self): + self.run = True + threading.Thread(target=self.jobs, daemon=True).start() + RNS.log("Started MQTT scheduler", RNS.LOG_DEBUG) + + def stop(self): + RNS.log("Stopping MQTT scheduler", RNS.LOG_DEBUG) + self.run = False + + def jobs(self): + while self.run: + try: + if len(self.waiting_msgs) > 0: + RNS.log(f"Processing {len(self.waiting_msgs)} MQTT messages", RNS.LOG_DEBUG) + self.process_queue() + + except Exception as e: + RNS.log("An error occurred while running MQTT scheduler jobs: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + time.sleep(MQTT.SCHEDULER_SLEEP) + + RNS.log("Stopped MQTT scheduler", RNS.LOG_DEBUG) + + def connect_failed(self, client, userdata): + RNS.log(f"Connection to MQTT server failed", RNS.LOG_DEBUG) + self.is_connected = False + + def disconnected(self, client, userdata, disconnect_flags, reason_code, properties): + RNS.log(f"Disconnected from MQTT server, reason code: {reason_code}", RNS.LOG_EXTREME) + self.is_connected = False def set_server(self, host, port): self.host = host @@ -28,40 +69,48 @@ class MQTT(): self.client.loop_start() def disconnect(self): + RNS.log("Disconnecting from MQTT server", RNS.LOG_EXTREME) # TODO: Remove debug self.client.disconnect() self.client.loop_stop() + self.is_connected = False def post_message(self, topic, data): mqtt_msg = self.client.publish(topic, data, qos=1) self.unacked_msgs.add(mqtt_msg.mid) self.waiting_telemetry.add(mqtt_msg) + def process_queue(self): + with self.queue_lock: + self.connect() + + try: + while len(self.waiting_msgs) > 0: + topic, data = self.waiting_msgs.pop() + self.post_message(topic, data) + except Exception as e: + RNS.log(f"An error occurred while publishing MQTT messages: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + try: + for msg in self.waiting_telemetry: + msg.wait_for_publish() + except Exception as e: + RNS.log(f"An error occurred while publishing MQTT messages: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + self.disconnect() + def handle(self, context_dest, telemetry): remote_telemeter = Telemeter.from_packed(telemetry) read_telemetry = remote_telemeter.read_all() telemetry_timestamp = read_telemetry["time"]["utc"] - - from rich.pretty import pprint - pprint(read_telemetry) - - def mqtt_job(): - self.connect() - root_path = f"lxmf/telemetry/{RNS.prettyhexrep(context_dest)}" - for sensor in remote_telemeter.sensors: - s = remote_telemeter.sensors[sensor] - topics = s.render_mqtt() - RNS.log(topics) - - if topics != None: - for topic in topics: - topic_path = f"{root_path}/{topic}" - data = topics[topic] - RNS.log(f" {topic_path}: {data}") - self.post_message(topic_path, data) - - for msg in self.waiting_telemetry: - msg.wait_for_publish() - - self.disconnect() - - threading.Thread(target=mqtt_job, daemon=True).start() \ No newline at end of file + root_path = f"lxmf/telemetry/{RNS.prettyhexrep(context_dest)}" + for sensor in remote_telemeter.sensors: + s = remote_telemeter.sensors[sensor] + topics = s.render_mqtt() + if topics != None: + for topic in topics: + topic_path = f"{root_path}/{topic}" + data = topics[topic] + self.waiting_msgs.append((topic_path, data)) + # RNS.log(f"{topic_path}: {data}") # TODO: Remove debug From be6a1de135e2fa26b066794422e0895d83e5737a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 24 Jan 2025 22:15:05 +0100 Subject: [PATCH 40/76] Added LXMF PN sensor to Telemeter --- sbapp/sideband/sense.py | 203 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 201 insertions(+), 2 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 002e6c7..db18db2 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -54,7 +54,8 @@ class Telemeter(): Sensor.SID_PROXIMITY: Proximity, Sensor.SID_POWER_CONSUMPTION: PowerConsumption, Sensor.SID_POWER_PRODUCTION: PowerProduction, Sensor.SID_PROCESSOR: Processor, Sensor.SID_RAM: RandomAccessMemory, Sensor.SID_NVM: NonVolatileMemory, - Sensor.SID_CUSTOM: Custom, Sensor.SID_TANK: Tank, Sensor.SID_FUEL: Fuel} + Sensor.SID_CUSTOM: Custom, Sensor.SID_TANK: Tank, Sensor.SID_FUEL: Fuel, + Sensor.SID_RNS_TRANSPORT: RNSTransport, Sensor.SID_LXMF_PROPAGATION: LXMFPropagation} self.available = { "time": Sensor.SID_TIME, @@ -67,7 +68,8 @@ class Telemeter(): "acceleration": Sensor.SID_ACCELERATION, "proximity": Sensor.SID_PROXIMITY, "power_consumption": Sensor.SID_POWER_CONSUMPTION, "power_production": Sensor.SID_POWER_PRODUCTION, "processor": Sensor.SID_PROCESSOR, "ram": Sensor.SID_RAM, "nvm": Sensor.SID_NVM, - "custom": Sensor.SID_CUSTOM, "tank": Sensor.SID_TANK, "fuel": Sensor.SID_FUEL} + "custom": Sensor.SID_CUSTOM, "tank": Sensor.SID_TANK, "fuel": Sensor.SID_FUEL, + "rns_transport": Sensor.SID_RNS_TRANSPORT, "lxmf_propagation": Sensor.SID_LXMF_PROPAGATION} self.names = {} for name in self.available: @@ -206,6 +208,8 @@ class Sensor(): SID_NVM = 0x15 SID_TANK = 0x16 SID_FUEL = 0x17 + SID_RNS_TRANSPORT = 0x19 + SID_LXMF_PROPAGATION = 0x18 SID_CUSTOM = 0xff def __init__(self, sid = None, stale_time = None): @@ -2499,6 +2503,201 @@ class Fuel(Sensor): return rendered +class RNSTransport(Sensor): + pass + +class LXMFPropagation(Sensor): + SID = Sensor.SID_LXMF_PROPAGATION + STALE_TIME = 5 + + def __init__(self): + self.identity = None + self.lxmd = None + super().__init__(type(self).SID, type(self).STALE_TIME) + + def set_identity(self, identity): + if type(identity) == RNS.Identity: + self.identity = identity + else: + file_path = os.path.expanduser(identity) + if os.path.isfile(file_path): + try: + self.identity = RNS.Identity.from_file(file_path) + except Exception as e: + RNS.log("Could not load LXMF propagation sensor identity from \"{file_path}\"", RNS.LOG_ERROR) + + def setup_sensor(self): + self.update_data() + + def teardown_sensor(self): + self.identity = None + self.data = None + + def update_data(self): + if self.identity != None: + if self.lxmd == None: + import LXMF.LXMPeer as LXMPeer + import LXMF.Utilities.lxmd as lxmd + self.ERROR_NO_IDENTITY = LXMPeer.LXMPeer.ERROR_NO_IDENTITY + self.ERROR_NO_ACCESS = LXMPeer.LXMPeer.ERROR_NO_ACCESS + self.ERROR_TIMEOUT = LXMPeer.LXMPeer.ERROR_TIMEOUT + self.lxmd = lxmd + + status_response = self.lxmd.query_status(identity=self.identity) + if status_response == None: + RNS.log("Status response from lxmd was received, but contained no data", RNS.LOG_ERROR) + elif status_response == self.ERROR_NO_IDENTITY: + RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) + elif status_response == self.ERROR_NO_IDENTITY: + RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) + elif status_response == self.ERROR_NO_IDENTITY: + RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) + else: + RNS.log("Received status response from lxmd", RNS.LOG_DEBUG) # TODO: Remove debug + self.data = status_response + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = self.data + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + return packed + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + from rich.pretty import pprint + pprint(self.data["peers"]) + + try: + d = self.data + values = { + "destination_hash": d["destination_hash"], + "identity_hash": d["identity_hash"], + "uptime": d["uptime"], + "delivery_limit": d["delivery_limit"]*1000, + "propagation_limit": d["propagation_limit"]*1000, + "autopeer_maxdepth": d["autopeer_maxdepth"], + "from_static_only": d["from_static_only"], + "messagestore_count": d["messagestore"]["count"], + "messagestore_bytes": d["messagestore"]["bytes"], + "messagestore_free": d["messagestore"]["limit"]-d["messagestore"]["bytes"], + "messagestore_limit": d["messagestore"]["limit"], + "messagestore_pct": round(max( (d["messagestore"]["bytes"]/d["messagestore"]["limit"])*100, 100.0), 2), + "client_propagation_messages_received": d["clients"]["client_propagation_messages_received"], + "client_propagation_messages_served": d["clients"]["client_propagation_messages_served"], + "unpeered_propagation_incoming": d["unpeered_propagation_incoming"], + "unpeered_propagation_rx_bytes": d["unpeered_propagation_rx_bytes"], + "static_peers": d["static_peers"], + "total_peers": d["total_peers"], + "max_peers": d["max_peers"], + "peers": {} + } + + for peer_id in d["peers"]: + p = d["peers"][peer_id] + values["peers"][peer_id] = { + "type": p["type"], + "state": p["state"], + "alive": p["alive"], + "last_heard": p["last_heard"], + "next_sync_attempt": p["next_sync_attempt"], + "last_sync_attempt": p["last_sync_attempt"], + "sync_backoff": p["sync_backoff"], + "peering_timebase": p["peering_timebase"], + "ler": p["ler"], + "str": p["str"], + "transfer_limit": p["transfer_limit"], + "network_distance": p["network_distance"], + "rx_bytes": p["rx_bytes"], + "tx_bytes": p["tx_bytes"], + "messages_offered": p["messages"]["offered"], + "messages_outgoing": p["messages"]["outgoing"], + "messages_incoming": p["messages"]["incoming"], + "messages_unhandled": p["messages"]["unhandled"], + } + + rendered = { + "icon": "email-fast-outline", + "name": "LXMF Propagation", + "values": values, + } + + return rendered + + except Exception as e: + RNS.log(f"Could not render lxmd telemetry data. The contained exception was: {e}", RNS.LOG_ERROR) + + return None + + def render_mqtt(self, relative_to=None): + if self.data != None: + r = self.render(relative_to=relative_to) + v = r["values"] + nid = mqtt_desthash(v["destination_hash"]) + topic = f"{self.name()}/{nid}" + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/identity_hash": mqtt_desthash(v["identity_hash"]), + f"{topic}/uptime": v["uptime"], + f"{topic}/delivery_limit": v["delivery_limit"], + f"{topic}/propagation_limit": v["propagation_limit"], + f"{topic}/autopeer_maxdepth": v["autopeer_maxdepth"], + f"{topic}/from_static_only": v["from_static_only"], + f"{topic}/messagestore_count": v["messagestore_count"], + f"{topic}/messagestore_bytes": v["messagestore_bytes"], + f"{topic}/messagestore_free": v["messagestore_free"], + f"{topic}/messagestore_limit": v["messagestore_limit"], + f"{topic}/messagestore_pct": v["messagestore_pct"], + f"{topic}/client_propagation_messages_received": v["client_propagation_messages_received"], + f"{topic}/client_propagation_messages_served": v["client_propagation_messages_served"], + f"{topic}/unpeered_propagation_incoming": v["unpeered_propagation_incoming"], + f"{topic}/unpeered_propagation_rx_bytes": v["unpeered_propagation_rx_bytes"], + f"{topic}/static_peers": v["static_peers"], + f"{topic}/total_peers": v["total_peers"], + f"{topic}/max_peers": v["max_peers"], + } + + for peer_id in v["peers"]: + p = v["peers"][peer_id] + pid = mqtt_desthash(peer_id) + rendered[f"{topic}/peers/{pid}/type"] = p["type"] + rendered[f"{topic}/peers/{pid}/state"] = p["state"] + rendered[f"{topic}/peers/{pid}/alive"] = p["alive"] + rendered[f"{topic}/peers/{pid}/last_heard"] = p["last_heard"] + rendered[f"{topic}/peers/{pid}/next_sync_attempt"] = p["next_sync_attempt"] + rendered[f"{topic}/peers/{pid}/last_sync_attempt"] = p["last_sync_attempt"] + rendered[f"{topic}/peers/{pid}/sync_backoff"] = p["sync_backoff"] + rendered[f"{topic}/peers/{pid}/peering_timebase"] = p["peering_timebase"] + rendered[f"{topic}/peers/{pid}/ler"] = p["ler"] + rendered[f"{topic}/peers/{pid}/str"] = p["str"] + rendered[f"{topic}/peers/{pid}/transfer_limit"] = p["transfer_limit"] + rendered[f"{topic}/peers/{pid}/network_distance"] = p["network_distance"] + rendered[f"{topic}/peers/{pid}/rx_bytes"] = p["rx_bytes"] + rendered[f"{topic}/peers/{pid}/tx_bytes"] = p["tx_bytes"] + rendered[f"{topic}/peers/{pid}/messages_offered"] = p["messages_offered"] + rendered[f"{topic}/peers/{pid}/messages_outgoing"] = p["messages_outgoing"] + rendered[f"{topic}/peers/{pid}/messages_incoming"] = p["messages_incoming"] + rendered[f"{topic}/peers/{pid}/messages_unhandled"] = p["messages_unhandled"] + + else: + rendered = None + + return rendered + def mqtt_desthash(desthash): if type(desthash) == bytes: return RNS.prettyhexrep(desthash) From cc722dec9f7dd84fa96a116d6478f8fca82d16dc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 24 Jan 2025 22:32:57 +0100 Subject: [PATCH 41/76] Set default stale time for LXMF PN sensor, cleanup --- sbapp/sideband/mqtt.py | 1 + sbapp/sideband/sense.py | 5 +---- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index 962f6b4..6131d1c 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -39,6 +39,7 @@ class MQTT(): if len(self.waiting_msgs) > 0: RNS.log(f"Processing {len(self.waiting_msgs)} MQTT messages", RNS.LOG_DEBUG) self.process_queue() + RNS.log("All MQTT messages processed", RNS.LOG_DEBUG) except Exception as e: RNS.log("An error occurred while running MQTT scheduler jobs: {e}", RNS.LOG_ERROR) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index db18db2..4b700fb 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2508,7 +2508,7 @@ class RNSTransport(Sensor): class LXMFPropagation(Sensor): SID = Sensor.SID_LXMF_PROPAGATION - STALE_TIME = 5 + STALE_TIME = 120 def __init__(self): self.identity = None @@ -2578,9 +2578,6 @@ class LXMFPropagation(Sensor): if self.data == None: return None - from rich.pretty import pprint - pprint(self.data["peers"]) - try: d = self.data values = { From 94809b0ec4e79b6ecf4d0c82ce90340e893339b6 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 14:23:03 +0100 Subject: [PATCH 42/76] Added RNS Transport sensor and MQTT renderers --- sbapp/sideband/sense.py | 317 ++++++++++++++++++++++++++++++++-------- 1 file changed, 259 insertions(+), 58 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 4b700fb..3d4d314 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2504,7 +2504,196 @@ class Fuel(Sensor): return rendered class RNSTransport(Sensor): - pass + SID = Sensor.SID_RNS_TRANSPORT + STALE_TIME = 5 + + def __init__(self): + super().__init__(type(self).SID, type(self).STALE_TIME) + + def setup_sensor(self): + self.update_data() + + def teardown_sensor(self): + self.identity = None + self.data = None + + def update_data(self): + r = RNS.Reticulum.get_instance() + ifstats = r.get_interface_stats() + rss = None + if "rss" in ifstats: + rss = ifstats.pop("rss") + self.data = { + "transport_enabled": RNS.Reticulum.transport_enabled(), + "transport_identity": RNS.Transport.identity.hash, + "transport_uptime": time.time()-RNS.Transport.start_time if RNS.Reticulum.transport_enabled() else None, + "traffic_rxb": RNS.Transport.traffic_rxb, + "traffic_txb": RNS.Transport.traffic_txb, + "speed_rx": RNS.Transport.speed_rx, + "speed_tx": RNS.Transport.speed_tx, + "memory_used": rss, + "ifstats": ifstats, + "link_count": r.get_link_count(), + "path_table": sorted(r.get_path_table(max_hops=RNS.Transport.PATHFINDER_M-1), key=lambda e: (e["interface"], e["hops"]) ) + } + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = self.data + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + return packed + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + try: + d = self.data + ifs = {} + transport_nodes = {} + for ife in d["ifstats"]["interfaces"]: + ifi = ife.copy() + ifi["paths"] = {} + ifi["path_count"] = 0 + ifs[ifi.pop("name")] = ifi + + for path in d["path_table"]: + pifn = path["interface"] + if pifn in ifs: + pif = ifs[pifn] + via = path["via"] + if not via in transport_nodes: + transport_nodes[via] = {"on_interface": pifn} + if not via in pif["paths"]: + pif["paths"][via] = {} + p = path.copy() + p.pop("via") + pif["paths"][via][p.pop("hash")] = p + pif["path_count"] += 1 + + + values = { + "transport_enabled": d["transport_enabled"], + "transport_identity": d["transport_identity"], + "transport_uptime": d["transport_uptime"], + "traffic_rxb": d["traffic_rxb"], + "traffic_txb": d["traffic_txb"], + "speed_rx": d["speed_rx"], + "speed_tx": d["speed_tx"], + "memory_used": d["memory_used"], + "path_count": len(d["path_table"]), + "link_count": d["link_count"], + "interfaces": ifs, + "remote_transport_node_count": len(transport_nodes), + "remote_transport_nodes": transport_nodes, + "path_table": d["path_table"], + } + + rendered = { + "icon": "transit-connection-variant", + "name": "Reticulum Transport", + "values": values, + } + + return rendered + + except Exception as e: + RNS.log(f"Could not render RNS Transport telemetry data. The contained exception was: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + return None + + def render_mqtt(self, relative_to=None): + try: + if self.data != None: + r = self.render(relative_to=relative_to) + v = r["values"] + tid = mqtt_desthash(v["transport_identity"]) + topic = f"{self.name()}/{tid}" + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/transport_enabled": v["transport_enabled"], + f"{topic}/transport_identity": mqtt_desthash(v["transport_identity"]), + f"{topic}/transport_uptime": v["transport_uptime"], + f"{topic}/traffic_rxb": v["traffic_rxb"], + f"{topic}/traffic_txb": v["traffic_txb"], + f"{topic}/speed_rx": v["speed_rx"], + f"{topic}/speed_tx": v["speed_tx"], + f"{topic}/memory_used": v["memory_used"], + f"{topic}/path_count": v["path_count"], + f"{topic}/link_count": v["link_count"], + f"{topic}/remote_transport_node_count": v["remote_transport_node_count"], + } + + for if_name in v["interfaces"]: + i = v["interfaces"][if_name] + im = "unknown" + if i["mode"] == RNS.Interfaces.Interface.Interface.MODE_FULL: + im = "full" + elif i["mode"] == RNS.Interfaces.Interface.Interface.MODE_POINT_TO_POINT: + im = "point_to_point" + elif i["mode"] == RNS.Interfaces.Interface.Interface.MODE_ACCESS_POINT: + im = "access_point" + elif i["mode"] == RNS.Interfaces.Interface.Interface.MODE_ROAMING: + im = "roaming" + elif i["mode"] == RNS.Interfaces.Interface.Interface.MODE_BOUNDARY: + im = "boundary" + elif i["mode"] == RNS.Interfaces.Interface.Interface.MODE_GATEWAY: + im = "gateway" + + mif_name = mqtt_hash(i["hash"]) + rendered[f"{topic}/interfaces/{mif_name}/name"] = if_name + rendered[f"{topic}/interfaces/{mif_name}/short_name"] = i["short_name"] + rendered[f"{topic}/interfaces/{mif_name}/up"] = i["status"] + rendered[f"{topic}/interfaces/{mif_name}/mode"] = im + rendered[f"{topic}/interfaces/{mif_name}/type"] = i["type"] + rendered[f"{topic}/interfaces/{mif_name}/bitrate"] = i["bitrate"] + rendered[f"{topic}/interfaces/{mif_name}/rxs"] = i["rxs"] + rendered[f"{topic}/interfaces/{mif_name}/txs"] = i["txs"] + rendered[f"{topic}/interfaces/{mif_name}/rxb"] = i["rxb"] + rendered[f"{topic}/interfaces/{mif_name}/txb"] = i["txb"] + rendered[f"{topic}/interfaces/{mif_name}/ifac_signature"] = mqtt_hash(i["ifac_signature"]) + rendered[f"{topic}/interfaces/{mif_name}/ifac_size"] = i["ifac_size"] + rendered[f"{topic}/interfaces/{mif_name}/ifac_netname"] = i["ifac_netname"] + rendered[f"{topic}/interfaces/{mif_name}/incoming_announce_frequency"] = i["incoming_announce_frequency"] + rendered[f"{topic}/interfaces/{mif_name}/outgoing_announce_frequency"] = i["outgoing_announce_frequency"] + rendered[f"{topic}/interfaces/{mif_name}/held_announces"] = i["held_announces"] + rendered[f"{topic}/interfaces/{mif_name}/path_count"] = i["path_count"] + + for via in i["paths"]: + vh = mqtt_desthash(via) + + for desthash in i["paths"][via]: + dh = mqtt_desthash(desthash) + d = i["paths"][via][desthash] + lp = f"{topic}/interfaces/{mif_name}/paths/{vh}/{dh}" + rendered[f"{lp}/hops"] = d["hops"] + rendered[f"{lp}/timestamp"] = d["timestamp"] + rendered[f"{lp}/expires"] = d["expires"] + rendered[f"{lp}/interface"] = d["interface"] + + else: + rendered = None + + return rendered + + except Exception as e: + RNS.log(f"Could not render RNS Transport telemetry data to MQTT format. The contained exception was: {e}", RNS.LOG_ERROR) + + return None class LXMFPropagation(Sensor): SID = Sensor.SID_LXMF_PROPAGATION @@ -2548,12 +2737,11 @@ class LXMFPropagation(Sensor): RNS.log("Status response from lxmd was received, but contained no data", RNS.LOG_ERROR) elif status_response == self.ERROR_NO_IDENTITY: RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) - elif status_response == self.ERROR_NO_IDENTITY: - RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) - elif status_response == self.ERROR_NO_IDENTITY: - RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) + elif status_response == self.ERROR_NO_ACCESS: + RNS.log("Access was denied while attempting to update lxmd telemetry", RNS.LOG_ERROR) + elif status_response == self.ERROR_TIMEOUT: + RNS.log("Updating telemetry from lxmd failed due to timeout", RNS.LOG_ERROR) else: - RNS.log("Received status response from lxmd", RNS.LOG_DEBUG) # TODO: Remove debug self.data = status_response def pack(self): @@ -2640,63 +2828,76 @@ class LXMFPropagation(Sensor): return None def render_mqtt(self, relative_to=None): - if self.data != None: - r = self.render(relative_to=relative_to) - v = r["values"] - nid = mqtt_desthash(v["destination_hash"]) - topic = f"{self.name()}/{nid}" - rendered = { - f"{topic}/name": r["name"], - f"{topic}/icon": r["icon"], - f"{topic}/identity_hash": mqtt_desthash(v["identity_hash"]), - f"{topic}/uptime": v["uptime"], - f"{topic}/delivery_limit": v["delivery_limit"], - f"{topic}/propagation_limit": v["propagation_limit"], - f"{topic}/autopeer_maxdepth": v["autopeer_maxdepth"], - f"{topic}/from_static_only": v["from_static_only"], - f"{topic}/messagestore_count": v["messagestore_count"], - f"{topic}/messagestore_bytes": v["messagestore_bytes"], - f"{topic}/messagestore_free": v["messagestore_free"], - f"{topic}/messagestore_limit": v["messagestore_limit"], - f"{topic}/messagestore_pct": v["messagestore_pct"], - f"{topic}/client_propagation_messages_received": v["client_propagation_messages_received"], - f"{topic}/client_propagation_messages_served": v["client_propagation_messages_served"], - f"{topic}/unpeered_propagation_incoming": v["unpeered_propagation_incoming"], - f"{topic}/unpeered_propagation_rx_bytes": v["unpeered_propagation_rx_bytes"], - f"{topic}/static_peers": v["static_peers"], - f"{topic}/total_peers": v["total_peers"], - f"{topic}/max_peers": v["max_peers"], - } + try: + if self.data != None: + r = self.render(relative_to=relative_to) + v = r["values"] + nid = mqtt_desthash(v["destination_hash"]) + topic = f"{self.name()}/{nid}" + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + f"{topic}/identity_hash": mqtt_desthash(v["identity_hash"]), + f"{topic}/uptime": v["uptime"], + f"{topic}/delivery_limit": v["delivery_limit"], + f"{topic}/propagation_limit": v["propagation_limit"], + f"{topic}/autopeer_maxdepth": v["autopeer_maxdepth"], + f"{topic}/from_static_only": v["from_static_only"], + f"{topic}/messagestore_count": v["messagestore_count"], + f"{topic}/messagestore_bytes": v["messagestore_bytes"], + f"{topic}/messagestore_free": v["messagestore_free"], + f"{topic}/messagestore_limit": v["messagestore_limit"], + f"{topic}/messagestore_pct": v["messagestore_pct"], + f"{topic}/client_propagation_messages_received": v["client_propagation_messages_received"], + f"{topic}/client_propagation_messages_served": v["client_propagation_messages_served"], + f"{topic}/unpeered_propagation_incoming": v["unpeered_propagation_incoming"], + f"{topic}/unpeered_propagation_rx_bytes": v["unpeered_propagation_rx_bytes"], + f"{topic}/static_peers": v["static_peers"], + f"{topic}/total_peers": v["total_peers"], + f"{topic}/max_peers": v["max_peers"], + } - for peer_id in v["peers"]: - p = v["peers"][peer_id] - pid = mqtt_desthash(peer_id) - rendered[f"{topic}/peers/{pid}/type"] = p["type"] - rendered[f"{topic}/peers/{pid}/state"] = p["state"] - rendered[f"{topic}/peers/{pid}/alive"] = p["alive"] - rendered[f"{topic}/peers/{pid}/last_heard"] = p["last_heard"] - rendered[f"{topic}/peers/{pid}/next_sync_attempt"] = p["next_sync_attempt"] - rendered[f"{topic}/peers/{pid}/last_sync_attempt"] = p["last_sync_attempt"] - rendered[f"{topic}/peers/{pid}/sync_backoff"] = p["sync_backoff"] - rendered[f"{topic}/peers/{pid}/peering_timebase"] = p["peering_timebase"] - rendered[f"{topic}/peers/{pid}/ler"] = p["ler"] - rendered[f"{topic}/peers/{pid}/str"] = p["str"] - rendered[f"{topic}/peers/{pid}/transfer_limit"] = p["transfer_limit"] - rendered[f"{topic}/peers/{pid}/network_distance"] = p["network_distance"] - rendered[f"{topic}/peers/{pid}/rx_bytes"] = p["rx_bytes"] - rendered[f"{topic}/peers/{pid}/tx_bytes"] = p["tx_bytes"] - rendered[f"{topic}/peers/{pid}/messages_offered"] = p["messages_offered"] - rendered[f"{topic}/peers/{pid}/messages_outgoing"] = p["messages_outgoing"] - rendered[f"{topic}/peers/{pid}/messages_incoming"] = p["messages_incoming"] - rendered[f"{topic}/peers/{pid}/messages_unhandled"] = p["messages_unhandled"] - - else: - rendered = None + for peer_id in v["peers"]: + p = v["peers"][peer_id] + pid = mqtt_desthash(peer_id) + rendered[f"{topic}/peers/{pid}/type"] = p["type"] + rendered[f"{topic}/peers/{pid}/state"] = p["state"] + rendered[f"{topic}/peers/{pid}/alive"] = p["alive"] + rendered[f"{topic}/peers/{pid}/last_heard"] = p["last_heard"] + rendered[f"{topic}/peers/{pid}/next_sync_attempt"] = p["next_sync_attempt"] + rendered[f"{topic}/peers/{pid}/last_sync_attempt"] = p["last_sync_attempt"] + rendered[f"{topic}/peers/{pid}/sync_backoff"] = p["sync_backoff"] + rendered[f"{topic}/peers/{pid}/peering_timebase"] = p["peering_timebase"] + rendered[f"{topic}/peers/{pid}/ler"] = p["ler"] + rendered[f"{topic}/peers/{pid}/str"] = p["str"] + rendered[f"{topic}/peers/{pid}/transfer_limit"] = p["transfer_limit"] + rendered[f"{topic}/peers/{pid}/network_distance"] = p["network_distance"] + rendered[f"{topic}/peers/{pid}/rx_bytes"] = p["rx_bytes"] + rendered[f"{topic}/peers/{pid}/tx_bytes"] = p["tx_bytes"] + rendered[f"{topic}/peers/{pid}/messages_offered"] = p["messages_offered"] + rendered[f"{topic}/peers/{pid}/messages_outgoing"] = p["messages_outgoing"] + rendered[f"{topic}/peers/{pid}/messages_incoming"] = p["messages_incoming"] + rendered[f"{topic}/peers/{pid}/messages_unhandled"] = p["messages_unhandled"] + + else: + rendered = None - return rendered + return rendered + + except Exception as e: + RNS.log(f"Could not render lxmd telemetry data to MQTT format. The contained exception was: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + return None def mqtt_desthash(desthash): if type(desthash) == bytes: return RNS.prettyhexrep(desthash) + else: + return None + +def mqtt_hash(ihash): + if type(ihash) == bytes: + return RNS.hexrep(ihash, delimit=False) else: return None \ No newline at end of file From 17d4de36c49220fed38e204fa5ad4f8fa086a480 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 14:57:11 +0100 Subject: [PATCH 43/76] Improved MQTT error handling --- sbapp/sideband/mqtt.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index 6131d1c..85a0742 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -38,8 +38,8 @@ class MQTT(): try: if len(self.waiting_msgs) > 0: RNS.log(f"Processing {len(self.waiting_msgs)} MQTT messages", RNS.LOG_DEBUG) - self.process_queue() - RNS.log("All MQTT messages processed", RNS.LOG_DEBUG) + if self.process_queue(): + RNS.log("All MQTT messages processed", RNS.LOG_DEBUG) except Exception as e: RNS.log("An error occurred while running MQTT scheduler jobs: {e}", RNS.LOG_ERROR) @@ -82,7 +82,11 @@ class MQTT(): def process_queue(self): with self.queue_lock: - self.connect() + try: + self.connect() + except Exception as e: + RNS.log(f"An error occurred while connecting to MQTT server: {e}", RNS.LOG_ERROR) + return False try: while len(self.waiting_msgs) > 0: @@ -100,6 +104,7 @@ class MQTT(): RNS.trace_exception(e) self.disconnect() + return True def handle(self, context_dest, telemetry): remote_telemeter = Telemeter.from_packed(telemetry) From 23e0e2394e302e8da9473150f9f523e3699468ba Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 15:39:22 +0100 Subject: [PATCH 44/76] Cleanup --- sbapp/sideband/core.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index a5dc2cf..a880bac 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2283,7 +2283,9 @@ class SidebandCore(): self.setstate("app.flags.last_telemetry", time.time()) if self.config["telemetry_to_mqtt"] == True: - self.mqtt_handle_telemetry(context_dest, telemetry) + def mqtt_job(): + self.mqtt_handle_telemetry(context_dest, telemetry) + threading.Thread(target=mqtt_job, daemon=True).start() return telemetry @@ -3222,6 +3224,9 @@ class SidebandCore(): if self.config["telemetry_enabled"] == True: self.update_telemeter_config() if self.telemeter != None: + def mqtt_job(): + self.mqtt_handle_telemetry(self.lxmf_destination.hash, self.telemeter.packed()) + threading.Thread(target=mqtt_job, daemon=True).start() return self.telemeter.read_all() else: return {} From 4f201c561572f2a1d5218d71d79eb8001ddaf4ce Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 15:39:47 +0100 Subject: [PATCH 45/76] Port handling --- sbapp/sideband/mqtt.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index 85a0742..bdf7db8 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -58,6 +58,11 @@ class MQTT(): self.is_connected = False def set_server(self, host, port): + try: + port = int(port) + except: + port = None + self.host = host self.port = port or 1883 From c4cdd388b7d059b8f1399ca9c67ec213f105b222 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 15:41:08 +0100 Subject: [PATCH 46/76] Added telemetry entries --- sbapp/sideband/sense.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 3d4d314..e9edc9a 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2791,8 +2791,11 @@ class LXMFPropagation(Sensor): "peers": {} } + active_peers = 0 for peer_id in d["peers"]: p = d["peers"][peer_id] + if p["alive"] == True: + active_peers += 1 values["peers"][peer_id] = { "type": p["type"], "state": p["state"], @@ -2814,6 +2817,9 @@ class LXMFPropagation(Sensor): "messages_unhandled": p["messages"]["unhandled"], } + values["active_peers"] = active_peers + values["unreachable_peers"] = values["total_peers"] - active_peers + rendered = { "icon": "email-fast-outline", "name": "LXMF Propagation", @@ -2854,6 +2860,8 @@ class LXMFPropagation(Sensor): f"{topic}/unpeered_propagation_rx_bytes": v["unpeered_propagation_rx_bytes"], f"{topic}/static_peers": v["static_peers"], f"{topic}/total_peers": v["total_peers"], + f"{topic}/active_peers": v["active_peers"], + f"{topic}/unreachable_peers": v["unreachable_peers"], f"{topic}/max_peers": v["max_peers"], } From d459780ed70db26014026ccaf4d15411f713740c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 15:46:37 +0100 Subject: [PATCH 47/76] Added MQTT configuration UI --- sbapp/ui/objectdetails.py | 10 ++++ sbapp/ui/telemetry.py | 116 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/sbapp/ui/objectdetails.py b/sbapp/ui/objectdetails.py index 3ae6009..a5ab969 100644 --- a/sbapp/ui/objectdetails.py +++ b/sbapp/ui/objectdetails.py @@ -767,6 +767,16 @@ class RVDetails(MDRecycleView): threading.Thread(target=lj, daemon=True).start() release_function = select + + elif name == "Reticulum Transport": + te = "enabled" if s["values"]["transport_enabled"] else "disabled" + formatted_values = f"Reticulum Transport [b]{te}[/b]" + + elif name == "LXMF Propagation": + tp = str(s["values"]["total_peers"]) + ap = str(s["values"]["active_peers"]) + formatted_values = f"Peered with [b]{tp}[/b] LXMF Propagation Nodes, [b]{ap}[/b] available" + else: formatted_values = f"{name}" for vn in s["values"]: diff --git a/sbapp/ui/telemetry.py b/sbapp/ui/telemetry.py index 71858b5..f9ab75c 100644 --- a/sbapp/ui/telemetry.py +++ b/sbapp/ui/telemetry.py @@ -44,6 +44,30 @@ class Telemetry(): else: self.screen.ids.telemetry_collector.text = RNS.hexrep(self.app.sideband.config["telemetry_collector"], delimit=False) + self.screen.ids.telemetry_mqtt_host.bind(focus=self.telemetry_save) + if self.app.sideband.config["telemetry_mqtt_host"] == None: + self.screen.ids.telemetry_mqtt_host.text = "" + else: + self.screen.ids.telemetry_mqtt_host.text = self.app.sideband.config["telemetry_mqtt_host"] + + self.screen.ids.telemetry_mqtt_port.bind(focus=self.telemetry_save) + if self.app.sideband.config["telemetry_mqtt_port"] == None: + self.screen.ids.telemetry_mqtt_port.text = "" + else: + self.screen.ids.telemetry_mqtt_port.text = self.app.sideband.config["telemetry_mqtt_port"] + + self.screen.ids.telemetry_mqtt_user.bind(focus=self.telemetry_save) + if self.app.sideband.config["telemetry_mqtt_user"] == None: + self.screen.ids.telemetry_mqtt_user.text = "" + else: + self.screen.ids.telemetry_mqtt_user.text = self.app.sideband.config["telemetry_mqtt_user"] + + self.screen.ids.telemetry_mqtt_pass.bind(focus=self.telemetry_save) + if self.app.sideband.config["telemetry_mqtt_pass"] == None: + self.screen.ids.telemetry_mqtt_pass.text = "" + else: + self.screen.ids.telemetry_mqtt_pass.text = self.app.sideband.config["telemetry_mqtt_pass"] + self.screen.ids.telemetry_icon_preview.icon_color = self.app.sideband.config["telemetry_fg"] self.screen.ids.telemetry_icon_preview.md_bg_color = self.app.sideband.config["telemetry_bg"] self.screen.ids.telemetry_icon_preview.icon = self.app.sideband.config["telemetry_icon"] @@ -83,6 +107,9 @@ class Telemetry(): self.screen.ids.telemetry_allow_requests_from_anyone.active = self.app.sideband.config["telemetry_allow_requests_from_anyone"] self.screen.ids.telemetry_allow_requests_from_anyone.bind(active=self.telemetry_save) + + self.screen.ids.telemetry_to_mqtt.active = self.app.sideband.config["telemetry_to_mqtt"] + self.screen.ids.telemetry_to_mqtt.bind(active=self.telemetry_save) self.screen.ids.telemetry_scrollview.effect_cls = ScrollEffect @@ -259,6 +286,11 @@ class Telemetry(): self.app.sideband.config["telemetry_allow_requests_from_trusted"] = self.screen.ids.telemetry_allow_requests_from_trusted.active self.app.sideband.config["telemetry_allow_requests_from_anyone"] = self.screen.ids.telemetry_allow_requests_from_anyone.active self.app.sideband.config["telemetry_collector_enabled"] = self.screen.ids.telemetry_collector_enabled.active + self.app.sideband.config["telemetry_to_mqtt"] = self.screen.ids.telemetry_to_mqtt.active + self.app.sideband.config["telemetry_mqtt_host"] = self.screen.ids.telemetry_mqtt_host.text + self.app.sideband.config["telemetry_mqtt_port"] = self.screen.ids.telemetry_mqtt_port.text + self.app.sideband.config["telemetry_mqtt_user"] = self.screen.ids.telemetry_mqtt_user.text + self.app.sideband.config["telemetry_mqtt_pass"] = self.screen.ids.telemetry_mqtt_pass.text self.app.sideband.save_configuration() if run_telemetry_update: @@ -880,6 +912,90 @@ MDScreen: on_release: root.delegate.telemetry_bg_color(self) disabled: False + MDLabel: + text: "MQTT Configuration" + font_style: "H6" + + MDLabel: + id: telemetry_info6 + markup: True + text: "\\nYou can configure Sideband to send all received telemetry data to an MQTT server by specifying the relevant hostname, port and authentication details.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Send telemetry to MQTT" + font_style: "H6" + + MDSwitch: + id: telemetry_to_mqtt + pos_hint: {"center_y": 0.3} + active: False + + MDBoxLayout: + orientation: "vertical" + spacing: dp(24) + size_hint_y: None + padding: [dp(0),dp(0),dp(0),dp(0)] + #height: dp(232) + height: self.minimum_height + + MDTextField: + id: telemetry_mqtt_host + hint_text: "Server Hostname" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "vertical" + spacing: dp(24) + size_hint_y: None + padding: [dp(0),dp(0),dp(0),dp(0)] + #height: dp(232) + height: self.minimum_height + + MDTextField: + id: telemetry_mqtt_port + hint_text: "Server Port" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "vertical" + spacing: dp(24) + size_hint_y: None + padding: [dp(0),dp(0),dp(0),dp(0)] + #height: dp(232) + height: self.minimum_height + + MDTextField: + id: telemetry_mqtt_user + hint_text: "Username" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "vertical" + spacing: dp(24) + size_hint_y: None + padding: [dp(0),dp(0),dp(0),dp(60)] + #height: dp(232) + height: self.minimum_height + + MDTextField: + id: telemetry_mqtt_pass + password: True + hint_text: "Password" + text: "" + font_size: dp(24) + MDLabel: text: "Advanced Configuration" font_style: "H6" From 93aa17177b7490135b1758afaa72d04eb120fcf1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 15:59:39 +0100 Subject: [PATCH 48/76] Added RNS Transport stats sensor to sensors UI --- sbapp/sideband/core.py | 6 +++++- sbapp/ui/telemetry.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index a880bac..ce5547d 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -791,6 +791,8 @@ class SidebandCore(): self.config["telemetry_s_acceleration"] = False if not "telemetry_s_proximity" in self.config: self.config["telemetry_s_proximity"] = False + if not "telemetry_s_rns_transport" in self.config: + self.config["telemetry_s_rns_transport"] = False if not "telemetry_s_fixed_location" in self.config: self.config["telemetry_s_fixed_location"] = False if not "telemetry_s_fixed_latlon" in self.config: @@ -3176,7 +3178,9 @@ class SidebandCore(): else: self.telemeter = Telemeter(android_context=self.service_context, service=True, location_provider=self.owner_service) - sensors = ["location", "information", "battery", "pressure", "temperature", "humidity", "magnetic_field", "ambient_light", "gravity", "angular_velocity", "acceleration", "proximity"] + sensors = ["location", "information", "battery", "pressure", "temperature", "humidity", "magnetic_field", + "ambient_light", "gravity", "angular_velocity", "acceleration", "proximity", "rns_transport"] + for sensor in sensors: if self.config["telemetry_s_"+sensor]: self.telemeter.enable(sensor) diff --git a/sbapp/ui/telemetry.py b/sbapp/ui/telemetry.py index f9ab75c..6b2fe17 100644 --- a/sbapp/ui/telemetry.py +++ b/sbapp/ui/telemetry.py @@ -398,6 +398,8 @@ class Telemetry(): self.sensors_screen.ids.telemetry_s_accelerometer.bind(active=self.sensors_save) self.sensors_screen.ids.telemetry_s_proximity.active = self.app.sideband.config["telemetry_s_proximity"] self.sensors_screen.ids.telemetry_s_proximity.bind(active=self.sensors_save) + self.sensors_screen.ids.telemetry_s_rns_transport.active = self.app.sideband.config["telemetry_s_rns_transport"] + self.sensors_screen.ids.telemetry_s_rns_transport.bind(active=self.sensors_save) self.sensors_screen.ids.telemetry_s_information.active = self.app.sideband.config["telemetry_s_information"] self.sensors_screen.ids.telemetry_s_information.bind(active=self.sensors_save) self.sensors_screen.ids.telemetry_s_information_text.text = str(self.app.sideband.config["telemetry_s_information_text"]) @@ -466,6 +468,7 @@ class Telemetry(): self.app.sideband.config["telemetry_s_angular_velocity"] = self.sensors_screen.ids.telemetry_s_gyroscope.active self.app.sideband.config["telemetry_s_acceleration"] = self.sensors_screen.ids.telemetry_s_accelerometer.active self.app.sideband.config["telemetry_s_proximity"] = self.sensors_screen.ids.telemetry_s_proximity.active + self.app.sideband.config["telemetry_s_rns_transport"] = self.sensors_screen.ids.telemetry_s_rns_transport.active if self.app.sideband.config["telemetry_s_information"] != self.sensors_screen.ids.telemetry_s_information.active: run_telemetry_update = True @@ -1327,6 +1330,21 @@ MDScreen: pos_hint: {"center_y": 0.3} active: False + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Reticulum Transport Stats" + font_style: "H6" + + MDSwitch: + id: telemetry_s_rns_transport + pos_hint: {"center_y": 0.3} + active: False + MDBoxLayout: orientation: "horizontal" size_hint_y: None From 156c2d4bd2c94a803a787cf8facf8ef0128ada97 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 16:20:40 +0100 Subject: [PATCH 49/76] Fix traffic counter entries --- sbapp/sideband/sense.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index e9edc9a..efddf14 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2527,10 +2527,10 @@ class RNSTransport(Sensor): "transport_enabled": RNS.Reticulum.transport_enabled(), "transport_identity": RNS.Transport.identity.hash, "transport_uptime": time.time()-RNS.Transport.start_time if RNS.Reticulum.transport_enabled() else None, - "traffic_rxb": RNS.Transport.traffic_rxb, - "traffic_txb": RNS.Transport.traffic_txb, - "speed_rx": RNS.Transport.speed_rx, - "speed_tx": RNS.Transport.speed_tx, + "traffic_rxb": ifstats["rxb"], + "traffic_txb": ifstats["txb"], + "speed_rx": ifstats["rxs"], + "speed_tx": ifstats["txs"], "memory_used": rss, "ifstats": ifstats, "link_count": r.get_link_count(), From fc3e97b8fc20fc10ede3785d77662b98f54723b4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 25 Jan 2025 16:20:49 +0100 Subject: [PATCH 50/76] Upped queue size --- sbapp/sideband/mqtt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index bdf7db8..fb82daa 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -6,7 +6,7 @@ from sbapp.mqtt import client as mqtt from .sense import Telemeter, Commands class MQTT(): - QUEUE_MAXLEN = 1024 + QUEUE_MAXLEN = 65536 SCHEDULER_SLEEP = 1 def __init__(self): From cc87e8c10985ad1070b33c4c8af55f9ccdb52729 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 01:12:06 +0100 Subject: [PATCH 51/76] Improved RNS Transport stats --- sbapp/sideband/mqtt.py | 2 +- sbapp/sideband/sense.py | 76 ++++++++++++++++++++++++++++++----------- 2 files changed, 57 insertions(+), 21 deletions(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index fb82daa..0d69816 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -115,7 +115,7 @@ class MQTT(): remote_telemeter = Telemeter.from_packed(telemetry) read_telemetry = remote_telemeter.read_all() telemetry_timestamp = read_telemetry["time"]["utc"] - root_path = f"lxmf/telemetry/{RNS.prettyhexrep(context_dest)}" + root_path = f"lxmf/telemetry/{RNS.hexrep(context_dest, delimit=False)}" for sensor in remote_telemeter.sensors: s = remote_telemeter.sensors[sensor] topics = s.render_mqtt() diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index efddf14..e69b988 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2505,9 +2505,13 @@ class Fuel(Sensor): class RNSTransport(Sensor): SID = Sensor.SID_RNS_TRANSPORT - STALE_TIME = 5 + STALE_TIME = 1 def __init__(self): + self._last_traffic_rxb = 0 + self._last_traffic_txb = 0 + self._last_update = 0 + self._update_lock = threading.Lock() super().__init__(type(self).SID, type(self).STALE_TIME) def setup_sensor(self): @@ -2518,24 +2522,50 @@ class RNSTransport(Sensor): self.data = None def update_data(self): - r = RNS.Reticulum.get_instance() - ifstats = r.get_interface_stats() - rss = None - if "rss" in ifstats: - rss = ifstats.pop("rss") - self.data = { - "transport_enabled": RNS.Reticulum.transport_enabled(), - "transport_identity": RNS.Transport.identity.hash, - "transport_uptime": time.time()-RNS.Transport.start_time if RNS.Reticulum.transport_enabled() else None, - "traffic_rxb": ifstats["rxb"], - "traffic_txb": ifstats["txb"], - "speed_rx": ifstats["rxs"], - "speed_tx": ifstats["txs"], - "memory_used": rss, - "ifstats": ifstats, - "link_count": r.get_link_count(), - "path_table": sorted(r.get_path_table(max_hops=RNS.Transport.PATHFINDER_M-1), key=lambda e: (e["interface"], e["hops"]) ) - } + with self._update_lock: + if time.time() - self._last_update < self.STALE_TIME: + return + + r = RNS.Reticulum.get_instance() + self._last_update = time.time() + ifstats = r.get_interface_stats() + rss = None + if "rss" in ifstats: + rss = ifstats.pop("rss") + + if self.last_update == 0: + RNS.log("NO CALC DIFF") + rxs = ifstats["rxs"] + txs = ifstats["txs"] + else: + td = time.time()-self.last_update + rxd = ifstats["rxb"] - self._last_traffic_rxb + txd = ifstats["txb"] - self._last_traffic_txb + rxs = (rxd/td)*8 + txs = (txd/td)*8 + RNS.log(f"CALC DIFFS: td={td}, rxd={rxd}, txd={txd}") + RNS.log(f" rxs={rxs}, txs={txs}") + + + self._last_traffic_rxb = ifstats["rxb"] + self._last_traffic_txb = ifstats["txb"] + + self.data = { + "transport_enabled": RNS.Reticulum.transport_enabled(), + "transport_identity": RNS.Transport.identity.hash, + "transport_uptime": time.time()-RNS.Transport.start_time if RNS.Reticulum.transport_enabled() else None, + "traffic_rxb": ifstats["rxb"], + "traffic_txb": ifstats["txb"], + "speed_rx": rxs, + "speed_tx": txs, + "speed_rx_inst": ifstats["rxs"], + "speed_tx_inst": ifstats["txs"], + "memory_used": rss, + "ifstats": ifstats, + "interface_count": len(ifstats["interfaces"]), + "link_count": r.get_link_count(), + "path_table": sorted(r.get_path_table(max_hops=RNS.Transport.PATHFINDER_M-1), key=lambda e: (e["interface"], e["hops"]) ) + } def pack(self): d = self.data @@ -2592,9 +2622,12 @@ class RNSTransport(Sensor): "traffic_txb": d["traffic_txb"], "speed_rx": d["speed_rx"], "speed_tx": d["speed_tx"], + "speed_rx_inst": d["speed_rx_inst"], + "speed_tx_inst": d["speed_tx_inst"], "memory_used": d["memory_used"], "path_count": len(d["path_table"]), "link_count": d["link_count"], + "interface_count": len(ifs), "interfaces": ifs, "remote_transport_node_count": len(transport_nodes), "remote_transport_nodes": transport_nodes, @@ -2632,9 +2665,12 @@ class RNSTransport(Sensor): f"{topic}/traffic_txb": v["traffic_txb"], f"{topic}/speed_rx": v["speed_rx"], f"{topic}/speed_tx": v["speed_tx"], + f"{topic}/speed_rx_inst": v["speed_rx_inst"], + f"{topic}/speed_tx_inst": v["speed_tx_inst"], f"{topic}/memory_used": v["memory_used"], f"{topic}/path_count": v["path_count"], f"{topic}/link_count": v["link_count"], + f"{topic}/interface_count": v["interface_count"], f"{topic}/remote_transport_node_count": v["remote_transport_node_count"], } @@ -2900,7 +2936,7 @@ class LXMFPropagation(Sensor): def mqtt_desthash(desthash): if type(desthash) == bytes: - return RNS.prettyhexrep(desthash) + return RNS.hexrep(desthash, delimit=False) else: return None From b03d91d2067f802ccdbfe67952f21be502fa0076 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 12:15:26 +0100 Subject: [PATCH 52/76] Background updater for lxmd sensor --- sbapp/sideband/sense.py | 71 +++++++++++++++++++++++++++++------------ 1 file changed, 51 insertions(+), 20 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index e69b988..d5f0c54 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2733,11 +2733,15 @@ class RNSTransport(Sensor): class LXMFPropagation(Sensor): SID = Sensor.SID_LXMF_PROPAGATION - STALE_TIME = 120 + STALE_TIME = 45 def __init__(self): self.identity = None self.lxmd = None + self._last_update = 0 + self._update_interval = 60 + self._update_lock = threading.Lock() + self._running = False super().__init__(type(self).SID, type(self).STALE_TIME) def set_identity(self, identity): @@ -2751,34 +2755,61 @@ class LXMFPropagation(Sensor): except Exception as e: RNS.log("Could not load LXMF propagation sensor identity from \"{file_path}\"", RNS.LOG_ERROR) + def _update_job(self): + while self._running: + self._update_data() + time.sleep(self._update_interval) + + def _start_update_job(self): + if not self._running: + self._running = True + update_thread = threading.Thread(target=self._update_job, daemon=True) + update_thread.start() + def setup_sensor(self): self.update_data() def teardown_sensor(self): + self._running = False self.identity = None self.data = None def update_data(self): - if self.identity != None: - if self.lxmd == None: - import LXMF.LXMPeer as LXMPeer - import LXMF.Utilities.lxmd as lxmd - self.ERROR_NO_IDENTITY = LXMPeer.LXMPeer.ERROR_NO_IDENTITY - self.ERROR_NO_ACCESS = LXMPeer.LXMPeer.ERROR_NO_ACCESS - self.ERROR_TIMEOUT = LXMPeer.LXMPeer.ERROR_TIMEOUT - self.lxmd = lxmd + # This sensor runs the actual data updates + # in the background. An update_data request + # will simply start the update job if it is + # not already running. + if not self._running: + RNS.log(self) + self._start_update_job() - status_response = self.lxmd.query_status(identity=self.identity) - if status_response == None: - RNS.log("Status response from lxmd was received, but contained no data", RNS.LOG_ERROR) - elif status_response == self.ERROR_NO_IDENTITY: - RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) - elif status_response == self.ERROR_NO_ACCESS: - RNS.log("Access was denied while attempting to update lxmd telemetry", RNS.LOG_ERROR) - elif status_response == self.ERROR_TIMEOUT: - RNS.log("Updating telemetry from lxmd failed due to timeout", RNS.LOG_ERROR) - else: - self.data = status_response + def _update_data(self): + if not self.synthesized: + with self._update_lock: + if time.time() - self._last_update < self.STALE_TIME: + return + + if self.identity != None: + if self.lxmd == None: + import LXMF.LXMPeer as LXMPeer + import LXMF.Utilities.lxmd as lxmd + self.ERROR_NO_IDENTITY = LXMPeer.LXMPeer.ERROR_NO_IDENTITY + self.ERROR_NO_ACCESS = LXMPeer.LXMPeer.ERROR_NO_ACCESS + self.ERROR_TIMEOUT = LXMPeer.LXMPeer.ERROR_TIMEOUT + self.lxmd = lxmd + + self._last_update = time.time() + status_response = self.lxmd.query_status(identity=self.identity) + if status_response == None: + RNS.log("Status response from lxmd was received, but contained no data", RNS.LOG_ERROR) + elif status_response == self.ERROR_NO_IDENTITY: + RNS.log("Updating telemetry from lxmd failed due to missing identification", RNS.LOG_ERROR) + elif status_response == self.ERROR_NO_ACCESS: + RNS.log("Access was denied while attempting to update lxmd telemetry", RNS.LOG_ERROR) + elif status_response == self.ERROR_TIMEOUT: + RNS.log("Updating telemetry from lxmd failed due to timeout", RNS.LOG_ERROR) + else: + self.data = status_response def pack(self): d = self.data From ebc4462a508639551b91dbe6748097a090b0b0ae Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 12:21:28 +0100 Subject: [PATCH 53/76] Updated text --- sbapp/ui/telemetry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/ui/telemetry.py b/sbapp/ui/telemetry.py index 6b2fe17..1215bd3 100644 --- a/sbapp/ui/telemetry.py +++ b/sbapp/ui/telemetry.py @@ -922,7 +922,7 @@ MDScreen: MDLabel: id: telemetry_info6 markup: True - text: "\\nYou can configure Sideband to send all received telemetry data to an MQTT server by specifying the relevant hostname, port and authentication details.\\n" + text: "\\nFor integration with other systems, you can configure Sideband to send all known telemetry data to an MQTT server in real-time as it is received or generated.\\n" size_hint_y: None text_size: self.width, None height: self.texture_size[1] From a812f0a5892b60a2fcf075eec8d1cdc38daa07fd Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 12:53:40 +0100 Subject: [PATCH 54/76] Added lxmd telemetry plugin to examples --- docs/example_plugins/lxmd_telemetry.py | 41 ++++++++++++++++++++++++++ docs/example_plugins/telemetry.py | 3 +- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 docs/example_plugins/lxmd_telemetry.py diff --git a/docs/example_plugins/lxmd_telemetry.py b/docs/example_plugins/lxmd_telemetry.py new file mode 100644 index 0000000..bef47b9 --- /dev/null +++ b/docs/example_plugins/lxmd_telemetry.py @@ -0,0 +1,41 @@ +# This is an LXMd telemetry plugin that +# queries a running LXMF Propagation Node +# for status and statistics. + +import RNS + +class LXMdTelemetryPlugin(SidebandTelemetryPlugin): + plugin_name = "lxmd_telemetry" + + def start(self): + # Do any initialisation work here + RNS.log("LXMd telemetry plugin starting...") + + # And finally call start on superclass + super().start() + + def stop(self): + # Do any teardown work here + pass + + # And finally call stop on superclass + super().stop() + + def update_telemetry(self, telemeter): + if telemeter != None: + if not "lxmf_propagation" in telemeter.sensors: + # Create lxmd status sensor if it is not already + # enabled in the running telemeter instance + telemeter.enable("lxmf_propagation") + + # Set the identity file used to communicate with + # the running LXMd instance. + telemeter.sensors["lxmf_propagation"].set_identity("~/.lxmd/identity") + + # You can also get LXMF Propagation Node stats + # from an LXMd instance running inside nomadnet + # telemeter.sensors["lxmf_propagation"].set_identity("~/.nomadnetwork/storage/identity") + +# Finally, tell Sideband what class in this +# file is the actual plugin class. +plugin_class = LXMdTelemetryPlugin diff --git a/docs/example_plugins/telemetry.py b/docs/example_plugins/telemetry.py index c6993e9..fc4f618 100644 --- a/docs/example_plugins/telemetry.py +++ b/docs/example_plugins/telemetry.py @@ -59,7 +59,8 @@ class BasicTelemetryPlugin(SidebandTelemetryPlugin): # Create fuel sensor telemeter.synthesize("fuel") - telemeter.sensors["fuel"].update_entry(capacity=75, level=61) + telemeter.sensors["fuel"].update_entry(capacity=75, level=61, type_label="Main") + telemeter.sensors["fuel"].update_entry(capacity=15, level=15, type_label="Reserve") # Finally, tell Sideband what class in this # file is the actual plugin class. From 0d548e4cbb8337b3f9842821431a3e737029afcf Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 13:02:05 +0100 Subject: [PATCH 55/76] Fixed fstring parsing error on Android --- sbapp/sideband/sense.py | 79 ++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 33 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index d5f0c54..7716417 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -1757,8 +1757,9 @@ class PowerConsumption(Sensor): f"{topic}/icon": r["icon"], } for consumer in r["values"]: - rendered[f"{topic}/{consumer["label"]}/w"] = consumer["w"] - rendered[f"{topic}/{consumer["label"]}/icon"] = consumer["custom_icon"] + cl = consumer["label"] + rendered[f"{topic}/{cl}/w"] = consumer["w"] + rendered[f"{topic}/{cl}/icon"] = consumer["custom_icon"] else: rendered = None @@ -1854,8 +1855,9 @@ class PowerProduction(Sensor): f"{topic}/icon": r["icon"], } for producer in r["values"]: - rendered[f"{topic}/{producer["label"]}/w"] = producer["w"] - rendered[f"{topic}/{producer["label"]}/icon"] = producer["custom_icon"] + pl = producer["label"] + rendered[f"{topic}/{pl}/w"] = producer["w"] + rendered[f"{topic}/{pl}/icon"] = producer["custom_icon"] else: rendered = None @@ -1956,11 +1958,12 @@ class Processor(Sensor): f"{topic}/icon": r["icon"], } for cpu in r["values"]: - rendered[f"{topic}/{cpu["label"]}/current_load"] = cpu["current_load"] - rendered[f"{topic}/{cpu["label"]}/avgs/1m"] = cpu["load_avgs"][0] - rendered[f"{topic}/{cpu["label"]}/avgs/5m"] = cpu["load_avgs"][1] - rendered[f"{topic}/{cpu["label"]}/avgs/15m"] = cpu["load_avgs"][2] - rendered[f"{topic}/{cpu["label"]}/clock"] = cpu["clock"] + cl = cpu["label"] + rendered[f"{topic}/{cl}/current_load"] = cpu["current_load"] + rendered[f"{topic}/{cl}/avgs/1m"] = cpu["load_avgs"][0] + rendered[f"{topic}/{cl}/avgs/5m"] = cpu["load_avgs"][1] + rendered[f"{topic}/{cl}/avgs/15m"] = cpu["load_avgs"][2] + rendered[f"{topic}/{cl}/clock"] = cpu["clock"] else: rendered = None @@ -2062,10 +2065,11 @@ class RandomAccessMemory(Sensor): f"{topic}/icon": r["icon"], } for ram in r["values"]: - rendered[f"{topic}/{ram["label"]}/capacity"] = ram["capacity"] - rendered[f"{topic}/{ram["label"]}/used"] = ram["used"] - rendered[f"{topic}/{ram["label"]}/free"] = ram["free"] - rendered[f"{topic}/{ram["label"]}/percent"] = ram["percent"] + rl = ram["label"] + rendered[f"{topic}/{rl}/capacity"] = ram["capacity"] + rendered[f"{topic}/{rl}/used"] = ram["used"] + rendered[f"{topic}/{rl}/free"] = ram["free"] + rendered[f"{topic}/{rl}/percent"] = ram["percent"] else: rendered = None @@ -2167,10 +2171,11 @@ class NonVolatileMemory(Sensor): f"{topic}/icon": r["icon"], } for nvm in r["values"]: - rendered[f"{topic}/{nvm["label"]}/capacity"] = nvm["capacity"] - rendered[f"{topic}/{nvm["label"]}/used"] = nvm["used"] - rendered[f"{topic}/{nvm["label"]}/free"] = nvm["free"] - rendered[f"{topic}/{nvm["label"]}/percent"] = nvm["percent"] + nl = nvm["label"] + rendered[f"{topic}/{nl}/capacity"] = nvm["capacity"] + rendered[f"{topic}/{nl}/used"] = nvm["used"] + rendered[f"{topic}/{nl}/free"] = nvm["free"] + rendered[f"{topic}/{nl}/percent"] = nvm["percent"] else: rendered = None @@ -2270,8 +2275,9 @@ class Custom(Sensor): f"{topic}/icon": r["icon"], } for custom in r["values"]: - rendered[f"{topic}/{custom["label"]}/value"] = custom["value"] - rendered[f"{topic}/{custom["label"]}/icon"] = custom["custom_icon"] + cl = custom["label"] + rendered[f"{topic}/{cl}/value"] = custom["value"] + rendered[f"{topic}/{cl}/icon"] = custom["custom_icon"] else: rendered = None @@ -2379,12 +2385,13 @@ class Tank(Sensor): f"{topic}/icon": r["icon"], } for tank in r["values"]: - rendered[f"{topic}/{tank["label"]}/unit"] = tank["unit"] - rendered[f"{topic}/{tank["label"]}/capacity"] = tank["capacity"] - rendered[f"{topic}/{tank["label"]}/level"] = tank["level"] - rendered[f"{topic}/{tank["label"]}/free"] = tank["free"] - rendered[f"{topic}/{tank["label"]}/percent"] = tank["percent"] - rendered[f"{topic}/{tank["label"]}/icon"] = tank["custom_icon"] + tl = tank["label"] + rendered[f"{topic}/{tl}/unit"] = tank["unit"] + rendered[f"{topic}/{tl}/capacity"] = tank["capacity"] + rendered[f"{topic}/{tl}/level"] = tank["level"] + rendered[f"{topic}/{tl}/free"] = tank["free"] + rendered[f"{topic}/{tl}/percent"] = tank["percent"] + rendered[f"{topic}/{tl}/icon"] = tank["custom_icon"] else: rendered = None @@ -2492,12 +2499,13 @@ class Fuel(Sensor): f"{topic}/icon": r["icon"], } for tank in r["values"]: - rendered[f"{topic}/{tank["label"]}/unit"] = tank["unit"] - rendered[f"{topic}/{tank["label"]}/capacity"] = tank["capacity"] - rendered[f"{topic}/{tank["label"]}/level"] = tank["level"] - rendered[f"{topic}/{tank["label"]}/free"] = tank["free"] - rendered[f"{topic}/{tank["label"]}/percent"] = tank["percent"] - rendered[f"{topic}/{tank["label"]}/icon"] = tank["custom_icon"] + tl = tank["label"] + rendered[f"{topic}/{tl}/unit"] = tank["unit"] + rendered[f"{topic}/{tl}/capacity"] = tank["capacity"] + rendered[f"{topic}/{tl}/level"] = tank["level"] + rendered[f"{topic}/{tl}/free"] = tank["free"] + rendered[f"{topic}/{tl}/percent"] = tank["percent"] + rendered[f"{topic}/{tl}/icon"] = tank["custom_icon"] else: rendered = None @@ -2733,13 +2741,13 @@ class RNSTransport(Sensor): class LXMFPropagation(Sensor): SID = Sensor.SID_LXMF_PROPAGATION - STALE_TIME = 45 + STALE_TIME = 15 def __init__(self): self.identity = None self.lxmd = None self._last_update = 0 - self._update_interval = 60 + self._update_interval = 18 self._update_lock = threading.Lock() self._running = False super().__init__(type(self).SID, type(self).STALE_TIME) @@ -2755,6 +2763,11 @@ class LXMFPropagation(Sensor): except Exception as e: RNS.log("Could not load LXMF propagation sensor identity from \"{file_path}\"", RNS.LOG_ERROR) + if self.identity != None: + self.setup_sensor() + else: + RNS.log(f"Identity was not configured for {self}. Updates will not occur until a valid identity is configured.", RNS.LOG_ERROR) + def _update_job(self): while self._running: self._update_data() From 120d29db7528fcf510008e451d73e571c68d8168 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 14:10:45 +0100 Subject: [PATCH 56/76] Moved mqtt lib --- sbapp/pmqtt/__init__.py | 5 + sbapp/pmqtt/client.py | 4856 +++++++++++++++++++++++++++++++ sbapp/pmqtt/enums.py | 113 + sbapp/pmqtt/matcher.py | 78 + sbapp/pmqtt/packettypes.py | 43 + sbapp/pmqtt/properties.py | 421 +++ sbapp/pmqtt/publish.py | 306 ++ sbapp/pmqtt/py.typed | 0 sbapp/pmqtt/reasoncodes.py | 223 ++ sbapp/pmqtt/subscribe.py | 281 ++ sbapp/pmqtt/subscribeoptions.py | 113 + 11 files changed, 6439 insertions(+) create mode 100644 sbapp/pmqtt/__init__.py create mode 100644 sbapp/pmqtt/client.py create mode 100644 sbapp/pmqtt/enums.py create mode 100644 sbapp/pmqtt/matcher.py create mode 100644 sbapp/pmqtt/packettypes.py create mode 100644 sbapp/pmqtt/properties.py create mode 100644 sbapp/pmqtt/publish.py create mode 100644 sbapp/pmqtt/py.typed create mode 100644 sbapp/pmqtt/reasoncodes.py create mode 100644 sbapp/pmqtt/subscribe.py create mode 100644 sbapp/pmqtt/subscribeoptions.py diff --git a/sbapp/pmqtt/__init__.py b/sbapp/pmqtt/__init__.py new file mode 100644 index 0000000..9372c8f --- /dev/null +++ b/sbapp/pmqtt/__init__.py @@ -0,0 +1,5 @@ +__version__ = "2.1.1.dev0" + + +class MQTTException(Exception): + pass diff --git a/sbapp/pmqtt/client.py b/sbapp/pmqtt/client.py new file mode 100644 index 0000000..37763cc --- /dev/null +++ b/sbapp/pmqtt/client.py @@ -0,0 +1,4856 @@ +# Copyright (c) 2012-2019 Roger Light and others +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Roger Light - initial API and implementation +# Ian Craggs - MQTT V5 support +""" +This is an MQTT client module. MQTT is a lightweight pub/sub messaging +protocol that is easy to implement and suitable for low powered devices. +""" +from __future__ import annotations + +import base64 +import collections +import errno +import hashlib +import logging +import os +import platform +import select +import socket +import string +import struct +import threading +import time +import urllib.parse +import urllib.request +import uuid +import warnings +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, NamedTuple, Sequence, Tuple, Union, cast + +from .packettypes import PacketTypes + +from .enums import CallbackAPIVersion, ConnackCode, LogLevel, MessageState, MessageType, MQTTErrorCode, MQTTProtocolVersion, PahoClientMode, _ConnectionState +from .matcher import MQTTMatcher +from .properties import Properties +from .reasoncodes import ReasonCode, ReasonCodes +from .subscribeoptions import SubscribeOptions + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + +if TYPE_CHECKING: + try: + from typing import TypedDict # type: ignore + except ImportError: + from typing_extensions import TypedDict + + try: + from typing import Protocol # type: ignore + except ImportError: + from typing_extensions import Protocol # type: ignore + + class _InPacket(TypedDict): + command: int + have_remaining: int + remaining_count: list[int] + remaining_mult: int + remaining_length: int + packet: bytearray + to_process: int + pos: int + + + class _OutPacket(TypedDict): + command: int + mid: int + qos: int + pos: int + to_process: int + packet: bytes + info: MQTTMessageInfo | None + + class SocketLike(Protocol): + def recv(self, buffer_size: int) -> bytes: + ... + def send(self, buffer: bytes) -> int: + ... + def close(self) -> None: + ... + def fileno(self) -> int: + ... + def setblocking(self, flag: bool) -> None: + ... + + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +try: + import socks # type: ignore[import-untyped] +except ImportError: + socks = None # type: ignore[assignment] + + +try: + # Use monotonic clock if available + time_func = time.monotonic +except AttributeError: + time_func = time.time + +try: + import dns.resolver + + HAVE_DNS = True +except ImportError: + HAVE_DNS = False + + +if platform.system() == 'Windows': + EAGAIN = errno.WSAEWOULDBLOCK # type: ignore[attr-defined] +else: + EAGAIN = errno.EAGAIN + +# Avoid linter complain. We kept importing it as ReasonCodes (plural) for compatibility +_ = ReasonCodes + +# Keep copy of enums values for compatibility. +CONNECT = MessageType.CONNECT +CONNACK = MessageType.CONNACK +PUBLISH = MessageType.PUBLISH +PUBACK = MessageType.PUBACK +PUBREC = MessageType.PUBREC +PUBREL = MessageType.PUBREL +PUBCOMP = MessageType.PUBCOMP +SUBSCRIBE = MessageType.SUBSCRIBE +SUBACK = MessageType.SUBACK +UNSUBSCRIBE = MessageType.UNSUBSCRIBE +UNSUBACK = MessageType.UNSUBACK +PINGREQ = MessageType.PINGREQ +PINGRESP = MessageType.PINGRESP +DISCONNECT = MessageType.DISCONNECT +AUTH = MessageType.AUTH + +# Log levels +MQTT_LOG_INFO = LogLevel.MQTT_LOG_INFO +MQTT_LOG_NOTICE = LogLevel.MQTT_LOG_NOTICE +MQTT_LOG_WARNING = LogLevel.MQTT_LOG_WARNING +MQTT_LOG_ERR = LogLevel.MQTT_LOG_ERR +MQTT_LOG_DEBUG = LogLevel.MQTT_LOG_DEBUG +LOGGING_LEVEL = { + LogLevel.MQTT_LOG_DEBUG: logging.DEBUG, + LogLevel.MQTT_LOG_INFO: logging.INFO, + LogLevel.MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level + LogLevel.MQTT_LOG_WARNING: logging.WARNING, + LogLevel.MQTT_LOG_ERR: logging.ERROR, +} + +# CONNACK codes +CONNACK_ACCEPTED = ConnackCode.CONNACK_ACCEPTED +CONNACK_REFUSED_PROTOCOL_VERSION = ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION +CONNACK_REFUSED_IDENTIFIER_REJECTED = ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED +CONNACK_REFUSED_SERVER_UNAVAILABLE = ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE +CONNACK_REFUSED_BAD_USERNAME_PASSWORD = ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD +CONNACK_REFUSED_NOT_AUTHORIZED = ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED + +# Message state +mqtt_ms_invalid = MessageState.MQTT_MS_INVALID +mqtt_ms_publish = MessageState.MQTT_MS_PUBLISH +mqtt_ms_wait_for_puback = MessageState.MQTT_MS_WAIT_FOR_PUBACK +mqtt_ms_wait_for_pubrec = MessageState.MQTT_MS_WAIT_FOR_PUBREC +mqtt_ms_resend_pubrel = MessageState.MQTT_MS_RESEND_PUBREL +mqtt_ms_wait_for_pubrel = MessageState.MQTT_MS_WAIT_FOR_PUBREL +mqtt_ms_resend_pubcomp = MessageState.MQTT_MS_RESEND_PUBCOMP +mqtt_ms_wait_for_pubcomp = MessageState.MQTT_MS_WAIT_FOR_PUBCOMP +mqtt_ms_send_pubrec = MessageState.MQTT_MS_SEND_PUBREC +mqtt_ms_queued = MessageState.MQTT_MS_QUEUED + +MQTT_ERR_AGAIN = MQTTErrorCode.MQTT_ERR_AGAIN +MQTT_ERR_SUCCESS = MQTTErrorCode.MQTT_ERR_SUCCESS +MQTT_ERR_NOMEM = MQTTErrorCode.MQTT_ERR_NOMEM +MQTT_ERR_PROTOCOL = MQTTErrorCode.MQTT_ERR_PROTOCOL +MQTT_ERR_INVAL = MQTTErrorCode.MQTT_ERR_INVAL +MQTT_ERR_NO_CONN = MQTTErrorCode.MQTT_ERR_NO_CONN +MQTT_ERR_CONN_REFUSED = MQTTErrorCode.MQTT_ERR_CONN_REFUSED +MQTT_ERR_NOT_FOUND = MQTTErrorCode.MQTT_ERR_NOT_FOUND +MQTT_ERR_CONN_LOST = MQTTErrorCode.MQTT_ERR_CONN_LOST +MQTT_ERR_TLS = MQTTErrorCode.MQTT_ERR_TLS +MQTT_ERR_PAYLOAD_SIZE = MQTTErrorCode.MQTT_ERR_PAYLOAD_SIZE +MQTT_ERR_NOT_SUPPORTED = MQTTErrorCode.MQTT_ERR_NOT_SUPPORTED +MQTT_ERR_AUTH = MQTTErrorCode.MQTT_ERR_AUTH +MQTT_ERR_ACL_DENIED = MQTTErrorCode.MQTT_ERR_ACL_DENIED +MQTT_ERR_UNKNOWN = MQTTErrorCode.MQTT_ERR_UNKNOWN +MQTT_ERR_ERRNO = MQTTErrorCode.MQTT_ERR_ERRNO +MQTT_ERR_QUEUE_SIZE = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE +MQTT_ERR_KEEPALIVE = MQTTErrorCode.MQTT_ERR_KEEPALIVE + +MQTTv31 = MQTTProtocolVersion.MQTTv31 +MQTTv311 = MQTTProtocolVersion.MQTTv311 +MQTTv5 = MQTTProtocolVersion.MQTTv5 + +MQTT_CLIENT = PahoClientMode.MQTT_CLIENT +MQTT_BRIDGE = PahoClientMode.MQTT_BRIDGE + +# For MQTT V5, use the clean start flag only on the first successful connect +MQTT_CLEAN_START_FIRST_ONLY: CleanStartOption = 3 + +sockpair_data = b"0" + +# Payload support all those type and will be converted to bytes: +# * str are utf8 encoded +# * int/float are converted to string and utf8 encoded (e.g. 1 is converted to b"1") +# * None is converted to a zero-length payload (i.e. b"") +PayloadType = Union[str, bytes, bytearray, int, float, None] + +HTTPHeader = Dict[str, str] +WebSocketHeaders = Union[Callable[[HTTPHeader], HTTPHeader], HTTPHeader] + +CleanStartOption = Union[bool, Literal[3]] + + +class ConnectFlags(NamedTuple): + """Contains additional information passed to `on_connect` callback""" + + session_present: bool + """ + this flag is useful for clients that are + using clean session set to False only (MQTTv3) or clean_start = False (MQTTv5). + In that case, if client that reconnects to a broker that it has previously + connected to, this flag indicates whether the broker still has the + session information for the client. If true, the session still exists. + """ + + +class DisconnectFlags(NamedTuple): + """Contains additional information passed to `on_disconnect` callback""" + + is_disconnect_packet_from_server: bool + """ + tells whether this on_disconnect call is the result + of receiving an DISCONNECT packet from the broker or if the on_disconnect is only + generated by the client library. + When true, the reason code is generated by the broker. + """ + + +CallbackOnConnect_v1_mqtt3 = Callable[["Client", Any, Dict[str, Any], MQTTErrorCode], None] +CallbackOnConnect_v1_mqtt5 = Callable[["Client", Any, Dict[str, Any], ReasonCode, Union[Properties, None]], None] +CallbackOnConnect_v1 = Union[CallbackOnConnect_v1_mqtt5, CallbackOnConnect_v1_mqtt3] +CallbackOnConnect_v2 = Callable[["Client", Any, ConnectFlags, ReasonCode, Union[Properties, None]], None] +CallbackOnConnect = Union[CallbackOnConnect_v1, CallbackOnConnect_v2] +CallbackOnConnectFail = Callable[["Client", Any], None] +CallbackOnDisconnect_v1_mqtt3 = Callable[["Client", Any, MQTTErrorCode], None] +CallbackOnDisconnect_v1_mqtt5 = Callable[["Client", Any, Union[ReasonCode, int, None], Union[Properties, None]], None] +CallbackOnDisconnect_v1 = Union[CallbackOnDisconnect_v1_mqtt3, CallbackOnDisconnect_v1_mqtt5] +CallbackOnDisconnect_v2 = Callable[["Client", Any, DisconnectFlags, ReasonCode, Union[Properties, None]], None] +CallbackOnDisconnect = Union[CallbackOnDisconnect_v1, CallbackOnDisconnect_v2] +CallbackOnLog = Callable[["Client", Any, int, str], None] +CallbackOnMessage = Callable[["Client", Any, "MQTTMessage"], None] +CallbackOnPreConnect = Callable[["Client", Any], None] +CallbackOnPublish_v1 = Callable[["Client", Any, int], None] +CallbackOnPublish_v2 = Callable[["Client", Any, int, ReasonCode, Properties], None] +CallbackOnPublish = Union[CallbackOnPublish_v1, CallbackOnPublish_v2] +CallbackOnSocket = Callable[["Client", Any, "SocketLike"], None] +CallbackOnSubscribe_v1_mqtt3 = Callable[["Client", Any, int, Tuple[int, ...]], None] +CallbackOnSubscribe_v1_mqtt5 = Callable[["Client", Any, int, List[ReasonCode], Properties], None] +CallbackOnSubscribe_v1 = Union[CallbackOnSubscribe_v1_mqtt3, CallbackOnSubscribe_v1_mqtt5] +CallbackOnSubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None] +CallbackOnSubscribe = Union[CallbackOnSubscribe_v1, CallbackOnSubscribe_v2] +CallbackOnUnsubscribe_v1_mqtt3 = Callable[["Client", Any, int], None] +CallbackOnUnsubscribe_v1_mqtt5 = Callable[["Client", Any, int, Properties, Union[ReasonCode, List[ReasonCode]]], None] +CallbackOnUnsubscribe_v1 = Union[CallbackOnUnsubscribe_v1_mqtt3, CallbackOnUnsubscribe_v1_mqtt5] +CallbackOnUnsubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None] +CallbackOnUnsubscribe = Union[CallbackOnUnsubscribe_v1, CallbackOnUnsubscribe_v2] + +# This is needed for typing because class Client redefined the name "socket" +_socket = socket + + +class WebsocketConnectionError(ConnectionError): + """ WebsocketConnectionError is a subclass of ConnectionError. + + It's raised when unable to perform the Websocket handshake. + """ + pass + + +def error_string(mqtt_errno: MQTTErrorCode | int) -> str: + """Return the error string associated with an mqtt error number.""" + if mqtt_errno == MQTT_ERR_SUCCESS: + return "No error." + elif mqtt_errno == MQTT_ERR_NOMEM: + return "Out of memory." + elif mqtt_errno == MQTT_ERR_PROTOCOL: + return "A network protocol error occurred when communicating with the broker." + elif mqtt_errno == MQTT_ERR_INVAL: + return "Invalid function arguments provided." + elif mqtt_errno == MQTT_ERR_NO_CONN: + return "The client is not currently connected." + elif mqtt_errno == MQTT_ERR_CONN_REFUSED: + return "The connection was refused." + elif mqtt_errno == MQTT_ERR_NOT_FOUND: + return "Message not found (internal error)." + elif mqtt_errno == MQTT_ERR_CONN_LOST: + return "The connection was lost." + elif mqtt_errno == MQTT_ERR_TLS: + return "A TLS error occurred." + elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE: + return "Payload too large." + elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED: + return "This feature is not supported." + elif mqtt_errno == MQTT_ERR_AUTH: + return "Authorisation failed." + elif mqtt_errno == MQTT_ERR_ACL_DENIED: + return "Access denied by ACL." + elif mqtt_errno == MQTT_ERR_UNKNOWN: + return "Unknown error." + elif mqtt_errno == MQTT_ERR_ERRNO: + return "Error defined by errno." + elif mqtt_errno == MQTT_ERR_QUEUE_SIZE: + return "Message queue full." + elif mqtt_errno == MQTT_ERR_KEEPALIVE: + return "Client or broker did not communicate in the keepalive interval." + else: + return "Unknown error." + + +def connack_string(connack_code: int|ReasonCode) -> str: + """Return the string associated with a CONNACK result or CONNACK reason code.""" + if isinstance(connack_code, ReasonCode): + return str(connack_code) + + if connack_code == CONNACK_ACCEPTED: + return "Connection Accepted." + elif connack_code == CONNACK_REFUSED_PROTOCOL_VERSION: + return "Connection Refused: unacceptable protocol version." + elif connack_code == CONNACK_REFUSED_IDENTIFIER_REJECTED: + return "Connection Refused: identifier rejected." + elif connack_code == CONNACK_REFUSED_SERVER_UNAVAILABLE: + return "Connection Refused: broker unavailable." + elif connack_code == CONNACK_REFUSED_BAD_USERNAME_PASSWORD: + return "Connection Refused: bad user name or password." + elif connack_code == CONNACK_REFUSED_NOT_AUTHORIZED: + return "Connection Refused: not authorised." + else: + return "Connection Refused: unknown reason." + + +def convert_connack_rc_to_reason_code(connack_code: ConnackCode) -> ReasonCode: + if connack_code == ConnackCode.CONNACK_ACCEPTED: + return ReasonCode(PacketTypes.CONNACK, "Success") + if connack_code == ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION: + return ReasonCode(PacketTypes.CONNACK, "Unsupported protocol version") + if connack_code == ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED: + return ReasonCode(PacketTypes.CONNACK, "Client identifier not valid") + if connack_code == ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE: + return ReasonCode(PacketTypes.CONNACK, "Server unavailable") + if connack_code == ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD: + return ReasonCode(PacketTypes.CONNACK, "Bad user name or password") + if connack_code == ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED: + return ReasonCode(PacketTypes.CONNACK, "Not authorized") + + return ReasonCode(PacketTypes.CONNACK, "Unspecified error") + + +def convert_disconnect_error_code_to_reason_code(rc: MQTTErrorCode) -> ReasonCode: + if rc == MQTTErrorCode.MQTT_ERR_SUCCESS: + return ReasonCode(PacketTypes.DISCONNECT, "Success") + if rc == MQTTErrorCode.MQTT_ERR_KEEPALIVE: + return ReasonCode(PacketTypes.DISCONNECT, "Keep alive timeout") + if rc == MQTTErrorCode.MQTT_ERR_CONN_LOST: + return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error") + return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error") + + +def _base62( + num: int, + base: str = string.digits + string.ascii_letters, + padding: int = 1, +) -> str: + """Convert a number to base-62 representation.""" + if num < 0: + raise ValueError("Number must be positive or zero") + digits = [] + while num: + num, rest = divmod(num, 62) + digits.append(base[rest]) + digits.extend(base[0] for _ in range(len(digits), padding)) + return ''.join(reversed(digits)) + + +def topic_matches_sub(sub: str, topic: str) -> bool: + """Check whether a topic matches a subscription. + + For example: + + * Topic "foo/bar" would match the subscription "foo/#" or "+/bar" + * Topic "non/matching" would not match the subscription "non/+/+" + """ + matcher = MQTTMatcher() + matcher[sub] = True + try: + next(matcher.iter_match(topic)) + return True + except StopIteration: + return False + + +def _socketpair_compat() -> tuple[socket.socket, socket.socket]: + """TCP/IP socketpair including Windows support""" + listensock = socket.socket( + socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) + listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listensock.bind(("127.0.0.1", 0)) + listensock.listen(1) + + iface, port = listensock.getsockname() + sock1 = socket.socket( + socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) + sock1.setblocking(False) + try: + sock1.connect(("127.0.0.1", port)) + except BlockingIOError: + pass + sock2, address = listensock.accept() + sock2.setblocking(False) + listensock.close() + return (sock1, sock2) + + +def _force_bytes(s: str | bytes) -> bytes: + if isinstance(s, str): + return s.encode("utf-8") + return s + + +def _encode_payload(payload: str | bytes | bytearray | int | float | None) -> bytes|bytearray: + if isinstance(payload, str): + return payload.encode("utf-8") + + if isinstance(payload, (int, float)): + return str(payload).encode("ascii") + + if payload is None: + return b"" + + if not isinstance(payload, (bytes, bytearray)): + raise TypeError( + "payload must be a string, bytearray, int, float or None." + ) + + return payload + + +class MQTTMessageInfo: + __slots__ = 'mid', '_published', '_condition', 'rc', '_iterpos' + + def __init__(self, mid: int): + self.mid = mid + """ The message Id (int)""" + self._published = False + self._condition = threading.Condition() + self.rc: MQTTErrorCode = MQTTErrorCode.MQTT_ERR_SUCCESS + """ The `MQTTErrorCode` that give status for this message. + This value could change until the message `is_published`""" + self._iterpos = 0 + + def __str__(self) -> str: + return str((self.rc, self.mid)) + + def __iter__(self) -> Iterator[MQTTErrorCode | int]: + self._iterpos = 0 + return self + + def __next__(self) -> MQTTErrorCode | int: + return self.next() + + def next(self) -> MQTTErrorCode | int: + if self._iterpos == 0: + self._iterpos = 1 + return self.rc + elif self._iterpos == 1: + self._iterpos = 2 + return self.mid + else: + raise StopIteration + + def __getitem__(self, index: int) -> MQTTErrorCode | int: + if index == 0: + return self.rc + elif index == 1: + return self.mid + else: + raise IndexError("index out of range") + + def _set_as_published(self) -> None: + with self._condition: + self._published = True + self._condition.notify() + + def wait_for_publish(self, timeout: float | None = None) -> None: + if self.rc == MQTT_ERR_QUEUE_SIZE: + raise ValueError('Message is not queued due to ERR_QUEUE_SIZE') + elif self.rc == MQTT_ERR_AGAIN: + pass + elif self.rc > 0: + raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') + + timeout_time = None if timeout is None else time_func() + timeout + timeout_tenth = None if timeout is None else timeout / 10. + def timed_out() -> bool: + return False if timeout_time is None else time_func() > timeout_time + + with self._condition: + while not self._published and not timed_out(): + self._condition.wait(timeout_tenth) + + if self.rc > 0: + raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') + + def is_published(self) -> bool: + """Returns True if the message associated with this object has been + published, else returns False. + + To wait for this to become true, look at `wait_for_publish`. + """ + if self.rc == MQTTErrorCode.MQTT_ERR_QUEUE_SIZE: + raise ValueError('Message is not queued due to ERR_QUEUE_SIZE') + elif self.rc == MQTTErrorCode.MQTT_ERR_AGAIN: + pass + elif self.rc > 0: + raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') + + with self._condition: + return self._published + + +class MQTTMessage: + __slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info', 'properties' + + def __init__(self, mid: int = 0, topic: bytes = b""): + self.timestamp = 0.0 + self.state = mqtt_ms_invalid + self.dup = False + self.mid = mid + """ The message id (int).""" + self._topic = topic + self.payload = b"" + """the message payload (bytes)""" + self.qos = 0 + """ The message Quality of Service (0, 1 or 2).""" + self.retain = False + """ If true, the message is a retained message and not fresh.""" + self.info = MQTTMessageInfo(mid) + self.properties: Properties | None = None + """ In MQTT v5.0, the properties associated with the message. (`Properties`)""" + + def __eq__(self, other: object) -> bool: + """Override the default Equals behavior""" + if isinstance(other, self.__class__): + return self.mid == other.mid + return False + + def __ne__(self, other: object) -> bool: + """Define a non-equality test""" + return not self.__eq__(other) + + @property + def topic(self) -> str: + """topic that the message was published on. + + This property is read-only. + """ + return self._topic.decode('utf-8') + + @topic.setter + def topic(self, value: bytes) -> None: + self._topic = value + + +class Client: + def __init__( + self, + callback_api_version: CallbackAPIVersion = CallbackAPIVersion.VERSION1, + client_id: str | None = "", + clean_session: bool | None = None, + userdata: Any = None, + protocol: MQTTProtocolVersion = MQTTv311, + transport: Literal["tcp", "websockets", "unix"] = "tcp", + reconnect_on_failure: bool = True, + manual_ack: bool = False, + ) -> None: + transport = transport.lower() # type: ignore + if transport == "unix" and not hasattr(socket, "AF_UNIX"): + raise ValueError('"unix" transport not supported') + elif transport not in ("websockets", "tcp", "unix"): + raise ValueError( + f'transport must be "websockets", "tcp" or "unix", not {transport}') + + self._manual_ack = manual_ack + self._transport = transport + self._protocol = protocol + self._userdata = userdata + self._sock: SocketLike | None = None + self._sockpairR: socket.socket | None = None + self._sockpairW: socket.socket | None = None + self._keepalive = 60 + self._connect_timeout = 5.0 + self._client_mode = MQTT_CLIENT + self._callback_api_version = callback_api_version + + if self._callback_api_version == CallbackAPIVersion.VERSION1: + warnings.warn( + "Callback API version 1 is deprecated, update to latest version", + category=DeprecationWarning, + stacklevel=2, + ) + if isinstance(self._callback_api_version, str): + # Help user to migrate, it probably provided a client id + # as first arguments + raise ValueError( + "Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details" + ) + if self._callback_api_version not in CallbackAPIVersion: + raise ValueError("Unsupported callback API version") + + self._clean_start: int = MQTT_CLEAN_START_FIRST_ONLY + + if protocol == MQTTv5: + if clean_session is not None: + raise ValueError('Clean session is not used for MQTT 5.0') + else: + if clean_session is None: + clean_session = True + if not clean_session and (client_id == "" or client_id is None): + raise ValueError( + 'A client id must be provided if clean session is False.') + self._clean_session = clean_session + + # [MQTT-3.1.3-4] Client Id must be UTF-8 encoded string. + if client_id == "" or client_id is None: + if protocol == MQTTv31: + self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8") + else: + self._client_id = b"" + else: + self._client_id = _force_bytes(client_id) + + self._username: bytes | None = None + self._password: bytes | None = None + self._in_packet: _InPacket = { + "command": 0, + "have_remaining": 0, + "remaining_count": [], + "remaining_mult": 1, + "remaining_length": 0, + "packet": bytearray(b""), + "to_process": 0, + "pos": 0, + } + self._out_packet: collections.deque[_OutPacket] = collections.deque() + self._last_msg_in = time_func() + self._last_msg_out = time_func() + self._reconnect_min_delay = 1 + self._reconnect_max_delay = 120 + self._reconnect_delay: int | None = None + self._reconnect_on_failure = reconnect_on_failure + self._ping_t = 0.0 + self._last_mid = 0 + self._state = _ConnectionState.MQTT_CS_NEW + self._out_messages: collections.OrderedDict[ + int, MQTTMessage + ] = collections.OrderedDict() + self._in_messages: collections.OrderedDict[ + int, MQTTMessage + ] = collections.OrderedDict() + self._max_inflight_messages = 20 + self._inflight_messages = 0 + self._max_queued_messages = 0 + self._connect_properties: Properties | None = None + self._will_properties: Properties | None = None + self._will = False + self._will_topic = b"" + self._will_payload = b"" + self._will_qos = 0 + self._will_retain = False + self._on_message_filtered = MQTTMatcher() + self._host = "" + self._port = 1883 + self._bind_address = "" + self._bind_port = 0 + self._proxy: Any = {} + self._in_callback_mutex = threading.Lock() + self._callback_mutex = threading.RLock() + self._msgtime_mutex = threading.Lock() + self._out_message_mutex = threading.RLock() + self._in_message_mutex = threading.Lock() + self._reconnect_delay_mutex = threading.Lock() + self._mid_generate_mutex = threading.Lock() + self._thread: threading.Thread | None = None + self._thread_terminate = False + self._ssl = False + self._ssl_context: ssl.SSLContext | None = None + # Only used when SSL context does not have check_hostname attribute + self._tls_insecure = False + self._logger: logging.Logger | None = None + self._registered_write = False + # No default callbacks + self._on_log: CallbackOnLog | None = None + self._on_pre_connect: CallbackOnPreConnect | None = None + self._on_connect: CallbackOnConnect | None = None + self._on_connect_fail: CallbackOnConnectFail | None = None + self._on_subscribe: CallbackOnSubscribe | None = None + self._on_message: CallbackOnMessage | None = None + self._on_publish: CallbackOnPublish | None = None + self._on_unsubscribe: CallbackOnUnsubscribe | None = None + self._on_disconnect: CallbackOnDisconnect | None = None + self._on_socket_open: CallbackOnSocket | None = None + self._on_socket_close: CallbackOnSocket | None = None + self._on_socket_register_write: CallbackOnSocket | None = None + self._on_socket_unregister_write: CallbackOnSocket | None = None + self._websocket_path = "/mqtt" + self._websocket_extra_headers: WebSocketHeaders | None = None + # for clean_start == MQTT_CLEAN_START_FIRST_ONLY + self._mqttv5_first_connect = True + self.suppress_exceptions = False # For callbacks + + def __del__(self) -> None: + self._reset_sockets() + + @property + def host(self) -> str: + """ + Host to connect to. If `connect()` hasn't been called yet, returns an empty string. + + This property may not be changed if the connection is already open. + """ + return self._host + + @host.setter + def host(self, value: str) -> None: + if not self._connection_closed(): + raise RuntimeError("updating host on established connection is not supported") + + if not value: + raise ValueError("Invalid host.") + self._host = value + + @property + def port(self) -> int: + """ + Broker TCP port to connect to. + + This property may not be changed if the connection is already open. + """ + return self._port + + @port.setter + def port(self, value: int) -> None: + if not self._connection_closed(): + raise RuntimeError("updating port on established connection is not supported") + + if value <= 0: + raise ValueError("Invalid port number.") + self._port = value + + @property + def keepalive(self) -> int: + """ + Client keepalive interval (in seconds). + + This property may not be changed if the connection is already open. + """ + return self._keepalive + + @keepalive.setter + def keepalive(self, value: int) -> None: + if not self._connection_closed(): + # The issue here is that the previous value of keepalive matter to possibly + # sent ping packet. + raise RuntimeError("updating keepalive on established connection is not supported") + + if value < 0: + raise ValueError("Keepalive must be >=0.") + + self._keepalive = value + + @property + def transport(self) -> Literal["tcp", "websockets", "unix"]: + """ + Transport method used for the connection ("tcp" or "websockets"). + + This property may not be changed if the connection is already open. + """ + return self._transport + + @transport.setter + def transport(self, value: Literal["tcp", "websockets"]) -> None: + if not self._connection_closed(): + raise RuntimeError("updating transport on established connection is not supported") + + self._transport = value + + @property + def protocol(self) -> MQTTProtocolVersion: + """ + Protocol version used (MQTT v3, MQTT v3.11, MQTTv5) + + This property is read-only. + """ + return self._protocol + + @property + def connect_timeout(self) -> float: + """ + Connection establishment timeout in seconds. + + This property may not be changed if the connection is already open. + """ + return self._connect_timeout + + @connect_timeout.setter + def connect_timeout(self, value: float) -> None: + if not self._connection_closed(): + raise RuntimeError("updating connect_timeout on established connection is not supported") + + if value <= 0.0: + raise ValueError("timeout must be a positive number") + + self._connect_timeout = value + + @property + def username(self) -> str | None: + """The username used to connect to the MQTT broker, or None if no username is used. + + This property may not be changed if the connection is already open. + """ + if self._username is None: + return None + return self._username.decode("utf-8") + + @username.setter + def username(self, value: str | None) -> None: + if not self._connection_closed(): + raise RuntimeError("updating username on established connection is not supported") + + if value is None: + self._username = None + else: + self._username = value.encode("utf-8") + + @property + def password(self) -> str | None: + """The password used to connect to the MQTT broker, or None if no password is used. + + This property may not be changed if the connection is already open. + """ + if self._password is None: + return None + return self._password.decode("utf-8") + + @password.setter + def password(self, value: str | None) -> None: + if not self._connection_closed(): + raise RuntimeError("updating password on established connection is not supported") + + if value is None: + self._password = None + else: + self._password = value.encode("utf-8") + + @property + def max_inflight_messages(self) -> int: + """ + Maximum number of messages with QoS > 0 that can be partway through the network flow at once + + This property may not be changed if the connection is already open. + """ + return self._max_inflight_messages + + @max_inflight_messages.setter + def max_inflight_messages(self, value: int) -> None: + if not self._connection_closed(): + # Not tested. Some doubt that everything is okay when max_inflight change between 0 + # and > 0 value because _update_inflight is skipped when _max_inflight_messages == 0 + raise RuntimeError("updating max_inflight_messages on established connection is not supported") + + if value < 0: + raise ValueError("Invalid inflight.") + + self._max_inflight_messages = value + + @property + def max_queued_messages(self) -> int: + """ + Maximum number of message in the outgoing message queue, 0 means unlimited + + This property may not be changed if the connection is already open. + """ + return self._max_queued_messages + + @max_queued_messages.setter + def max_queued_messages(self, value: int) -> None: + if not self._connection_closed(): + # Not tested. + raise RuntimeError("updating max_queued_messages on established connection is not supported") + + if value < 0: + raise ValueError("Invalid queue size.") + + self._max_queued_messages = value + + @property + def will_topic(self) -> str | None: + """ + The topic name a will message is sent to when disconnecting unexpectedly. None if a will shall not be sent. + + This property is read-only. Use `will_set()` to change its value. + """ + if self._will_topic is None: + return None + + return self._will_topic.decode("utf-8") + + @property + def will_payload(self) -> bytes | None: + """ + The payload for the will message that is sent when disconnecting unexpectedly. None if a will shall not be sent. + + This property is read-only. Use `will_set()` to change its value. + """ + return self._will_payload + + @property + def logger(self) -> logging.Logger | None: + return self._logger + + @logger.setter + def logger(self, value: logging.Logger | None) -> None: + self._logger = value + + def _sock_recv(self, bufsize: int) -> bytes: + if self._sock is None: + raise ConnectionError("self._sock is None") + try: + return self._sock.recv(bufsize) + except ssl.SSLWantReadError as err: + raise BlockingIOError() from err + except ssl.SSLWantWriteError as err: + self._call_socket_register_write() + raise BlockingIOError() from err + except AttributeError as err: + self._easy_log( + MQTT_LOG_DEBUG, "socket was None: %s", err) + raise ConnectionError() from err + + def _sock_send(self, buf: bytes) -> int: + if self._sock is None: + raise ConnectionError("self._sock is None") + + try: + return self._sock.send(buf) + except ssl.SSLWantReadError as err: + raise BlockingIOError() from err + except ssl.SSLWantWriteError as err: + self._call_socket_register_write() + raise BlockingIOError() from err + except BlockingIOError as err: + self._call_socket_register_write() + raise BlockingIOError() from err + + def _sock_close(self) -> None: + """Close the connection to the server.""" + if not self._sock: + return + + try: + sock = self._sock + self._sock = None + self._call_socket_unregister_write(sock) + self._call_socket_close(sock) + finally: + # In case a callback fails, still close the socket to avoid leaking the file descriptor. + sock.close() + + def _reset_sockets(self, sockpair_only: bool = False) -> None: + if not sockpair_only: + self._sock_close() + + if self._sockpairR: + self._sockpairR.close() + self._sockpairR = None + if self._sockpairW: + self._sockpairW.close() + self._sockpairW = None + + def reinitialise( + self, + client_id: str = "", + clean_session: bool = True, + userdata: Any = None, + ) -> None: + self._reset_sockets() + + self.__init__(client_id, clean_session, userdata) # type: ignore[misc] + + def ws_set_options( + self, + path: str = "/mqtt", + headers: WebSocketHeaders | None = None, + ) -> None: + """ Set the path and headers for a websocket connection + + :param str path: a string starting with / which should be the endpoint of the + mqtt connection on the remote server + + :param headers: can be either a dict or a callable object. If it is a dict then + the extra items in the dict are added to the websocket headers. If it is + a callable, then the default websocket headers are passed into this + function and the result is used as the new headers. + """ + self._websocket_path = path + + if headers is not None: + if isinstance(headers, dict) or callable(headers): + self._websocket_extra_headers = headers + else: + raise ValueError( + "'headers' option to ws_set_options has to be either a dictionary or callable") + + def tls_set_context( + self, + context: ssl.SSLContext | None = None, + ) -> None: + """Configure network encryption and authentication context. Enables SSL/TLS support. + + :param context: an ssl.SSLContext object. By default this is given by + ``ssl.create_default_context()``, if available. + + Must be called before `connect()`, `connect_async()` or `connect_srv()`.""" + if self._ssl_context is not None: + raise ValueError('SSL/TLS has already been configured.') + + if context is None: + context = ssl.create_default_context() + + self._ssl = True + self._ssl_context = context + + # Ensure _tls_insecure is consistent with check_hostname attribute + if hasattr(context, 'check_hostname'): + self._tls_insecure = not context.check_hostname + + def tls_set( + self, + ca_certs: str | None = None, + certfile: str | None = None, + keyfile: str | None = None, + cert_reqs: ssl.VerifyMode | None = None, + tls_version: int | None = None, + ciphers: str | None = None, + keyfile_password: str | None = None, + alpn_protocols: list[str] | None = None, + ) -> None: + """Configure network encryption and authentication options. Enables SSL/TLS support. + + :param str ca_certs: a string path to the Certificate Authority certificate files + that are to be treated as trusted by this client. If this is the only + option given then the client will operate in a similar manner to a web + browser. That is to say it will require the broker to have a + certificate signed by the Certificate Authorities in ca_certs and will + communicate using TLS v1,2, but will not attempt any form of + authentication. This provides basic network encryption but may not be + sufficient depending on how the broker is configured. + + By default, on Python 2.7.9+ or 3.4+, the default certification + authority of the system is used. On older Python version this parameter + is mandatory. + :param str certfile: PEM encoded client certificate filename. Used with + keyfile for client TLS based authentication. Support for this feature is + broker dependent. Note that if the files in encrypted and needs a password to + decrypt it, then this can be passed using the keyfile_password argument - you + should take precautions to ensure that your password is + not hard coded into your program by loading the password from a file + for example. If you do not provide keyfile_password, the password will + be requested to be typed in at a terminal window. + :param str keyfile: PEM encoded client private keys filename. Used with + certfile for client TLS based authentication. Support for this feature is + broker dependent. Note that if the files in encrypted and needs a password to + decrypt it, then this can be passed using the keyfile_password argument - you + should take precautions to ensure that your password is + not hard coded into your program by loading the password from a file + for example. If you do not provide keyfile_password, the password will + be requested to be typed in at a terminal window. + :param cert_reqs: the certificate requirements that the client imposes + on the broker to be changed. By default this is ssl.CERT_REQUIRED, + which means that the broker must provide a certificate. See the ssl + pydoc for more information on this parameter. + :param tls_version: the version of the SSL/TLS protocol used to be + specified. By default TLS v1.2 is used. Previous versions are allowed + but not recommended due to possible security problems. + :param str ciphers: encryption ciphers that are allowed + for this connection, or None to use the defaults. See the ssl pydoc for + more information. + + Must be called before `connect()`, `connect_async()` or `connect_srv()`.""" + if ssl is None: + raise ValueError('This platform has no SSL/TLS.') + + if not hasattr(ssl, 'SSLContext'): + # Require Python version that has SSL context support in standard library + raise ValueError( + 'Python 2.7.9 and 3.2 are the minimum supported versions for TLS.') + + if ca_certs is None and not hasattr(ssl.SSLContext, 'load_default_certs'): + raise ValueError('ca_certs must not be None.') + + # Create SSLContext object + if tls_version is None: + tls_version = ssl.PROTOCOL_TLSv1_2 + # If the python version supports it, use highest TLS version automatically + if hasattr(ssl, "PROTOCOL_TLS_CLIENT"): + # This also enables CERT_REQUIRED and check_hostname by default. + tls_version = ssl.PROTOCOL_TLS_CLIENT + elif hasattr(ssl, "PROTOCOL_TLS"): + tls_version = ssl.PROTOCOL_TLS + context = ssl.SSLContext(tls_version) + + # Configure context + if ciphers is not None: + context.set_ciphers(ciphers) + + if certfile is not None: + context.load_cert_chain(certfile, keyfile, keyfile_password) + + if cert_reqs == ssl.CERT_NONE and hasattr(context, 'check_hostname'): + context.check_hostname = False + + context.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if ca_certs is not None: + context.load_verify_locations(ca_certs) + else: + context.load_default_certs() + + if alpn_protocols is not None: + if not getattr(ssl, "HAS_ALPN", None): + raise ValueError("SSL library has no support for ALPN") + context.set_alpn_protocols(alpn_protocols) + + self.tls_set_context(context) + + if cert_reqs != ssl.CERT_NONE: + # Default to secure, sets context.check_hostname attribute + # if available + self.tls_insecure_set(False) + else: + # But with ssl.CERT_NONE, we can not check_hostname + self.tls_insecure_set(True) + + def tls_insecure_set(self, value: bool) -> None: + """Configure verification of the server hostname in the server certificate. + + If value is set to true, it is impossible to guarantee that the host + you are connecting to is not impersonating your server. This can be + useful in initial server testing, but makes it possible for a malicious + third party to impersonate your server through DNS spoofing, for + example. + + Do not use this function in a real system. Setting value to true means + there is no point using encryption. + + Must be called before `connect()` and after either `tls_set()` or + `tls_set_context()`.""" + + if self._ssl_context is None: + raise ValueError( + 'Must configure SSL context before using tls_insecure_set.') + + self._tls_insecure = value + + # Ensure check_hostname is consistent with _tls_insecure attribute + if hasattr(self._ssl_context, 'check_hostname'): + # Rely on SSLContext to check host name + # If verify_mode is CERT_NONE then the host name will never be checked + self._ssl_context.check_hostname = not value + + def proxy_set(self, **proxy_args: Any) -> None: + """Configure proxying of MQTT connection. Enables support for SOCKS or + HTTP proxies. + + Proxying is done through the PySocks library. Brief descriptions of the + proxy_args parameters are below; see the PySocks docs for more info. + + (Required) + + :param proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5} + :param proxy_addr: IP address or DNS name of proxy server + + (Optional) + + :param proxy_port: (int) port number of the proxy server. If not provided, + the PySocks package default value will be utilized, which differs by proxy_type. + :param proxy_rdns: boolean indicating whether proxy lookup should be performed + remotely (True, default) or locally (False) + :param proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy + :param proxy_password: password for SOCKS5 proxy + + Example:: + + mqttc.proxy_set(proxy_type=socks.HTTP, proxy_addr='1.2.3.4', proxy_port=4231) + """ + if socks is None: + raise ValueError("PySocks must be installed for proxy support.") + elif not self._proxy_is_valid(proxy_args): + raise ValueError("proxy_type and/or proxy_addr are invalid.") + else: + self._proxy = proxy_args + + def enable_logger(self, logger: logging.Logger | None = None) -> None: + """ + Enables a logger to send log messages to + + :param logging.Logger logger: if specified, that ``logging.Logger`` object will be used, otherwise + one will be created automatically. + + See `disable_logger` to undo this action. + """ + if logger is None: + if self._logger is not None: + # Do not replace existing logger + return + logger = logging.getLogger(__name__) + self.logger = logger + + def disable_logger(self) -> None: + """ + Disable logging using standard python logging package. This has no effect on the `on_log` callback. + """ + self._logger = None + + def connect( + self, + host: str, + port: int = 1883, + keepalive: int = 60, + bind_address: str = "", + bind_port: int = 0, + clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, + properties: Properties | None = None, + ) -> MQTTErrorCode: + """Connect to a remote broker. This is a blocking call that establishes + the underlying connection and transmits a CONNECT packet. + Note that the connection status will not be updated until a CONNACK is received and + processed (this requires a running network loop, see `loop_start`, `loop_forever`, `loop`...). + + :param str host: the hostname or IP address of the remote broker. + :param int port: the network port of the server host to connect to. Defaults to + 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you + are using `tls_set()` the port may need providing. + :param int keepalive: Maximum period in seconds between communications with the + broker. If no other messages are being exchanged, this controls the + rate at which the client will send ping messages to the broker. + :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. + Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, + respectively. MQTT session data (such as outstanding messages and subscriptions) + is cleared on successful connect when the clean_start flag is set. + For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar + result. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the + MQTT connect packet. + """ + + if self._protocol == MQTTv5: + self._mqttv5_first_connect = True + else: + if clean_start != MQTT_CLEAN_START_FIRST_ONLY: + raise ValueError("Clean start only applies to MQTT V5") + if properties: + raise ValueError("Properties only apply to MQTT V5") + + self.connect_async(host, port, keepalive, + bind_address, bind_port, clean_start, properties) + return self.reconnect() + + def connect_srv( + self, + domain: str | None = None, + keepalive: int = 60, + bind_address: str = "", + bind_port: int = 0, + clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, + properties: Properties | None = None, + ) -> MQTTErrorCode: + """Connect to a remote broker. + + :param str domain: the DNS domain to search for SRV records; if None, + try to determine local domain name. + :param keepalive, bind_address, clean_start and properties: see `connect()` + """ + + if HAVE_DNS is False: + raise ValueError( + 'No DNS resolver library found, try "pip install dnspython".') + + if domain is None: + domain = socket.getfqdn() + domain = domain[domain.find('.') + 1:] + + try: + rr = f'_mqtt._tcp.{domain}' + if self._ssl: + # IANA specifies secure-mqtt (not mqtts) for port 8883 + rr = f'_secure-mqtt._tcp.{domain}' + answers = [] + for answer in dns.resolver.query(rr, dns.rdatatype.SRV): + addr = answer.target.to_text()[:-1] + answers.append( + (addr, answer.port, answer.priority, answer.weight)) + except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers) as err: + raise ValueError(f"No answer/NXDOMAIN for SRV in {domain}") from err + + # FIXME: doesn't account for weight + for answer in answers: + host, port, prio, weight = answer + + try: + return self.connect(host, port, keepalive, bind_address, bind_port, clean_start, properties) + except Exception: # noqa: S110 + pass + + raise ValueError("No SRV hosts responded") + + def connect_async( + self, + host: str, + port: int = 1883, + keepalive: int = 60, + bind_address: str = "", + bind_port: int = 0, + clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, + properties: Properties | None = None, + ) -> None: + """Connect to a remote broker asynchronously. This is a non-blocking + connect call that can be used with `loop_start()` to provide very quick + start. + + Any already established connection will be terminated immediately. + + :param str host: the hostname or IP address of the remote broker. + :param int port: the network port of the server host to connect to. Defaults to + 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you + are using `tls_set()` the port may need providing. + :param int keepalive: Maximum period in seconds between communications with the + broker. If no other messages are being exchanged, this controls the + rate at which the client will send ping messages to the broker. + :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. + Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, + respectively. MQTT session data (such as outstanding messages and subscriptions) + is cleared on successful connect when the clean_start flag is set. + For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar + result. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the + MQTT connect packet. + """ + if bind_port < 0: + raise ValueError('Invalid bind port number.') + + # Switch to state NEW to allow update of host, port & co. + self._sock_close() + self._state = _ConnectionState.MQTT_CS_NEW + + self.host = host + self.port = port + self.keepalive = keepalive + self._bind_address = bind_address + self._bind_port = bind_port + self._clean_start = clean_start + self._connect_properties = properties + self._state = _ConnectionState.MQTT_CS_CONNECT_ASYNC + + def reconnect_delay_set(self, min_delay: int = 1, max_delay: int = 120) -> None: + """ Configure the exponential reconnect delay + + When connection is lost, wait initially min_delay seconds and + double this time every attempt. The wait is capped at max_delay. + Once the client is fully connected (e.g. not only TCP socket, but + received a success CONNACK), the wait timer is reset to min_delay. + """ + with self._reconnect_delay_mutex: + self._reconnect_min_delay = min_delay + self._reconnect_max_delay = max_delay + self._reconnect_delay = None + + def reconnect(self) -> MQTTErrorCode: + """Reconnect the client after a disconnect. Can only be called after + connect()/connect_async().""" + if len(self._host) == 0: + raise ValueError('Invalid host.') + if self._port <= 0: + raise ValueError('Invalid port number.') + + self._in_packet = { + "command": 0, + "have_remaining": 0, + "remaining_count": [], + "remaining_mult": 1, + "remaining_length": 0, + "packet": bytearray(b""), + "to_process": 0, + "pos": 0, + } + + self._ping_t = 0.0 + self._state = _ConnectionState.MQTT_CS_CONNECTING + + self._sock_close() + + # Mark all currently outgoing QoS = 0 packets as lost, + # or `wait_for_publish()` could hang forever + for pkt in self._out_packet: + if pkt["command"] & 0xF0 == PUBLISH and pkt["qos"] == 0 and pkt["info"] is not None: + pkt["info"].rc = MQTT_ERR_CONN_LOST + pkt["info"]._set_as_published() + + self._out_packet.clear() + + with self._msgtime_mutex: + self._last_msg_in = time_func() + self._last_msg_out = time_func() + + # Put messages in progress in a valid state. + self._messages_reconnect_reset() + + with self._callback_mutex: + on_pre_connect = self.on_pre_connect + + if on_pre_connect: + try: + on_pre_connect(self, self._userdata) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_pre_connect: %s', err) + if not self.suppress_exceptions: + raise + + self._sock = self._create_socket() + + self._sock.setblocking(False) # type: ignore[attr-defined] + self._registered_write = False + self._call_socket_open(self._sock) + + return self._send_connect(self._keepalive) + + def loop(self, timeout: float = 1.0) -> MQTTErrorCode: + """Process network events. + + It is strongly recommended that you use `loop_start()`, or + `loop_forever()`, or if you are using an external event loop using + `loop_read()`, `loop_write()`, and `loop_misc()`. Using loop() on it's own is + no longer recommended. + + This function must be called regularly to ensure communication with the + broker is carried out. It calls select() on the network socket to wait + for network events. If incoming data is present it will then be + processed. Outgoing commands, from e.g. `publish()`, are normally sent + immediately that their function is called, but this is not always + possible. loop() will also attempt to send any remaining outgoing + messages, which also includes commands that are part of the flow for + messages with QoS>0. + + :param int timeout: The time in seconds to wait for incoming/outgoing network + traffic before timing out and returning. + + Returns MQTT_ERR_SUCCESS on success. + Returns >0 on error. + + A ValueError will be raised if timeout < 0""" + + if self._sockpairR is None or self._sockpairW is None: + self._reset_sockets(sockpair_only=True) + self._sockpairR, self._sockpairW = _socketpair_compat() + + return self._loop(timeout) + + def _loop(self, timeout: float = 1.0) -> MQTTErrorCode: + if timeout < 0.0: + raise ValueError('Invalid timeout.') + + if self.want_write(): + wlist = [self._sock] + else: + wlist = [] + + # used to check if there are any bytes left in the (SSL) socket + pending_bytes = 0 + if hasattr(self._sock, 'pending'): + pending_bytes = self._sock.pending() # type: ignore[union-attr] + + # if bytes are pending do not wait in select + if pending_bytes > 0: + timeout = 0.0 + + # sockpairR is used to break out of select() before the timeout, on a + # call to publish() etc. + if self._sockpairR is None: + rlist = [self._sock] + else: + rlist = [self._sock, self._sockpairR] + + try: + socklist = select.select(rlist, wlist, [], timeout) + except TypeError: + # Socket isn't correct type, in likelihood connection is lost + # ... or we called disconnect(). In that case the socket will + # be closed but some loop (like loop_forever) will continue to + # call _loop(). We still want to break that loop by returning an + # rc != MQTT_ERR_SUCCESS and we don't want state to change from + # mqtt_cs_disconnecting. + if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + return MQTTErrorCode.MQTT_ERR_CONN_LOST + except ValueError: + # Can occur if we just reconnected but rlist/wlist contain a -1 for + # some reason. + if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + return MQTTErrorCode.MQTT_ERR_CONN_LOST + except Exception: + # Note that KeyboardInterrupt, etc. can still terminate since they + # are not derived from Exception + return MQTTErrorCode.MQTT_ERR_UNKNOWN + + if self._sock in socklist[0] or pending_bytes > 0: + rc = self.loop_read() + if rc or self._sock is None: + return rc + + if self._sockpairR and self._sockpairR in socklist[0]: + # Stimulate output write even though we didn't ask for it, because + # at that point the publish or other command wasn't present. + socklist[1].insert(0, self._sock) + # Clear sockpairR - only ever a single byte written. + try: + # Read many bytes at once - this allows up to 10000 calls to + # publish() inbetween calls to loop(). + self._sockpairR.recv(10000) + except BlockingIOError: + pass + + if self._sock in socklist[1]: + rc = self.loop_write() + if rc or self._sock is None: + return rc + + return self.loop_misc() + + def publish( + self, + topic: str, + payload: PayloadType = None, + qos: int = 0, + retain: bool = False, + properties: Properties | None = None, + ) -> MQTTMessageInfo: + """Publish a message on a topic. + + This causes a message to be sent to the broker and subsequently from + the broker to any clients subscribing to matching topics. + + :param str topic: The topic that the message should be published on. + :param payload: The actual message to send. If not given, or set to None a + zero length message will be used. Passing an int or float will result + in the payload being converted to a string representing that number. If + you wish to send a true int/float, use struct.pack() to create the + payload you require. + :param int qos: The quality of service level to use. + :param bool retain: If set to true, the message will be set as the "last known + good"/retained message for the topic. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included. + + Returns a `MQTTMessageInfo` class, which can be used to determine whether + the message has been delivered (using `is_published()`) or to block + waiting for the message to be delivered (`wait_for_publish()`). The + message ID and return code of the publish() call can be found at + :py:attr:`info.mid ` and :py:attr:`info.rc `. + + For backwards compatibility, the `MQTTMessageInfo` class is iterable so + the old construct of ``(rc, mid) = client.publish(...)`` is still valid. + + rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the + client is not currently connected. mid is the message ID for the + publish request. The mid value can be used to track the publish request + by checking against the mid argument in the on_publish() callback if it + is defined. + + :raises ValueError: if topic is None, has zero length or is + invalid (contains a wildcard), except if the MQTT version used is v5.0. + For v5.0, a zero length topic can be used when a Topic Alias has been set. + :raises ValueError: if qos is not one of 0, 1 or 2 + :raises ValueError: if the length of the payload is greater than 268435455 bytes. + """ + if self._protocol != MQTTv5: + if topic is None or len(topic) == 0: + raise ValueError('Invalid topic.') + + topic_bytes = topic.encode('utf-8') + + self._raise_for_invalid_topic(topic_bytes) + + if qos < 0 or qos > 2: + raise ValueError('Invalid QoS level.') + + local_payload = _encode_payload(payload) + + if len(local_payload) > 268435455: + raise ValueError('Payload too large.') + + local_mid = self._mid_generate() + + if qos == 0: + info = MQTTMessageInfo(local_mid) + rc = self._send_publish( + local_mid, topic_bytes, local_payload, qos, retain, False, info, properties) + info.rc = rc + return info + else: + message = MQTTMessage(local_mid, topic_bytes) + message.timestamp = time_func() + message.payload = local_payload + message.qos = qos + message.retain = retain + message.dup = False + message.properties = properties + + with self._out_message_mutex: + if self._max_queued_messages > 0 and len(self._out_messages) >= self._max_queued_messages: + message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE + return message.info + + if local_mid in self._out_messages: + message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE + return message.info + + self._out_messages[message.mid] = message + if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages: + self._inflight_messages += 1 + if qos == 1: + message.state = mqtt_ms_wait_for_puback + elif qos == 2: + message.state = mqtt_ms_wait_for_pubrec + + rc = self._send_publish(message.mid, topic_bytes, message.payload, message.qos, message.retain, + message.dup, message.info, message.properties) + + # remove from inflight messages so it will be send after a connection is made + if rc == MQTTErrorCode.MQTT_ERR_NO_CONN: + self._inflight_messages -= 1 + message.state = mqtt_ms_publish + + message.info.rc = rc + return message.info + else: + message.state = mqtt_ms_queued + message.info.rc = MQTTErrorCode.MQTT_ERR_SUCCESS + return message.info + + def username_pw_set( + self, username: str | None, password: str | None = None + ) -> None: + """Set a username and optionally a password for broker authentication. + + Must be called before connect() to have any effect. + Requires a broker that supports MQTT v3.1 or more. + + :param str username: The username to authenticate with. Need have no relationship to the client id. Must be str + [MQTT-3.1.3-11]. + Set to None to reset client back to not using username/password for broker authentication. + :param str password: The password to authenticate with. Optional, set to None if not required. If it is str, then it + will be encoded as UTF-8. + """ + + # [MQTT-3.1.3-11] User name must be UTF-8 encoded string + self._username = None if username is None else username.encode('utf-8') + if isinstance(password, str): + self._password = password.encode('utf-8') + else: + self._password = password + + def enable_bridge_mode(self) -> None: + """Sets the client in a bridge mode instead of client mode. + + Must be called before `connect()` to have any effect. + Requires brokers that support bridge mode. + + Under bridge mode, the broker will identify the client as a bridge and + not send it's own messages back to it. Hence a subsciption of # is + possible without message loops. This feature also correctly propagates + the retain flag on the messages. + + Currently Mosquitto and RSMB support this feature. This feature can + be used to create a bridge between multiple broker. + """ + self._client_mode = MQTT_BRIDGE + + def _connection_closed(self) -> bool: + """ + Return true if the connection is closed (and not trying to be opened). + """ + return ( + self._state == _ConnectionState.MQTT_CS_NEW + or (self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) and self._sock is None)) + + def is_connected(self) -> bool: + """Returns the current status of the connection + + True if connection exists + False if connection is closed + """ + return self._state == _ConnectionState.MQTT_CS_CONNECTED + + def disconnect( + self, + reasoncode: ReasonCode | None = None, + properties: Properties | None = None, + ) -> MQTTErrorCode: + """Disconnect a connected client from the broker. + + :param ReasonCode reasoncode: (MQTT v5.0 only) a ReasonCode instance setting the MQTT v5.0 + reasoncode to be sent with the disconnect packet. It is optional, the receiver + then assuming that 0 (success) is the value. + :param Properties properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + """ + if self._sock is None: + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + return MQTT_ERR_NO_CONN + else: + self._state = _ConnectionState.MQTT_CS_DISCONNECTING + + return self._send_disconnect(reasoncode, properties) + + def subscribe( + self, + topic: str | tuple[str, int] | tuple[str, SubscribeOptions] | list[tuple[str, int]] | list[tuple[str, SubscribeOptions]], + qos: int = 0, + options: SubscribeOptions | None = None, + properties: Properties | None = None, + ) -> tuple[MQTTErrorCode, int | None]: + """Subscribe the client to one or more topics. + + This function may be called in three different ways (and a further three for MQTT v5.0): + + Simple string and integer + ------------------------- + e.g. subscribe("my/topic", 2) + + :topic: A string specifying the subscription topic to subscribe to. + :qos: The desired quality of service level for the subscription. + Defaults to 0. + :options and properties: Not used. + + Simple string and subscribe options (MQTT v5.0 only) + ---------------------------------------------------- + e.g. subscribe("my/topic", options=SubscribeOptions(qos=2)) + + :topic: A string specifying the subscription topic to subscribe to. + :qos: Not used. + :options: The MQTT v5.0 subscribe options. + :properties: a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + String and integer tuple + ------------------------ + e.g. subscribe(("my/topic", 1)) + + :topic: A tuple of (topic, qos). Both topic and qos must be present in + the tuple. + :qos and options: Not used. + :properties: Only used for MQTT v5.0. A Properties instance setting the + MQTT v5.0 properties. Optional - if not set, no properties are sent. + + String and subscribe options tuple (MQTT v5.0 only) + --------------------------------------------------- + e.g. subscribe(("my/topic", SubscribeOptions(qos=1))) + + :topic: A tuple of (topic, SubscribeOptions). Both topic and subscribe + options must be present in the tuple. + :qos and options: Not used. + :properties: a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + List of string and integer tuples + --------------------------------- + e.g. subscribe([("my/topic", 0), ("another/topic", 2)]) + + This allows multiple topic subscriptions in a single SUBSCRIPTION + command, which is more efficient than using multiple calls to + subscribe(). + + :topic: A list of tuple of format (topic, qos). Both topic and qos must + be present in all of the tuples. + :qos, options and properties: Not used. + + List of string and subscribe option tuples (MQTT v5.0 only) + ----------------------------------------------------------- + e.g. subscribe([("my/topic", SubscribeOptions(qos=0), ("another/topic", SubscribeOptions(qos=2)]) + + This allows multiple topic subscriptions in a single SUBSCRIPTION + command, which is more efficient than using multiple calls to + subscribe(). + + :topic: A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe + options must be present in all of the tuples. + :qos and options: Not used. + :properties: a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + The function returns a tuple (result, mid), where result is + MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the + client is not currently connected. mid is the message ID for the + subscribe request. The mid value can be used to track the subscribe + request by checking against the mid argument in the on_subscribe() + callback if it is defined. + + Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has + zero string length, or if topic is not a string, tuple or list. + """ + topic_qos_list = None + + if isinstance(topic, tuple): + if self._protocol == MQTTv5: + topic, options = topic # type: ignore + if not isinstance(options, SubscribeOptions): + raise ValueError( + 'Subscribe options must be instance of SubscribeOptions class.') + else: + topic, qos = topic # type: ignore + + if isinstance(topic, (bytes, str)): + if qos < 0 or qos > 2: + raise ValueError('Invalid QoS level.') + if self._protocol == MQTTv5: + if options is None: + # if no options are provided, use the QoS passed instead + options = SubscribeOptions(qos=qos) + elif qos != 0: + raise ValueError( + 'Subscribe options and qos parameters cannot be combined.') + if not isinstance(options, SubscribeOptions): + raise ValueError( + 'Subscribe options must be instance of SubscribeOptions class.') + topic_qos_list = [(topic.encode('utf-8'), options)] + else: + if topic is None or len(topic) == 0: + raise ValueError('Invalid topic.') + topic_qos_list = [(topic.encode('utf-8'), qos)] # type: ignore + elif isinstance(topic, list): + if len(topic) == 0: + raise ValueError('Empty topic list') + topic_qos_list = [] + if self._protocol == MQTTv5: + for t, o in topic: + if not isinstance(o, SubscribeOptions): + # then the second value should be QoS + if o < 0 or o > 2: + raise ValueError('Invalid QoS level.') + o = SubscribeOptions(qos=o) + topic_qos_list.append((t.encode('utf-8'), o)) + else: + for t, q in topic: + if isinstance(q, SubscribeOptions) or q < 0 or q > 2: + raise ValueError('Invalid QoS level.') + if t is None or len(t) == 0 or not isinstance(t, (bytes, str)): + raise ValueError('Invalid topic.') + topic_qos_list.append((t.encode('utf-8'), q)) # type: ignore + + if topic_qos_list is None: + raise ValueError("No topic specified, or incorrect topic type.") + + if any(self._filter_wildcard_len_check(topic) != MQTT_ERR_SUCCESS for topic, _ in topic_qos_list): + raise ValueError('Invalid subscription filter.') + + if self._sock is None: + return (MQTT_ERR_NO_CONN, None) + + return self._send_subscribe(False, topic_qos_list, properties) + + def unsubscribe( + self, topic: str | list[str], properties: Properties | None = None + ) -> tuple[MQTTErrorCode, int | None]: + """Unsubscribe the client from one or more topics. + + :param topic: A single string, or list of strings that are the subscription + topics to unsubscribe from. + :param properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties + to be included. Optional - if not set, no properties are sent. + + Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS + to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not + currently connected. + mid is the message ID for the unsubscribe request. The mid value can be + used to track the unsubscribe request by checking against the mid + argument in the on_unsubscribe() callback if it is defined. + + :raises ValueError: if topic is None or has zero string length, or is + not a string or list. + """ + topic_list = None + if topic is None: + raise ValueError('Invalid topic.') + if isinstance(topic, (bytes, str)): + if len(topic) == 0: + raise ValueError('Invalid topic.') + topic_list = [topic.encode('utf-8')] + elif isinstance(topic, list): + topic_list = [] + for t in topic: + if len(t) == 0 or not isinstance(t, (bytes, str)): + raise ValueError('Invalid topic.') + topic_list.append(t.encode('utf-8')) + + if topic_list is None: + raise ValueError("No topic specified, or incorrect topic type.") + + if self._sock is None: + return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) + + return self._send_unsubscribe(False, topic_list, properties) + + def loop_read(self, max_packets: int = 1) -> MQTTErrorCode: + """Process read network events. Use in place of calling `loop()` if you + wish to handle your client reads as part of your own application. + + Use `socket()` to obtain the client socket to call select() or equivalent + on. + + Do not use if you are using `loop_start()` or `loop_forever()`.""" + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + max_packets = len(self._out_messages) + len(self._in_messages) + if max_packets < 1: + max_packets = 1 + + for _ in range(0, max_packets): + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + rc = self._packet_read() + if rc > 0: + return self._loop_rc_handle(rc) + elif rc == MQTTErrorCode.MQTT_ERR_AGAIN: + return MQTTErrorCode.MQTT_ERR_SUCCESS + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def loop_write(self) -> MQTTErrorCode: + """Process write network events. Use in place of calling `loop()` if you + wish to handle your client writes as part of your own application. + + Use `socket()` to obtain the client socket to call select() or equivalent + on. + + Use `want_write()` to determine if there is data waiting to be written. + + Do not use if you are using `loop_start()` or `loop_forever()`.""" + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + try: + rc = self._packet_write() + if rc == MQTTErrorCode.MQTT_ERR_AGAIN: + return MQTTErrorCode.MQTT_ERR_SUCCESS + elif rc > 0: + return self._loop_rc_handle(rc) + else: + return MQTTErrorCode.MQTT_ERR_SUCCESS + finally: + if self.want_write(): + self._call_socket_register_write() + else: + self._call_socket_unregister_write() + + def want_write(self) -> bool: + """Call to determine if there is network data waiting to be written. + Useful if you are calling select() yourself rather than using `loop()`, `loop_start()` or `loop_forever()`. + """ + return len(self._out_packet) > 0 + + def loop_misc(self) -> MQTTErrorCode: + """Process miscellaneous network events. Use in place of calling `loop()` if you + wish to call select() or equivalent on. + + Do not use if you are using `loop_start()` or `loop_forever()`.""" + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + now = time_func() + self._check_keepalive() + + if self._ping_t > 0 and now - self._ping_t >= self._keepalive: + # client->ping_t != 0 means we are waiting for a pingresp. + # This hasn't happened in the keepalive time so we should disconnect. + self._sock_close() + + if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + else: + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE + + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=rc, + ) + + return MQTTErrorCode.MQTT_ERR_CONN_LOST + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def max_inflight_messages_set(self, inflight: int) -> None: + """Set the maximum number of messages with QoS>0 that can be part way + through their network flow at once. Defaults to 20.""" + self.max_inflight_messages = inflight + + def max_queued_messages_set(self, queue_size: int) -> Client: + """Set the maximum number of messages in the outgoing message queue. + 0 means unlimited.""" + if not isinstance(queue_size, int): + raise ValueError('Invalid type of queue size.') + self.max_queued_messages = queue_size + return self + + def user_data_set(self, userdata: Any) -> None: + """Set the user data variable passed to callbacks. May be any data type.""" + self._userdata = userdata + + def user_data_get(self) -> Any: + """Get the user data variable passed to callbacks. May be any data type.""" + return self._userdata + + def will_set( + self, + topic: str, + payload: PayloadType = None, + qos: int = 0, + retain: bool = False, + properties: Properties | None = None, + ) -> None: + """Set a Will to be sent by the broker in case the client disconnects unexpectedly. + + This must be called before connect() to have any effect. + + :param str topic: The topic that the will message should be published on. + :param payload: The message to send as a will. If not given, or set to None a + zero length message will be used as the will. Passing an int or float + will result in the payload being converted to a string representing + that number. If you wish to send a true int/float, use struct.pack() to + create the payload you require. + :param int qos: The quality of service level to use for the will. + :param bool retain: If set to true, the will message will be set as the "last known + good"/retained message for the topic. + :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties + to be included with the will message. Optional - if not set, no properties are sent. + + :raises ValueError: if qos is not 0, 1 or 2, or if topic is None or has + zero string length. + + See `will_clear` to clear will. Note that will are NOT send if the client disconnect cleanly + for example by calling `disconnect()`. + """ + if topic is None or len(topic) == 0: + raise ValueError('Invalid topic.') + + if qos < 0 or qos > 2: + raise ValueError('Invalid QoS level.') + + if properties and not isinstance(properties, Properties): + raise ValueError( + "The properties argument must be an instance of the Properties class.") + + self._will_payload = _encode_payload(payload) + self._will = True + self._will_topic = topic.encode('utf-8') + self._will_qos = qos + self._will_retain = retain + self._will_properties = properties + + def will_clear(self) -> None: + """ Removes a will that was previously configured with `will_set()`. + + Must be called before connect() to have any effect.""" + self._will = False + self._will_topic = b"" + self._will_payload = b"" + self._will_qos = 0 + self._will_retain = False + + def socket(self) -> SocketLike | None: + """Return the socket or ssl object for this client.""" + return self._sock + + def loop_forever( + self, + timeout: float = 1.0, + retry_first_connection: bool = False, + ) -> MQTTErrorCode: + """This function calls the network loop functions for you in an + infinite blocking loop. It is useful for the case where you only want + to run the MQTT client loop in your program. + + loop_forever() will handle reconnecting for you if reconnect_on_failure is + true (this is the default behavior). If you call `disconnect()` in a callback + it will return. + + :param int timeout: The time in seconds to wait for incoming/outgoing network + traffic before timing out and returning. + :param bool retry_first_connection: Should the first connection attempt be retried on failure. + This is independent of the reconnect_on_failure setting. + + :raises OSError: if the first connection fail unless retry_first_connection=True + """ + + run = True + + while run: + if self._thread_terminate is True: + break + + if self._state == _ConnectionState.MQTT_CS_CONNECT_ASYNC: + try: + self.reconnect() + except OSError: + self._handle_on_connect_fail() + if not retry_first_connection: + raise + self._easy_log( + MQTT_LOG_DEBUG, "Connection failed, retrying") + self._reconnect_wait() + else: + break + + while run: + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + while rc == MQTTErrorCode.MQTT_ERR_SUCCESS: + rc = self._loop(timeout) + # We don't need to worry about locking here, because we've + # either called loop_forever() when in single threaded mode, or + # in multi threaded mode when loop_stop() has been called and + # so no other threads can access _out_packet or _messages. + if (self._thread_terminate is True + and len(self._out_packet) == 0 + and len(self._out_messages) == 0): + rc = MQTTErrorCode.MQTT_ERR_NOMEM + run = False + + def should_exit() -> bool: + return ( + self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) or + run is False or # noqa: B023 (uses the run variable from the outer scope on purpose) + self._thread_terminate is True + ) + + if should_exit() or not self._reconnect_on_failure: + run = False + else: + self._reconnect_wait() + + if should_exit(): + run = False + else: + try: + self.reconnect() + except OSError: + self._handle_on_connect_fail() + self._easy_log( + MQTT_LOG_DEBUG, "Connection failed, retrying") + + return rc + + def loop_start(self) -> MQTTErrorCode: + """This is part of the threaded client interface. Call this once to + start a new thread to process network traffic. This provides an + alternative to repeatedly calling `loop()` yourself. + + Under the hood, this will call `loop_forever` in a thread, which means that + the thread will terminate if you call `disconnect()` + """ + if self._thread is not None: + return MQTTErrorCode.MQTT_ERR_INVAL + + self._sockpairR, self._sockpairW = _socketpair_compat() + self._thread_terminate = False + self._thread = threading.Thread(target=self._thread_main, name=f"paho-mqtt-client-{self._client_id.decode()}") + self._thread.daemon = True + self._thread.start() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def loop_stop(self) -> MQTTErrorCode: + """This is part of the threaded client interface. Call this once to + stop the network thread previously created with `loop_start()`. This call + will block until the network thread finishes. + + This don't guarantee that publish packet are sent, use `wait_for_publish` or + `on_publish` to ensure `publish` are sent. + """ + if self._thread is None: + return MQTTErrorCode.MQTT_ERR_INVAL + + self._thread_terminate = True + if threading.current_thread() != self._thread: + self._thread.join() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + @property + def callback_api_version(self) -> CallbackAPIVersion: + """ + Return the callback API version used for user-callback. See docstring for + each user-callback (`on_connect`, `on_publish`, ...) for details. + + This property is read-only. + """ + return self._callback_api_version + + @property + def on_log(self) -> CallbackOnLog | None: + """The callback called when the client has log information. + Defined to allow debugging. + + Expected signature is:: + + log_callback(client, userdata, level, buf) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param int level: gives the severity of the message and will be one of + MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, + MQTT_LOG_ERR, and MQTT_LOG_DEBUG. + :param str buf: the message itself + + Decorator: @client.log_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_log + + @on_log.setter + def on_log(self, func: CallbackOnLog | None) -> None: + self._on_log = func + + def log_callback(self) -> Callable[[CallbackOnLog], CallbackOnLog]: + def decorator(func: CallbackOnLog) -> CallbackOnLog: + self.on_log = func + return func + return decorator + + @property + def on_pre_connect(self) -> CallbackOnPreConnect | None: + """The callback called immediately prior to the connection is made + request. + + Expected signature (for all callback API version):: + + connect_callback(client, userdata) + + :parama Client client: the client instance for this callback + :parama userdata: the private user data as set in Client() or user_data_set() + + Decorator: @client.pre_connect_callback() (``client`` is the name of the + instance which this callback is being attached to) + + """ + return self._on_pre_connect + + @on_pre_connect.setter + def on_pre_connect(self, func: CallbackOnPreConnect | None) -> None: + with self._callback_mutex: + self._on_pre_connect = func + + def pre_connect_callback( + self, + ) -> Callable[[CallbackOnPreConnect], CallbackOnPreConnect]: + def decorator(func: CallbackOnPreConnect) -> CallbackOnPreConnect: + self.on_pre_connect = func + return func + return decorator + + @property + def on_connect(self) -> CallbackOnConnect | None: + """The callback called when the broker reponds to our connection request. + + Expected signature for callback API version 2:: + + connect_callback(client, userdata, connect_flags, reason_code, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + connect_callback(client, userdata, flags, rc) + + * For MQTT v5.0 it's:: + + connect_callback(client, userdata, flags, reason_code, properties) + + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param ConnectFlags connect_flags: the flags for this connection + :param ReasonCode reason_code: the connection reason code received from the broken. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3, we convert return code to a reason code, see + `convert_connack_rc_to_reason_code()`. + `ReasonCode` may be compared to integer. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param dict flags: response flags sent by the broker + :param int rc: the connection result, should have a value of `ConnackCode` + + flags is a dict that contains response flags from the broker: + flags['session present'] - this flag is useful for clients that are + using clean session set to 0 only. If a client with clean + session=0, that reconnects to a broker that it has previously + connected to, this flag indicates whether the broker still has the + session information for the client. If 1, the session still exists. + + The value of rc indicates success or not: + - 0: Connection successful + - 1: Connection refused - incorrect protocol version + - 2: Connection refused - invalid client identifier + - 3: Connection refused - server unavailable + - 4: Connection refused - bad username or password + - 5: Connection refused - not authorised + - 6-255: Currently unused. + + Decorator: @client.connect_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_connect + + @on_connect.setter + def on_connect(self, func: CallbackOnConnect | None) -> None: + with self._callback_mutex: + self._on_connect = func + + def connect_callback( + self, + ) -> Callable[[CallbackOnConnect], CallbackOnConnect]: + def decorator(func: CallbackOnConnect) -> CallbackOnConnect: + self.on_connect = func + return func + return decorator + + @property + def on_connect_fail(self) -> CallbackOnConnectFail | None: + """The callback called when the client failed to connect + to the broker. + + Expected signature is (for all callback_api_version):: + + connect_fail_callback(client, userdata) + + :param Client client: the client instance for this callback + :parama userdata: the private user data as set in Client() or user_data_set() + + Decorator: @client.connect_fail_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_connect_fail + + @on_connect_fail.setter + def on_connect_fail(self, func: CallbackOnConnectFail | None) -> None: + with self._callback_mutex: + self._on_connect_fail = func + + def connect_fail_callback( + self, + ) -> Callable[[CallbackOnConnectFail], CallbackOnConnectFail]: + def decorator(func: CallbackOnConnectFail) -> CallbackOnConnectFail: + self.on_connect_fail = func + return func + return decorator + + @property + def on_subscribe(self) -> CallbackOnSubscribe | None: + """The callback called when the broker responds to a subscribe + request. + + Expected signature for callback API version 2:: + + subscribe_callback(client, userdata, mid, reason_code_list, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + subscribe_callback(client, userdata, mid, granted_qos) + + * For MQTT v5.0 it's:: + + subscribe_callback(client, userdata, mid, reason_code_list, properties) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param int mid: matches the mid variable returned from the corresponding + subscribe() call. + :param list[ReasonCode] reason_code_list: reason codes received from the broker for each subscription. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3, we convert granted QoS to a reason code. + It's a list of ReasonCode instances. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param list[int] granted_qos: list of integers that give the QoS level the broker has + granted for each of the different subscription requests. + + Decorator: @client.subscribe_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_subscribe + + @on_subscribe.setter + def on_subscribe(self, func: CallbackOnSubscribe | None) -> None: + with self._callback_mutex: + self._on_subscribe = func + + def subscribe_callback( + self, + ) -> Callable[[CallbackOnSubscribe], CallbackOnSubscribe]: + def decorator(func: CallbackOnSubscribe) -> CallbackOnSubscribe: + self.on_subscribe = func + return func + return decorator + + @property + def on_message(self) -> CallbackOnMessage | None: + """The callback called when a message has been received on a topic + that the client subscribes to. + + This callback will be called for every message received unless a + `message_callback_add()` matched the message. + + Expected signature is (for all callback API version): + message_callback(client, userdata, message) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param MQTTMessage message: the received message. + This is a class with members topic, payload, qos, retain. + + Decorator: @client.message_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_message + + @on_message.setter + def on_message(self, func: CallbackOnMessage | None) -> None: + with self._callback_mutex: + self._on_message = func + + def message_callback( + self, + ) -> Callable[[CallbackOnMessage], CallbackOnMessage]: + def decorator(func: CallbackOnMessage) -> CallbackOnMessage: + self.on_message = func + return func + return decorator + + @property + def on_publish(self) -> CallbackOnPublish | None: + """The callback called when a message that was to be sent using the + `publish()` call has completed transmission to the broker. + + For messages with QoS levels 1 and 2, this means that the appropriate + handshakes have completed. For QoS 0, this simply means that the message + has left the client. + This callback is important because even if the `publish()` call returns + success, it does not always mean that the message has been sent. + + See also `wait_for_publish` which could be simpler to use. + + Expected signature for callback API version 2:: + + publish_callback(client, userdata, mid, reason_code, properties) + + Expected signature for callback API version 1:: + + publish_callback(client, userdata, mid) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param int mid: matches the mid variable returned from the corresponding + `publish()` call, to allow outgoing messages to be tracked. + :param ReasonCode reason_code: the connection reason code received from the broken. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3 it's always the reason code Success + :parama Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + + Note: for QoS = 0, the reason_code and the properties don't really exist, it's the client + library that generate them. It's always an empty properties and a success reason code. + Because the (MQTTv5) standard don't have reason code for PUBLISH packet, the library create them + at PUBACK packet, as if the message was sent with QoS = 1. + + Decorator: @client.publish_callback() (``client`` is the name of the + instance which this callback is being attached to) + + """ + return self._on_publish + + @on_publish.setter + def on_publish(self, func: CallbackOnPublish | None) -> None: + with self._callback_mutex: + self._on_publish = func + + def publish_callback( + self, + ) -> Callable[[CallbackOnPublish], CallbackOnPublish]: + def decorator(func: CallbackOnPublish) -> CallbackOnPublish: + self.on_publish = func + return func + return decorator + + @property + def on_unsubscribe(self) -> CallbackOnUnsubscribe | None: + """The callback called when the broker responds to an unsubscribe + request. + + Expected signature for callback API version 2:: + + unsubscribe_callback(client, userdata, mid, reason_code_list, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + unsubscribe_callback(client, userdata, mid) + + * For MQTT v5.0 it's:: + + unsubscribe_callback(client, userdata, mid, properties, v1_reason_codes) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param mid: matches the mid variable returned from the corresponding + unsubscribe() call. + :param list[ReasonCode] reason_code_list: reason codes received from the broker for each unsubscription. + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3, there is not equivalent from broken and empty list + is always used. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param v1_reason_codes: the MQTT v5.0 reason codes received from the broker for each + unsubscribe topic. A list of ReasonCode instances OR a single + ReasonCode when we unsubscribe from a single topic. + + Decorator: @client.unsubscribe_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_unsubscribe + + @on_unsubscribe.setter + def on_unsubscribe(self, func: CallbackOnUnsubscribe | None) -> None: + with self._callback_mutex: + self._on_unsubscribe = func + + def unsubscribe_callback( + self, + ) -> Callable[[CallbackOnUnsubscribe], CallbackOnUnsubscribe]: + def decorator(func: CallbackOnUnsubscribe) -> CallbackOnUnsubscribe: + self.on_unsubscribe = func + return func + return decorator + + @property + def on_disconnect(self) -> CallbackOnDisconnect | None: + """The callback called when the client disconnects from the broker. + + Expected signature for callback API version 2:: + + disconnect_callback(client, userdata, disconnect_flags, reason_code, properties) + + Expected signature for callback API version 1 change with MQTT protocol version: + * For MQTT v3.1 and v3.1.1 it's:: + + disconnect_callback(client, userdata, rc) + + * For MQTT v5.0 it's:: + + disconnect_callback(client, userdata, reason_code, properties) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param DisconnectFlag disconnect_flags: the flags for this disconnection. + :param ReasonCode reason_code: the disconnection reason code possibly received from the broker (see disconnect_flags). + In MQTT v5.0 it's the reason code defined by the standard. + In MQTT v3 it's never received from the broker, we convert an MQTTErrorCode, + see `convert_disconnect_error_code_to_reason_code()`. + `ReasonCode` may be compared to integer. + :param Properties properties: the MQTT v5.0 properties received from the broker. + For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties + object is always used. + :param int rc: the disconnection result + The rc parameter indicates the disconnection state. If + MQTT_ERR_SUCCESS (0), the callback was called in response to + a disconnect() call. If any other value the disconnection + was unexpected, such as might be caused by a network error. + + Decorator: @client.disconnect_callback() (``client`` is the name of the + instance which this callback is being attached to) + + """ + return self._on_disconnect + + @on_disconnect.setter + def on_disconnect(self, func: CallbackOnDisconnect | None) -> None: + with self._callback_mutex: + self._on_disconnect = func + + def disconnect_callback( + self, + ) -> Callable[[CallbackOnDisconnect], CallbackOnDisconnect]: + def decorator(func: CallbackOnDisconnect) -> CallbackOnDisconnect: + self.on_disconnect = func + return func + return decorator + + @property + def on_socket_open(self) -> CallbackOnSocket | None: + """The callback called just after the socket was opend. + + This should be used to register the socket to an external event loop for reading. + + Expected signature is (for all callback API version):: + + socket_open_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which was just opened. + + Decorator: @client.socket_open_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_open + + @on_socket_open.setter + def on_socket_open(self, func: CallbackOnSocket | None) -> None: + with self._callback_mutex: + self._on_socket_open = func + + def socket_open_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator(func: CallbackOnSocket) -> CallbackOnSocket: + self.on_socket_open = func + return func + return decorator + + def _call_socket_open(self, sock: SocketLike) -> None: + """Call the socket_open callback with the just-opened socket""" + with self._callback_mutex: + on_socket_open = self.on_socket_open + + if on_socket_open: + with self._in_callback_mutex: + try: + on_socket_open(self, self._userdata, sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_open: %s', err) + if not self.suppress_exceptions: + raise + + @property + def on_socket_close(self) -> CallbackOnSocket | None: + """The callback called just before the socket is closed. + + This should be used to unregister the socket from an external event loop for reading. + + Expected signature is (for all callback API version):: + + socket_close_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which is about to be closed. + + Decorator: @client.socket_close_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_close + + @on_socket_close.setter + def on_socket_close(self, func: CallbackOnSocket | None) -> None: + with self._callback_mutex: + self._on_socket_close = func + + def socket_close_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator(func: CallbackOnSocket) -> CallbackOnSocket: + self.on_socket_close = func + return func + return decorator + + def _call_socket_close(self, sock: SocketLike) -> None: + """Call the socket_close callback with the about-to-be-closed socket""" + with self._callback_mutex: + on_socket_close = self.on_socket_close + + if on_socket_close: + with self._in_callback_mutex: + try: + on_socket_close(self, self._userdata, sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_close: %s', err) + if not self.suppress_exceptions: + raise + + @property + def on_socket_register_write(self) -> CallbackOnSocket | None: + """The callback called when the socket needs writing but can't. + + This should be used to register the socket with an external event loop for writing. + + Expected signature is (for all callback API version):: + + socket_register_write_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which should be registered for writing + + Decorator: @client.socket_register_write_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_register_write + + @on_socket_register_write.setter + def on_socket_register_write(self, func: CallbackOnSocket | None) -> None: + with self._callback_mutex: + self._on_socket_register_write = func + + def socket_register_write_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator(func: CallbackOnSocket) -> CallbackOnSocket: + self._on_socket_register_write = func + return func + return decorator + + def _call_socket_register_write(self) -> None: + """Call the socket_register_write callback with the unwritable socket""" + if not self._sock or self._registered_write: + return + self._registered_write = True + with self._callback_mutex: + on_socket_register_write = self.on_socket_register_write + + if on_socket_register_write: + try: + on_socket_register_write( + self, self._userdata, self._sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_register_write: %s', err) + if not self.suppress_exceptions: + raise + + @property + def on_socket_unregister_write( + self, + ) -> CallbackOnSocket | None: + """The callback called when the socket doesn't need writing anymore. + + This should be used to unregister the socket from an external event loop for writing. + + Expected signature is (for all callback API version):: + + socket_unregister_write_callback(client, userdata, socket) + + :param Client client: the client instance for this callback + :param userdata: the private user data as set in Client() or user_data_set() + :param SocketLike sock: the socket which should be unregistered for writing + + Decorator: @client.socket_unregister_write_callback() (``client`` is the name of the + instance which this callback is being attached to) + """ + return self._on_socket_unregister_write + + @on_socket_unregister_write.setter + def on_socket_unregister_write( + self, func: CallbackOnSocket | None + ) -> None: + with self._callback_mutex: + self._on_socket_unregister_write = func + + def socket_unregister_write_callback( + self, + ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: + def decorator( + func: CallbackOnSocket, + ) -> CallbackOnSocket: + self._on_socket_unregister_write = func + return func + return decorator + + def _call_socket_unregister_write( + self, sock: SocketLike | None = None + ) -> None: + """Call the socket_unregister_write callback with the writable socket""" + sock = sock or self._sock + if not sock or not self._registered_write: + return + self._registered_write = False + + with self._callback_mutex: + on_socket_unregister_write = self.on_socket_unregister_write + + if on_socket_unregister_write: + try: + on_socket_unregister_write(self, self._userdata, sock) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_socket_unregister_write: %s', err) + if not self.suppress_exceptions: + raise + + def message_callback_add(self, sub: str, callback: CallbackOnMessage) -> None: + """Register a message callback for a specific topic. + Messages that match 'sub' will be passed to 'callback'. Any + non-matching messages will be passed to the default `on_message` + callback. + + Call multiple times with different 'sub' to define multiple topic + specific callbacks. + + Topic specific callbacks may be removed with + `message_callback_remove()`. + + See `on_message` for the expected signature of the callback. + + Decorator: @client.topic_callback(sub) (``client`` is the name of the + instance which this callback is being attached to) + + Example:: + + @client.topic_callback("mytopic/#") + def handle_mytopic(client, userdata, message): + ... + """ + if callback is None or sub is None: + raise ValueError("sub and callback must both be defined.") + + with self._callback_mutex: + self._on_message_filtered[sub] = callback + + def topic_callback( + self, sub: str + ) -> Callable[[CallbackOnMessage], CallbackOnMessage]: + def decorator(func: CallbackOnMessage) -> CallbackOnMessage: + self.message_callback_add(sub, func) + return func + return decorator + + def message_callback_remove(self, sub: str) -> None: + """Remove a message callback previously registered with + `message_callback_add()`.""" + if sub is None: + raise ValueError("sub must defined.") + + with self._callback_mutex: + try: + del self._on_message_filtered[sub] + except KeyError: # no such subscription + pass + + # ============================================================ + # Private functions + # ============================================================ + + def _loop_rc_handle( + self, + rc: MQTTErrorCode, + ) -> MQTTErrorCode: + if rc: + self._sock_close() + + if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + + self._do_on_disconnect(packet_from_broker=False, v1_rc=rc) + + if rc == MQTT_ERR_CONN_LOST: + self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST + + return rc + + def _packet_read(self) -> MQTTErrorCode: + # This gets called if pselect() indicates that there is network data + # available - ie. at least one byte. What we do depends on what data we + # already have. + # If we've not got a command, attempt to read one and save it. This should + # always work because it's only a single byte. + # Then try to read the remaining length. This may fail because it is may + # be more than one byte - will need to save data pending next read if it + # does fail. + # Then try to read the remaining payload, where 'payload' here means the + # combined variable header and actual payload. This is the most likely to + # fail due to longer length, so save current data and current position. + # After all data is read, send to _mqtt_handle_packet() to deal with. + # Finally, free the memory and reset everything to starting conditions. + if self._in_packet['command'] == 0: + try: + command = self._sock_recv(1) + except BlockingIOError: + return MQTTErrorCode.MQTT_ERR_AGAIN + except TimeoutError as err: + self._easy_log( + MQTT_LOG_ERR, 'timeout on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + except OSError as err: + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + else: + if len(command) == 0: + return MQTTErrorCode.MQTT_ERR_CONN_LOST + self._in_packet['command'] = command[0] + + if self._in_packet['have_remaining'] == 0: + # Read remaining + # Algorithm for decoding taken from pseudo code at + # http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm + while True: + try: + byte = self._sock_recv(1) + except BlockingIOError: + return MQTTErrorCode.MQTT_ERR_AGAIN + except OSError as err: + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + else: + if len(byte) == 0: + return MQTTErrorCode.MQTT_ERR_CONN_LOST + byte_value = byte[0] + self._in_packet['remaining_count'].append(byte_value) + # Max 4 bytes length for remaining length as defined by protocol. + # Anything more likely means a broken/malicious client. + if len(self._in_packet['remaining_count']) > 4: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + self._in_packet['remaining_length'] += ( + byte_value & 127) * self._in_packet['remaining_mult'] + self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128 + + if (byte_value & 128) == 0: + break + + self._in_packet['have_remaining'] = 1 + self._in_packet['to_process'] = self._in_packet['remaining_length'] + + count = 100 # Don't get stuck in this loop if we have a huge message. + while self._in_packet['to_process'] > 0: + try: + data = self._sock_recv(self._in_packet['to_process']) + except BlockingIOError: + return MQTTErrorCode.MQTT_ERR_AGAIN + except OSError as err: + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + else: + if len(data) == 0: + return MQTTErrorCode.MQTT_ERR_CONN_LOST + self._in_packet['to_process'] -= len(data) + self._in_packet['packet'] += data + count -= 1 + if count == 0: + with self._msgtime_mutex: + self._last_msg_in = time_func() + return MQTTErrorCode.MQTT_ERR_AGAIN + + # All data for this packet is read. + self._in_packet['pos'] = 0 + rc = self._packet_handle() + + # Free data and reset values + self._in_packet = { + "command": 0, + "have_remaining": 0, + "remaining_count": [], + "remaining_mult": 1, + "remaining_length": 0, + "packet": bytearray(b""), + "to_process": 0, + "pos": 0, + } + + with self._msgtime_mutex: + self._last_msg_in = time_func() + return rc + + def _packet_write(self) -> MQTTErrorCode: + while True: + try: + packet = self._out_packet.popleft() + except IndexError: + return MQTTErrorCode.MQTT_ERR_SUCCESS + + try: + write_length = self._sock_send( + packet['packet'][packet['pos']:]) + except (AttributeError, ValueError): + self._out_packet.appendleft(packet) + return MQTTErrorCode.MQTT_ERR_SUCCESS + except BlockingIOError: + self._out_packet.appendleft(packet) + return MQTTErrorCode.MQTT_ERR_AGAIN + except OSError as err: + self._out_packet.appendleft(packet) + self._easy_log( + MQTT_LOG_ERR, 'failed to receive on socket: %s', err) + return MQTTErrorCode.MQTT_ERR_CONN_LOST + + if write_length > 0: + packet['to_process'] -= write_length + packet['pos'] += write_length + + if packet['to_process'] == 0: + if (packet['command'] & 0xF0) == PUBLISH and packet['qos'] == 0: + with self._callback_mutex: + on_publish = self.on_publish + + if on_publish: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + on_publish = cast(CallbackOnPublish_v1, on_publish) + + on_publish(self, self._userdata, packet["mid"]) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_publish = cast(CallbackOnPublish_v2, on_publish) + + on_publish( + self, + self._userdata, + packet["mid"], + ReasonCode(PacketTypes.PUBACK), + Properties(PacketTypes.PUBACK), + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err) + if not self.suppress_exceptions: + raise + + # TODO: Something is odd here. I don't see why packet["info"] can't be None. + # A packet could be produced by _handle_connack with qos=0 and no info + # (around line 3645). Ignore the mypy check for now but I feel there is a bug + # somewhere. + packet['info']._set_as_published() # type: ignore + + if (packet['command'] & 0xF0) == DISCONNECT: + with self._msgtime_mutex: + self._last_msg_out = time_func() + + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, + ) + self._sock_close() + # Only change to disconnected if the disconnection was wanted + # by the client (== state was disconnecting). If the broker disconnected + # use unilaterally don't change the state and client may reconnect. + if self._state == _ConnectionState.MQTT_CS_DISCONNECTING: + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + return MQTTErrorCode.MQTT_ERR_SUCCESS + + else: + # We haven't finished with this packet + self._out_packet.appendleft(packet) + else: + break + + with self._msgtime_mutex: + self._last_msg_out = time_func() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _easy_log(self, level: LogLevel, fmt: str, *args: Any) -> None: + if self.on_log is not None: + buf = fmt % args + try: + self.on_log(self, self._userdata, level, buf) + except Exception: # noqa: S110 + # Can't _easy_log this, as we'll recurse until we break + pass # self._logger will pick this up, so we're fine + if self._logger is not None: + level_std = LOGGING_LEVEL[level] + self._logger.log(level_std, fmt, *args) + + def _check_keepalive(self) -> None: + if self._keepalive == 0: + return + + now = time_func() + + with self._msgtime_mutex: + last_msg_out = self._last_msg_out + last_msg_in = self._last_msg_in + + if self._sock is not None and (now - last_msg_out >= self._keepalive or now - last_msg_in >= self._keepalive): + if self._state == _ConnectionState.MQTT_CS_CONNECTED and self._ping_t == 0: + try: + self._send_pingreq() + except Exception: + self._sock_close() + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=MQTTErrorCode.MQTT_ERR_CONN_LOST, + ) + else: + with self._msgtime_mutex: + self._last_msg_out = now + self._last_msg_in = now + else: + self._sock_close() + + if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): + self._state = _ConnectionState.MQTT_CS_DISCONNECTED + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + else: + rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE + + self._do_on_disconnect( + packet_from_broker=False, + v1_rc=rc, + ) + + def _mid_generate(self) -> int: + with self._mid_generate_mutex: + self._last_mid += 1 + if self._last_mid == 65536: + self._last_mid = 1 + return self._last_mid + + @staticmethod + def _raise_for_invalid_topic(topic: bytes) -> None: + """ Check if the topic is a topic without wildcard and valid length. + + Raise ValueError if the topic isn't valid. + """ + if b'+' in topic or b'#' in topic: + raise ValueError('Publish topic cannot contain wildcards.') + if len(topic) > 65535: + raise ValueError('Publish topic is too long.') + + @staticmethod + def _filter_wildcard_len_check(sub: bytes) -> MQTTErrorCode: + if (len(sub) == 0 or len(sub) > 65535 + or any(b'+' in p or b'#' in p for p in sub.split(b'/') if len(p) > 1) + or b'#/' in sub): + return MQTTErrorCode.MQTT_ERR_INVAL + else: + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _send_pingreq(self) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PINGREQ") + rc = self._send_simple_command(PINGREQ) + if rc == MQTTErrorCode.MQTT_ERR_SUCCESS: + self._ping_t = time_func() + return rc + + def _send_pingresp(self) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PINGRESP") + return self._send_simple_command(PINGRESP) + + def _send_puback(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBACK (Mid: %d)", mid) + return self._send_command_with_mid(PUBACK, mid, False) + + def _send_pubcomp(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBCOMP (Mid: %d)", mid) + return self._send_command_with_mid(PUBCOMP, mid, False) + + def _pack_remaining_length( + self, packet: bytearray, remaining_length: int + ) -> bytearray: + remaining_bytes = [] + while True: + byte = remaining_length % 128 + remaining_length = remaining_length // 128 + # If there are more digits to encode, set the top bit of this digit + if remaining_length > 0: + byte |= 0x80 + + remaining_bytes.append(byte) + packet.append(byte) + if remaining_length == 0: + # FIXME - this doesn't deal with incorrectly large payloads + return packet + + def _pack_str16(self, packet: bytearray, data: bytes | str) -> None: + data = _force_bytes(data) + packet.extend(struct.pack("!H", len(data))) + packet.extend(data) + + def _send_publish( + self, + mid: int, + topic: bytes, + payload: bytes|bytearray = b"", + qos: int = 0, + retain: bool = False, + dup: bool = False, + info: MQTTMessageInfo | None = None, + properties: Properties | None = None, + ) -> MQTTErrorCode: + # we assume that topic and payload are already properly encoded + if not isinstance(topic, bytes): + raise TypeError('topic must be bytes, not str') + if payload and not isinstance(payload, (bytes, bytearray)): + raise TypeError('payload must be bytes if set') + + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + + command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain + packet = bytearray() + packet.append(command) + + payloadlen = len(payload) + remaining_length = 2 + len(topic) + payloadlen + + if payloadlen == 0: + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s (NULL payload)", + dup, qos, retain, mid, topic, properties + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s' (NULL payload)", + dup, qos, retain, mid, topic + ) + else: + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)", + dup, qos, retain, mid, topic, properties, payloadlen + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)", + dup, qos, retain, mid, topic, payloadlen + ) + + if qos > 0: + # For message id + remaining_length += 2 + + if self._protocol == MQTTv5: + if properties is None: + packed_properties = b'\x00' + else: + packed_properties = properties.pack() + remaining_length += len(packed_properties) + + self._pack_remaining_length(packet, remaining_length) + self._pack_str16(packet, topic) + + if qos > 0: + # For message id + packet.extend(struct.pack("!H", mid)) + + if self._protocol == MQTTv5: + packet.extend(packed_properties) + + packet.extend(payload) + + return self._packet_queue(PUBLISH, packet, mid, qos, info) + + def _send_pubrec(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREC (Mid: %d)", mid) + return self._send_command_with_mid(PUBREC, mid, False) + + def _send_pubrel(self, mid: int) -> MQTTErrorCode: + self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREL (Mid: %d)", mid) + return self._send_command_with_mid(PUBREL | 2, mid, False) + + def _send_command_with_mid(self, command: int, mid: int, dup: int) -> MQTTErrorCode: + # For PUBACK, PUBCOMP, PUBREC, and PUBREL + if dup: + command |= 0x8 + + remaining_length = 2 + packet = struct.pack('!BBH', command, remaining_length, mid) + return self._packet_queue(command, packet, mid, 1) + + def _send_simple_command(self, command: int) -> MQTTErrorCode: + # For DISCONNECT, PINGREQ and PINGRESP + remaining_length = 0 + packet = struct.pack('!BB', command, remaining_length) + return self._packet_queue(command, packet, 0, 0) + + def _send_connect(self, keepalive: int) -> MQTTErrorCode: + proto_ver = int(self._protocol) + # hard-coded UTF-8 encoded string + protocol = b"MQTT" if proto_ver >= MQTTv311 else b"MQIsdp" + + remaining_length = 2 + len(protocol) + 1 + \ + 1 + 2 + 2 + len(self._client_id) + + connect_flags = 0 + if self._protocol == MQTTv5: + if self._clean_start is True: + connect_flags |= 0x02 + elif self._clean_start == MQTT_CLEAN_START_FIRST_ONLY and self._mqttv5_first_connect: + connect_flags |= 0x02 + elif self._clean_session: + connect_flags |= 0x02 + + if self._will: + remaining_length += 2 + \ + len(self._will_topic) + 2 + len(self._will_payload) + connect_flags |= 0x04 | ((self._will_qos & 0x03) << 3) | ( + (self._will_retain & 0x01) << 5) + + if self._username is not None: + remaining_length += 2 + len(self._username) + connect_flags |= 0x80 + if self._password is not None: + connect_flags |= 0x40 + remaining_length += 2 + len(self._password) + + if self._protocol == MQTTv5: + if self._connect_properties is None: + packed_connect_properties = b'\x00' + else: + packed_connect_properties = self._connect_properties.pack() + remaining_length += len(packed_connect_properties) + if self._will: + if self._will_properties is None: + packed_will_properties = b'\x00' + else: + packed_will_properties = self._will_properties.pack() + remaining_length += len(packed_will_properties) + + command = CONNECT + packet = bytearray() + packet.append(command) + + # as per the mosquitto broker, if the MSB of this version is set + # to 1, then it treats the connection as a bridge + if self._client_mode == MQTT_BRIDGE: + proto_ver |= 0x80 + + self._pack_remaining_length(packet, remaining_length) + packet.extend(struct.pack( + f"!H{len(protocol)}sBBH", + len(protocol), protocol, proto_ver, connect_flags, keepalive, + )) + + if self._protocol == MQTTv5: + packet += packed_connect_properties + + self._pack_str16(packet, self._client_id) + + if self._will: + if self._protocol == MQTTv5: + packet += packed_will_properties + self._pack_str16(packet, self._will_topic) + self._pack_str16(packet, self._will_payload) + + if self._username is not None: + self._pack_str16(packet, self._username) + + if self._password is not None: + self._pack_str16(packet, self._password) + + self._keepalive = keepalive + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%s", + (connect_flags & 0x80) >> 7, + (connect_flags & 0x40) >> 6, + (connect_flags & 0x20) >> 5, + (connect_flags & 0x18) >> 3, + (connect_flags & 0x4) >> 2, + (connect_flags & 0x2) >> 1, + keepalive, + self._client_id, + self._connect_properties + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s", + (connect_flags & 0x80) >> 7, + (connect_flags & 0x40) >> 6, + (connect_flags & 0x20) >> 5, + (connect_flags & 0x18) >> 3, + (connect_flags & 0x4) >> 2, + (connect_flags & 0x2) >> 1, + keepalive, + self._client_id + ) + return self._packet_queue(command, packet, 0, 0) + + def _send_disconnect( + self, + reasoncode: ReasonCode | None = None, + properties: Properties | None = None, + ) -> MQTTErrorCode: + if self._protocol == MQTTv5: + self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT reasonCode=%s properties=%s", + reasoncode, + properties + ) + else: + self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT") + + remaining_length = 0 + + command = DISCONNECT + packet = bytearray() + packet.append(command) + + if self._protocol == MQTTv5: + if properties is not None or reasoncode is not None: + if reasoncode is None: + reasoncode = ReasonCode(DISCONNECT >> 4, identifier=0) + remaining_length += 1 + if properties is not None: + packed_props = properties.pack() + remaining_length += len(packed_props) + + self._pack_remaining_length(packet, remaining_length) + + if self._protocol == MQTTv5: + if reasoncode is not None: + packet += reasoncode.pack() + if properties is not None: + packet += packed_props + + return self._packet_queue(command, packet, 0, 0) + + def _send_subscribe( + self, + dup: int, + topics: Sequence[tuple[bytes, SubscribeOptions | int]], + properties: Properties | None = None, + ) -> tuple[MQTTErrorCode, int]: + remaining_length = 2 + if self._protocol == MQTTv5: + if properties is None: + packed_subscribe_properties = b'\x00' + else: + packed_subscribe_properties = properties.pack() + remaining_length += len(packed_subscribe_properties) + for t, _ in topics: + remaining_length += 2 + len(t) + 1 + + command = SUBSCRIBE | (dup << 3) | 0x2 + packet = bytearray() + packet.append(command) + self._pack_remaining_length(packet, remaining_length) + local_mid = self._mid_generate() + packet.extend(struct.pack("!H", local_mid)) + + if self._protocol == MQTTv5: + packet += packed_subscribe_properties + + for t, q in topics: + self._pack_str16(packet, t) + if self._protocol == MQTTv5: + packet += q.pack() # type: ignore + else: + packet.append(q) # type: ignore + + self._easy_log( + MQTT_LOG_DEBUG, + "Sending SUBSCRIBE (d%d, m%d) %s", + dup, + local_mid, + topics, + ) + return (self._packet_queue(command, packet, local_mid, 1), local_mid) + + def _send_unsubscribe( + self, + dup: int, + topics: list[bytes], + properties: Properties | None = None, + ) -> tuple[MQTTErrorCode, int]: + remaining_length = 2 + if self._protocol == MQTTv5: + if properties is None: + packed_unsubscribe_properties = b'\x00' + else: + packed_unsubscribe_properties = properties.pack() + remaining_length += len(packed_unsubscribe_properties) + for t in topics: + remaining_length += 2 + len(t) + + command = UNSUBSCRIBE | (dup << 3) | 0x2 + packet = bytearray() + packet.append(command) + self._pack_remaining_length(packet, remaining_length) + local_mid = self._mid_generate() + packet.extend(struct.pack("!H", local_mid)) + + if self._protocol == MQTTv5: + packet += packed_unsubscribe_properties + + for t in topics: + self._pack_str16(packet, t) + + # topics_repr = ", ".join("'"+topic.decode('utf8')+"'" for topic in topics) + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending UNSUBSCRIBE (d%d, m%d) %s %s", + dup, + local_mid, + properties, + topics, + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Sending UNSUBSCRIBE (d%d, m%d) %s", + dup, + local_mid, + topics, + ) + return (self._packet_queue(command, packet, local_mid, 1), local_mid) + + def _check_clean_session(self) -> bool: + if self._protocol == MQTTv5: + if self._clean_start == MQTT_CLEAN_START_FIRST_ONLY: + return self._mqttv5_first_connect + else: + return self._clean_start # type: ignore + else: + return self._clean_session + + def _messages_reconnect_reset_out(self) -> None: + with self._out_message_mutex: + self._inflight_messages = 0 + for m in self._out_messages.values(): + m.timestamp = 0 + if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages: + if m.qos == 0: + m.state = mqtt_ms_publish + elif m.qos == 1: + # self._inflight_messages = self._inflight_messages + 1 + if m.state == mqtt_ms_wait_for_puback: + m.dup = True + m.state = mqtt_ms_publish + elif m.qos == 2: + # self._inflight_messages = self._inflight_messages + 1 + if self._check_clean_session(): + if m.state != mqtt_ms_publish: + m.dup = True + m.state = mqtt_ms_publish + else: + if m.state == mqtt_ms_wait_for_pubcomp: + m.state = mqtt_ms_resend_pubrel + else: + if m.state == mqtt_ms_wait_for_pubrec: + m.dup = True + m.state = mqtt_ms_publish + else: + m.state = mqtt_ms_queued + + def _messages_reconnect_reset_in(self) -> None: + with self._in_message_mutex: + if self._check_clean_session(): + self._in_messages = collections.OrderedDict() + return + for m in self._in_messages.values(): + m.timestamp = 0 + if m.qos != 2: + self._in_messages.pop(m.mid) + else: + # Preserve current state + pass + + def _messages_reconnect_reset(self) -> None: + self._messages_reconnect_reset_out() + self._messages_reconnect_reset_in() + + def _packet_queue( + self, + command: int, + packet: bytes, + mid: int, + qos: int, + info: MQTTMessageInfo | None = None, + ) -> MQTTErrorCode: + mpkt: _OutPacket = { + "command": command, + "mid": mid, + "qos": qos, + "pos": 0, + "to_process": len(packet), + "packet": packet, + "info": info, + } + + self._out_packet.append(mpkt) + + # Write a single byte to sockpairW (connected to sockpairR) to break + # out of select() if in threaded mode. + if self._sockpairW is not None: + try: + self._sockpairW.send(sockpair_data) + except BlockingIOError: + pass + + # If we have an external event loop registered, use that instead + # of calling loop_write() directly. + if self._thread is None and self._on_socket_register_write is None: + if self._in_callback_mutex.acquire(False): + self._in_callback_mutex.release() + return self.loop_write() + + self._call_socket_register_write() + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _packet_handle(self) -> MQTTErrorCode: + cmd = self._in_packet['command'] & 0xF0 + if cmd == PINGREQ: + return self._handle_pingreq() + elif cmd == PINGRESP: + return self._handle_pingresp() + elif cmd == PUBACK: + return self._handle_pubackcomp("PUBACK") + elif cmd == PUBCOMP: + return self._handle_pubackcomp("PUBCOMP") + elif cmd == PUBLISH: + return self._handle_publish() + elif cmd == PUBREC: + return self._handle_pubrec() + elif cmd == PUBREL: + return self._handle_pubrel() + elif cmd == CONNACK: + return self._handle_connack() + elif cmd == SUBACK: + self._handle_suback() + return MQTTErrorCode.MQTT_ERR_SUCCESS + elif cmd == UNSUBACK: + return self._handle_unsuback() + elif cmd == DISCONNECT and self._protocol == MQTTv5: # only allowed in MQTT 5.0 + self._handle_disconnect() + return MQTTErrorCode.MQTT_ERR_SUCCESS + else: + # If we don't recognise the command, return an error straight away. + self._easy_log(MQTT_LOG_ERR, "Error: Unrecognised command %s", cmd) + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + def _handle_pingreq(self) -> MQTTErrorCode: + if self._in_packet['remaining_length'] != 0: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + self._easy_log(MQTT_LOG_DEBUG, "Received PINGREQ") + return self._send_pingresp() + + def _handle_pingresp(self) -> MQTTErrorCode: + if self._in_packet['remaining_length'] != 0: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + # No longer waiting for a PINGRESP. + self._ping_t = 0 + self._easy_log(MQTT_LOG_DEBUG, "Received PINGRESP") + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_connack(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + if self._protocol == MQTTv5: + (flags, result) = struct.unpack( + "!BB", self._in_packet['packet'][:2]) + if result == 1: + # This is probably a failure from a broker that doesn't support + # MQTT v5. + reason = ReasonCode(CONNACK >> 4, aName="Unsupported protocol version") + properties = None + else: + reason = ReasonCode(CONNACK >> 4, identifier=result) + properties = Properties(CONNACK >> 4) + properties.unpack(self._in_packet['packet'][2:]) + else: + (flags, result) = struct.unpack("!BB", self._in_packet['packet']) + reason = convert_connack_rc_to_reason_code(result) + properties = None + if self._protocol == MQTTv311: + if result == CONNACK_REFUSED_PROTOCOL_VERSION: + if not self._reconnect_on_failure: + return MQTT_ERR_PROTOCOL + self._easy_log( + MQTT_LOG_DEBUG, + "Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.", + flags, result + ) + # Downgrade to MQTT v3.1 + self._protocol = MQTTv31 + return self.reconnect() + elif (result == CONNACK_REFUSED_IDENTIFIER_REJECTED + and self._client_id == b''): + if not self._reconnect_on_failure: + return MQTT_ERR_PROTOCOL + self._easy_log( + MQTT_LOG_DEBUG, + "Received CONNACK (%s, %s), attempting to use non-empty CID", + flags, result, + ) + self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8") + return self.reconnect() + + if result == 0: + self._state = _ConnectionState.MQTT_CS_CONNECTED + self._reconnect_delay = None + + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, "Received CONNACK (%s, %s) properties=%s", flags, reason, properties) + else: + self._easy_log( + MQTT_LOG_DEBUG, "Received CONNACK (%s, %s)", flags, result) + + # it won't be the first successful connect any more + self._mqttv5_first_connect = False + + with self._callback_mutex: + on_connect = self.on_connect + + if on_connect: + flags_dict = {} + flags_dict['session present'] = flags & 0x01 + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_connect = cast(CallbackOnConnect_v1_mqtt5, on_connect) + + on_connect(self, self._userdata, + flags_dict, reason, properties) + else: + on_connect = cast(CallbackOnConnect_v1_mqtt3, on_connect) + + on_connect( + self, self._userdata, flags_dict, result) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_connect = cast(CallbackOnConnect_v2, on_connect) + + connect_flags = ConnectFlags( + session_present=flags_dict['session present'] > 0 + ) + + if properties is None: + properties = Properties(PacketTypes.CONNACK) + + on_connect( + self, + self._userdata, + connect_flags, + reason, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_connect: %s', err) + if not self.suppress_exceptions: + raise + + if result == 0: + rc = MQTTErrorCode.MQTT_ERR_SUCCESS + with self._out_message_mutex: + for m in self._out_messages.values(): + m.timestamp = time_func() + if m.state == mqtt_ms_queued: + self.loop_write() # Process outgoing messages that have just been queued up + return MQTT_ERR_SUCCESS + + if m.qos == 0: + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + elif m.qos == 1: + if m.state == mqtt_ms_publish: + self._inflight_messages += 1 + m.state = mqtt_ms_wait_for_puback + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + elif m.qos == 2: + if m.state == mqtt_ms_publish: + self._inflight_messages += 1 + m.state = mqtt_ms_wait_for_pubrec + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + elif m.state == mqtt_ms_resend_pubrel: + self._inflight_messages += 1 + m.state = mqtt_ms_wait_for_pubcomp + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + rc = self._send_pubrel(m.mid) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + self.loop_write() # Process outgoing messages that have just been queued up + + return rc + elif result > 0 and result < 6: + return MQTTErrorCode.MQTT_ERR_CONN_REFUSED + else: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + def _handle_disconnect(self) -> None: + packet_type = DISCONNECT >> 4 + reasonCode = properties = None + if self._in_packet['remaining_length'] > 2: + reasonCode = ReasonCode(packet_type) + reasonCode.unpack(self._in_packet['packet']) + if self._in_packet['remaining_length'] > 3: + properties = Properties(packet_type) + props, props_len = properties.unpack( + self._in_packet['packet'][1:]) + self._easy_log(MQTT_LOG_DEBUG, "Received DISCONNECT %s %s", + reasonCode, + properties + ) + + self._sock_close() + self._do_on_disconnect( + packet_from_broker=True, + v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, # If reason is absent (remaining length < 1), it means normal disconnection + reason=reasonCode, + properties=properties, + ) + + def _handle_suback(self) -> None: + self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK") + pack_format = f"!H{len(self._in_packet['packet']) - 2}s" + (mid, packet) = struct.unpack(pack_format, self._in_packet['packet']) + + if self._protocol == MQTTv5: + properties = Properties(SUBACK >> 4) + props, props_len = properties.unpack(packet) + reasoncodes = [ReasonCode(SUBACK >> 4, identifier=c) for c in packet[props_len:]] + else: + pack_format = f"!{'B' * len(packet)}" + granted_qos = struct.unpack(pack_format, packet) + reasoncodes = [ReasonCode(SUBACK >> 4, identifier=c) for c in granted_qos] + properties = Properties(SUBACK >> 4) + + with self._callback_mutex: + on_subscribe = self.on_subscribe + + if on_subscribe: + with self._in_callback_mutex: # Don't call loop_write after _send_publish() + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_subscribe = cast(CallbackOnSubscribe_v1_mqtt5, on_subscribe) + + on_subscribe( + self, self._userdata, mid, reasoncodes, properties) + else: + on_subscribe = cast(CallbackOnSubscribe_v1_mqtt3, on_subscribe) + + on_subscribe( + self, self._userdata, mid, granted_qos) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_subscribe = cast(CallbackOnSubscribe_v2, on_subscribe) + + on_subscribe( + self, + self._userdata, + mid, + reasoncodes, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_subscribe: %s', err) + if not self.suppress_exceptions: + raise + + def _handle_publish(self) -> MQTTErrorCode: + header = self._in_packet['command'] + message = MQTTMessage() + message.dup = ((header & 0x08) >> 3) != 0 + message.qos = (header & 0x06) >> 1 + message.retain = (header & 0x01) != 0 + + pack_format = f"!H{len(self._in_packet['packet']) - 2}s" + (slen, packet) = struct.unpack(pack_format, self._in_packet['packet']) + pack_format = f"!{slen}s{len(packet) - slen}s" + (topic, packet) = struct.unpack(pack_format, packet) + + if self._protocol != MQTTv5 and len(topic) == 0: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + # Handle topics with invalid UTF-8 + # This replaces an invalid topic with a message and the hex + # representation of the topic for logging. When the user attempts to + # access message.topic in the callback, an exception will be raised. + try: + print_topic = topic.decode('utf-8') + except UnicodeDecodeError: + print_topic = f"TOPIC WITH INVALID UTF-8: {topic!r}" + + message.topic = topic + + if message.qos > 0: + pack_format = f"!H{len(packet) - 2}s" + (message.mid, packet) = struct.unpack(pack_format, packet) + + if self._protocol == MQTTv5: + message.properties = Properties(PUBLISH >> 4) + props, props_len = message.properties.unpack(packet) + packet = packet[props_len:] + + message.payload = packet + + if self._protocol == MQTTv5: + self._easy_log( + MQTT_LOG_DEBUG, + "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)", + message.dup, message.qos, message.retain, message.mid, + print_topic, message.properties, len(message.payload) + ) + else: + self._easy_log( + MQTT_LOG_DEBUG, + "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)", + message.dup, message.qos, message.retain, message.mid, + print_topic, len(message.payload) + ) + + message.timestamp = time_func() + if message.qos == 0: + self._handle_on_message(message) + return MQTTErrorCode.MQTT_ERR_SUCCESS + elif message.qos == 1: + self._handle_on_message(message) + if self._manual_ack: + return MQTTErrorCode.MQTT_ERR_SUCCESS + else: + return self._send_puback(message.mid) + elif message.qos == 2: + + rc = self._send_pubrec(message.mid) + + message.state = mqtt_ms_wait_for_pubrel + with self._in_message_mutex: + self._in_messages[message.mid] = message + + return rc + else: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + def ack(self, mid: int, qos: int) -> MQTTErrorCode: + """ + send an acknowledgement for a given message id (stored in :py:attr:`message.mid `). + only useful in QoS>=1 and ``manual_ack=True`` (option of `Client`) + """ + if self._manual_ack : + if qos == 1: + return self._send_puback(mid) + elif qos == 2: + return self._send_pubcomp(mid) + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def manual_ack_set(self, on: bool) -> None: + """ + The paho library normally acknowledges messages as soon as they are delivered to the caller. + If manual_ack is turned on, then the caller MUST manually acknowledge every message once + application processing is complete using `ack()` + """ + self._manual_ack = on + + + def _handle_pubrel(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] > 2: + reasonCode = ReasonCode(PUBREL >> 4) + reasonCode.unpack(self._in_packet['packet'][2:]) + if self._in_packet['remaining_length'] > 3: + properties = Properties(PUBREL >> 4) + props, props_len = properties.unpack( + self._in_packet['packet'][3:]) + self._easy_log(MQTT_LOG_DEBUG, "Received PUBREL (Mid: %d)", mid) + + with self._in_message_mutex: + if mid in self._in_messages: + # Only pass the message on if we have removed it from the queue - this + # prevents multiple callbacks for the same message. + message = self._in_messages.pop(mid) + self._handle_on_message(message) + self._inflight_messages -= 1 + if self._max_inflight_messages > 0: + with self._out_message_mutex: + rc = self._update_inflight() + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + + # FIXME: this should only be done if the message is known + # If unknown it's a protocol error and we should close the connection. + # But since we don't have (on disk) persistence for the session, it + # is possible that we must known about this message. + # Choose to acknowledge this message (thus losing a message) but + # avoid hanging. See #284. + if self._manual_ack: + return MQTTErrorCode.MQTT_ERR_SUCCESS + else: + return self._send_pubcomp(mid) + + def _update_inflight(self) -> MQTTErrorCode: + # Dont lock message_mutex here + for m in self._out_messages.values(): + if self._inflight_messages < self._max_inflight_messages: + if m.qos > 0 and m.state == mqtt_ms_queued: + self._inflight_messages += 1 + if m.qos == 1: + m.state = mqtt_ms_wait_for_puback + elif m.qos == 2: + m.state = mqtt_ms_wait_for_pubrec + rc = self._send_publish( + m.mid, + m.topic.encode('utf-8'), + m.payload, + m.qos, + m.retain, + m.dup, + properties=m.properties, + ) + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + else: + return MQTTErrorCode.MQTT_ERR_SUCCESS + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_pubrec(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] > 2: + reasonCode = ReasonCode(PUBREC >> 4) + reasonCode.unpack(self._in_packet['packet'][2:]) + if self._in_packet['remaining_length'] > 3: + properties = Properties(PUBREC >> 4) + props, props_len = properties.unpack( + self._in_packet['packet'][3:]) + self._easy_log(MQTT_LOG_DEBUG, "Received PUBREC (Mid: %d)", mid) + + with self._out_message_mutex: + if mid in self._out_messages: + msg = self._out_messages[mid] + msg.state = mqtt_ms_wait_for_pubcomp + msg.timestamp = time_func() + return self._send_pubrel(mid) + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_unsuback(self) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 4: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + if self._protocol == MQTTv5: + packet = self._in_packet['packet'][2:] + properties = Properties(UNSUBACK >> 4) + props, props_len = properties.unpack(packet) + reasoncodes_list = [ + ReasonCode(UNSUBACK >> 4, identifier=c) + for c in packet[props_len:] + ] + else: + reasoncodes_list = [] + properties = Properties(UNSUBACK >> 4) + + self._easy_log(MQTT_LOG_DEBUG, "Received UNSUBACK (Mid: %d)", mid) + with self._callback_mutex: + on_unsubscribe = self.on_unsubscribe + + if on_unsubscribe: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt5, on_unsubscribe) + + reasoncodes: ReasonCode | list[ReasonCode] = reasoncodes_list + if len(reasoncodes_list) == 1: + reasoncodes = reasoncodes_list[0] + + on_unsubscribe( + self, self._userdata, mid, properties, reasoncodes) + else: + on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt3, on_unsubscribe) + + on_unsubscribe(self, self._userdata, mid) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_unsubscribe = cast(CallbackOnUnsubscribe_v2, on_unsubscribe) + + if properties is None: + properties = Properties(PacketTypes.CONNACK) + + on_unsubscribe( + self, + self._userdata, + mid, + reasoncodes_list, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_unsubscribe: %s', err) + if not self.suppress_exceptions: + raise + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _do_on_disconnect( + self, + packet_from_broker: bool, + v1_rc: MQTTErrorCode, + reason: ReasonCode | None = None, + properties: Properties | None = None, + ) -> None: + with self._callback_mutex: + on_disconnect = self.on_disconnect + + if on_disconnect: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + if self._protocol == MQTTv5: + on_disconnect = cast(CallbackOnDisconnect_v1_mqtt5, on_disconnect) + + if packet_from_broker: + on_disconnect(self, self._userdata, reason, properties) + else: + on_disconnect(self, self._userdata, v1_rc, None) + else: + on_disconnect = cast(CallbackOnDisconnect_v1_mqtt3, on_disconnect) + + on_disconnect(self, self._userdata, v1_rc) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_disconnect = cast(CallbackOnDisconnect_v2, on_disconnect) + + disconnect_flags = DisconnectFlags( + is_disconnect_packet_from_server=packet_from_broker + ) + + if reason is None: + reason = convert_disconnect_error_code_to_reason_code(v1_rc) + + if properties is None: + properties = Properties(PacketTypes.DISCONNECT) + + on_disconnect( + self, + self._userdata, + disconnect_flags, + reason, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_disconnect: %s', err) + if not self.suppress_exceptions: + raise + + def _do_on_publish(self, mid: int, reason_code: ReasonCode, properties: Properties) -> MQTTErrorCode: + with self._callback_mutex: + on_publish = self.on_publish + + if on_publish: + with self._in_callback_mutex: + try: + if self._callback_api_version == CallbackAPIVersion.VERSION1: + on_publish = cast(CallbackOnPublish_v1, on_publish) + + on_publish(self, self._userdata, mid) + elif self._callback_api_version == CallbackAPIVersion.VERSION2: + on_publish = cast(CallbackOnPublish_v2, on_publish) + + on_publish( + self, + self._userdata, + mid, + reason_code, + properties, + ) + else: + raise RuntimeError("Unsupported callback API version") + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err) + if not self.suppress_exceptions: + raise + + msg = self._out_messages.pop(mid) + msg.info._set_as_published() + if msg.qos > 0: + self._inflight_messages -= 1 + if self._max_inflight_messages > 0: + rc = self._update_inflight() + if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: + return rc + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_pubackcomp( + self, cmd: Literal['PUBACK'] | Literal['PUBCOMP'] + ) -> MQTTErrorCode: + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] < 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + elif self._in_packet['remaining_length'] != 2: + return MQTTErrorCode.MQTT_ERR_PROTOCOL + + packet_type_enum = PUBACK if cmd == "PUBACK" else PUBCOMP + packet_type = packet_type_enum.value >> 4 + mid, = struct.unpack("!H", self._in_packet['packet'][:2]) + reasonCode = ReasonCode(packet_type) + properties = Properties(packet_type) + if self._protocol == MQTTv5: + if self._in_packet['remaining_length'] > 2: + reasonCode.unpack(self._in_packet['packet'][2:]) + if self._in_packet['remaining_length'] > 3: + props, props_len = properties.unpack( + self._in_packet['packet'][3:]) + self._easy_log(MQTT_LOG_DEBUG, "Received %s (Mid: %d)", cmd, mid) + + with self._out_message_mutex: + if mid in self._out_messages: + # Only inform the client the message has been sent once. + rc = self._do_on_publish(mid, reasonCode, properties) + return rc + + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def _handle_on_message(self, message: MQTTMessage) -> None: + + try: + topic = message.topic + except UnicodeDecodeError: + topic = None + + on_message_callbacks = [] + with self._callback_mutex: + if topic is not None: + on_message_callbacks = list(self._on_message_filtered.iter_match(message.topic)) + + if len(on_message_callbacks) == 0: + on_message = self.on_message + else: + on_message = None + + for callback in on_message_callbacks: + with self._in_callback_mutex: + try: + callback(self, self._userdata, message) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, + 'Caught exception in user defined callback function %s: %s', + callback.__name__, + err + ) + if not self.suppress_exceptions: + raise + + if on_message: + with self._in_callback_mutex: + try: + on_message(self, self._userdata, message) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_message: %s', err) + if not self.suppress_exceptions: + raise + + + def _handle_on_connect_fail(self) -> None: + with self._callback_mutex: + on_connect_fail = self.on_connect_fail + + if on_connect_fail: + with self._in_callback_mutex: + try: + on_connect_fail(self, self._userdata) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_connect_fail: %s', err) + + def _thread_main(self) -> None: + try: + self.loop_forever(retry_first_connection=True) + finally: + self._thread = None + + def _reconnect_wait(self) -> None: + # See reconnect_delay_set for details + now = time_func() + with self._reconnect_delay_mutex: + if self._reconnect_delay is None: + self._reconnect_delay = self._reconnect_min_delay + else: + self._reconnect_delay = min( + self._reconnect_delay * 2, + self._reconnect_max_delay, + ) + + target_time = now + self._reconnect_delay + + remaining = target_time - now + while (self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) + and not self._thread_terminate + and remaining > 0): + + time.sleep(min(remaining, 1)) + remaining = target_time - time_func() + + @staticmethod + def _proxy_is_valid(p) -> bool: # type: ignore[no-untyped-def] + def check(t, a) -> bool: # type: ignore[no-untyped-def] + return (socks is not None and + t in {socks.HTTP, socks.SOCKS4, socks.SOCKS5} and a) + + if isinstance(p, dict): + return check(p.get("proxy_type"), p.get("proxy_addr")) + elif isinstance(p, (list, tuple)): + return len(p) == 6 and check(p[0], p[1]) + else: + return False + + def _get_proxy(self) -> dict[str, Any] | None: + if socks is None: + return None + + # First, check if the user explicitly passed us a proxy to use + if self._proxy_is_valid(self._proxy): + return self._proxy + + # Next, check for an mqtt_proxy environment variable as long as the host + # we're trying to connect to isn't listed under the no_proxy environment + # variable (matches built-in module urllib's behavior) + if not (hasattr(urllib.request, "proxy_bypass") and + urllib.request.proxy_bypass(self._host)): + env_proxies = urllib.request.getproxies() + if "mqtt" in env_proxies: + parts = urllib.parse.urlparse(env_proxies["mqtt"]) + if parts.scheme == "http": + proxy = { + "proxy_type": socks.HTTP, + "proxy_addr": parts.hostname, + "proxy_port": parts.port + } + return proxy + elif parts.scheme == "socks": + proxy = { + "proxy_type": socks.SOCKS5, + "proxy_addr": parts.hostname, + "proxy_port": parts.port + } + return proxy + + # Finally, check if the user has monkeypatched the PySocks library with + # a default proxy + socks_default = socks.get_default_proxy() + if self._proxy_is_valid(socks_default): + proxy_keys = ("proxy_type", "proxy_addr", "proxy_port", + "proxy_rdns", "proxy_username", "proxy_password") + return dict(zip(proxy_keys, socks_default)) + + # If we didn't find a proxy through any of the above methods, return + # None to indicate that the connection should be handled normally + return None + + def _create_socket(self) -> SocketLike: + if self._transport == "unix": + sock = self._create_unix_socket_connection() + else: + sock = self._create_socket_connection() + + if self._ssl: + sock = self._ssl_wrap_socket(sock) + + if self._transport == "websockets": + sock.settimeout(self._keepalive) + return _WebsocketWrapper( + socket=sock, + host=self._host, + port=self._port, + is_ssl=self._ssl, + path=self._websocket_path, + extra_headers=self._websocket_extra_headers, + ) + + return sock + + def _create_unix_socket_connection(self) -> _socket.socket: + unix_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + unix_socket.connect(self._host) + return unix_socket + + def _create_socket_connection(self) -> _socket.socket: + proxy = self._get_proxy() + addr = (self._host, self._port) + source = (self._bind_address, self._bind_port) + + if proxy: + return socks.create_connection(addr, timeout=self._connect_timeout, source_address=source, **proxy) + else: + return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source) + + def _ssl_wrap_socket(self, tcp_sock: _socket.socket) -> ssl.SSLSocket: + if self._ssl_context is None: + raise ValueError( + "Impossible condition. _ssl_context should never be None if _ssl is True" + ) + + verify_host = not self._tls_insecure + try: + # Try with server_hostname, even it's not supported in certain scenarios + ssl_sock = self._ssl_context.wrap_socket( + tcp_sock, + server_hostname=self._host, + do_handshake_on_connect=False, + ) + except ssl.CertificateError: + # CertificateError is derived from ValueError + raise + except ValueError: + # Python version requires SNI in order to handle server_hostname, but SNI is not available + ssl_sock = self._ssl_context.wrap_socket( + tcp_sock, + do_handshake_on_connect=False, + ) + else: + # If SSL context has already checked hostname, then don't need to do it again + if getattr(self._ssl_context, 'check_hostname', False): # type: ignore + verify_host = False + + ssl_sock.settimeout(self._keepalive) + ssl_sock.do_handshake() + + if verify_host: + # TODO: this type error is a true error: + # error: Module has no attribute "match_hostname" [attr-defined] + # Python 3.12 no longer have this method. + ssl.match_hostname(ssl_sock.getpeercert(), self._host) # type: ignore + + return ssl_sock + +class _WebsocketWrapper: + OPCODE_CONTINUATION = 0x0 + OPCODE_TEXT = 0x1 + OPCODE_BINARY = 0x2 + OPCODE_CONNCLOSE = 0x8 + OPCODE_PING = 0x9 + OPCODE_PONG = 0xa + + def __init__( + self, + socket: socket.socket | ssl.SSLSocket, + host: str, + port: int, + is_ssl: bool, + path: str, + extra_headers: WebSocketHeaders | None, + ): + self.connected = False + + self._ssl = is_ssl + self._host = host + self._port = port + self._socket = socket + self._path = path + + self._sendbuffer = bytearray() + self._readbuffer = bytearray() + + self._requested_size = 0 + self._payload_head = 0 + self._readbuffer_head = 0 + + self._do_handshake(extra_headers) + + def __del__(self) -> None: + self._sendbuffer = bytearray() + self._readbuffer = bytearray() + + def _do_handshake(self, extra_headers: WebSocketHeaders | None) -> None: + + sec_websocket_key = uuid.uuid4().bytes + sec_websocket_key = base64.b64encode(sec_websocket_key) + + if self._ssl: + default_port = 443 + http_schema = "https" + else: + default_port = 80 + http_schema = "http" + + if default_port == self._port: + host_port = f"{self._host}" + else: + host_port = f"{self._host}:{self._port}" + + websocket_headers = { + "Host": host_port, + "Upgrade": "websocket", + "Connection": "Upgrade", + "Origin": f"{http_schema}://{host_port}", + "Sec-WebSocket-Key": sec_websocket_key.decode("utf8"), + "Sec-Websocket-Version": "13", + "Sec-Websocket-Protocol": "mqtt", + } + + # This is checked in ws_set_options so it will either be None, a + # dictionary, or a callable + if isinstance(extra_headers, dict): + websocket_headers.update(extra_headers) + elif callable(extra_headers): + websocket_headers = extra_headers(websocket_headers) + + header = "\r\n".join([ + f"GET {self._path} HTTP/1.1", + "\r\n".join(f"{i}: {j}" for i, j in websocket_headers.items()), + "\r\n", + ]).encode("utf8") + + self._socket.send(header) + + has_secret = False + has_upgrade = False + + while True: + # read HTTP response header as lines + try: + byte = self._socket.recv(1) + except ConnectionResetError: + byte = b"" + + self._readbuffer.extend(byte) + + # line end + if byte == b"\n": + if len(self._readbuffer) > 2: + # check upgrade + if b"connection" in str(self._readbuffer).lower().encode('utf-8'): + if b"upgrade" not in str(self._readbuffer).lower().encode('utf-8'): + raise WebsocketConnectionError( + "WebSocket handshake error, connection not upgraded") + else: + has_upgrade = True + + # check key hash + if b"sec-websocket-accept" in str(self._readbuffer).lower().encode('utf-8'): + GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + server_hash_str = self._readbuffer.decode( + 'utf-8').split(": ", 1)[1] + server_hash = server_hash_str.strip().encode('utf-8') + + client_hash_key = sec_websocket_key.decode('utf-8') + GUID + # Use of SHA-1 is OK here; it's according to the Websocket spec. + client_hash_digest = hashlib.sha1(client_hash_key.encode('utf-8')) # noqa: S324 + client_hash = base64.b64encode(client_hash_digest.digest()) + + if server_hash != client_hash: + raise WebsocketConnectionError( + "WebSocket handshake error, invalid secret key") + else: + has_secret = True + else: + # ending linebreak + break + + # reset linebuffer + self._readbuffer = bytearray() + + # connection reset + elif not byte: + raise WebsocketConnectionError("WebSocket handshake error") + + if not has_upgrade or not has_secret: + raise WebsocketConnectionError("WebSocket handshake error") + + self._readbuffer = bytearray() + self.connected = True + + def _create_frame( + self, opcode: int, data: bytearray, do_masking: int = 1 + ) -> bytearray: + header = bytearray() + length = len(data) + + mask_key = bytearray(os.urandom(4)) + mask_flag = do_masking + + # 1 << 7 is the final flag, we don't send continuated data + header.append(1 << 7 | opcode) + + if length < 126: + header.append(mask_flag << 7 | length) + + elif length < 65536: + header.append(mask_flag << 7 | 126) + header += struct.pack("!H", length) + + elif length < 0x8000000000000001: + header.append(mask_flag << 7 | 127) + header += struct.pack("!Q", length) + + else: + raise ValueError("Maximum payload size is 2^63") + + if mask_flag == 1: + for index in range(length): + data[index] ^= mask_key[index % 4] + data = mask_key + data + + return header + data + + def _buffered_read(self, length: int) -> bytearray: + + # try to recv and store needed bytes + wanted_bytes = length - (len(self._readbuffer) - self._readbuffer_head) + if wanted_bytes > 0: + + data = self._socket.recv(wanted_bytes) + + if not data: + raise ConnectionAbortedError + else: + self._readbuffer.extend(data) + + if len(data) < wanted_bytes: + raise BlockingIOError + + self._readbuffer_head += length + return self._readbuffer[self._readbuffer_head - length:self._readbuffer_head] + + def _recv_impl(self, length: int) -> bytes: + + # try to decode websocket payload part from data + try: + + self._readbuffer_head = 0 + + result = b"" + + chunk_startindex = self._payload_head + chunk_endindex = self._payload_head + length + + header1 = self._buffered_read(1) + header2 = self._buffered_read(1) + + opcode = (header1[0] & 0x0f) + maskbit = (header2[0] & 0x80) == 0x80 + lengthbits = (header2[0] & 0x7f) + payload_length = lengthbits + mask_key = None + + # read length + if lengthbits == 0x7e: + + value = self._buffered_read(2) + payload_length, = struct.unpack("!H", value) + + elif lengthbits == 0x7f: + + value = self._buffered_read(8) + payload_length, = struct.unpack("!Q", value) + + # read mask + if maskbit: + mask_key = self._buffered_read(4) + + # if frame payload is shorter than the requested data, read only the possible part + readindex = chunk_endindex + if payload_length < readindex: + readindex = payload_length + + if readindex > 0: + # get payload chunk + payload = self._buffered_read(readindex) + + # unmask only the needed part + if mask_key is not None: + for index in range(chunk_startindex, readindex): + payload[index] ^= mask_key[index % 4] + + result = payload[chunk_startindex:readindex] + self._payload_head = readindex + else: + payload = bytearray() + + # check if full frame arrived and reset readbuffer and payloadhead if needed + if readindex == payload_length: + self._readbuffer = bytearray() + self._payload_head = 0 + + # respond to non-binary opcodes, their arrival is not guaranteed because of non-blocking sockets + if opcode == _WebsocketWrapper.OPCODE_CONNCLOSE: + frame = self._create_frame( + _WebsocketWrapper.OPCODE_CONNCLOSE, payload, 0) + self._socket.send(frame) + + if opcode == _WebsocketWrapper.OPCODE_PING: + frame = self._create_frame( + _WebsocketWrapper.OPCODE_PONG, payload, 0) + self._socket.send(frame) + + # This isn't *proper* handling of continuation frames, but given + # that we only support binary frames, it is *probably* good enough. + if (opcode == _WebsocketWrapper.OPCODE_BINARY or opcode == _WebsocketWrapper.OPCODE_CONTINUATION) \ + and payload_length > 0: + return result + else: + raise BlockingIOError + + except ConnectionError: + self.connected = False + return b'' + + def _send_impl(self, data: bytes) -> int: + + # if previous frame was sent successfully + if len(self._sendbuffer) == 0: + # create websocket frame + frame = self._create_frame( + _WebsocketWrapper.OPCODE_BINARY, bytearray(data)) + self._sendbuffer.extend(frame) + self._requested_size = len(data) + + # try to write out as much as possible + length = self._socket.send(self._sendbuffer) + + self._sendbuffer = self._sendbuffer[length:] + + if len(self._sendbuffer) == 0: + # buffer sent out completely, return with payload's size + return self._requested_size + else: + # couldn't send whole data, request the same data again with 0 as sent length + return 0 + + def recv(self, length: int) -> bytes: + return self._recv_impl(length) + + def read(self, length: int) -> bytes: + return self._recv_impl(length) + + def send(self, data: bytes) -> int: + return self._send_impl(data) + + def write(self, data: bytes) -> int: + return self._send_impl(data) + + def close(self) -> None: + self._socket.close() + + def fileno(self) -> int: + return self._socket.fileno() + + def pending(self) -> int: + # Fix for bug #131: a SSL socket may still have data available + # for reading without select() being aware of it. + if self._ssl: + return self._socket.pending() # type: ignore[union-attr] + else: + # normal socket rely only on select() + return 0 + + def setblocking(self, flag: bool) -> None: + self._socket.setblocking(flag) diff --git a/sbapp/pmqtt/enums.py b/sbapp/pmqtt/enums.py new file mode 100644 index 0000000..5428769 --- /dev/null +++ b/sbapp/pmqtt/enums.py @@ -0,0 +1,113 @@ +import enum + + +class MQTTErrorCode(enum.IntEnum): + MQTT_ERR_AGAIN = -1 + MQTT_ERR_SUCCESS = 0 + MQTT_ERR_NOMEM = 1 + MQTT_ERR_PROTOCOL = 2 + MQTT_ERR_INVAL = 3 + MQTT_ERR_NO_CONN = 4 + MQTT_ERR_CONN_REFUSED = 5 + MQTT_ERR_NOT_FOUND = 6 + MQTT_ERR_CONN_LOST = 7 + MQTT_ERR_TLS = 8 + MQTT_ERR_PAYLOAD_SIZE = 9 + MQTT_ERR_NOT_SUPPORTED = 10 + MQTT_ERR_AUTH = 11 + MQTT_ERR_ACL_DENIED = 12 + MQTT_ERR_UNKNOWN = 13 + MQTT_ERR_ERRNO = 14 + MQTT_ERR_QUEUE_SIZE = 15 + MQTT_ERR_KEEPALIVE = 16 + + +class MQTTProtocolVersion(enum.IntEnum): + MQTTv31 = 3 + MQTTv311 = 4 + MQTTv5 = 5 + + +class CallbackAPIVersion(enum.Enum): + """Defined the arguments passed to all user-callback. + + See each callbacks for details: `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`, + `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`, + `on_socket_register_write`, `on_socket_unregister_write` + """ + VERSION1 = 1 + """The version used with paho-mqtt 1.x before introducing CallbackAPIVersion. + + This version had different arguments depending if MQTTv5 or MQTTv3 was used. `Properties` & `ReasonCode` were missing + on some callback (apply only to MQTTv5). + + This version is deprecated and will be removed in version 3.0. + """ + VERSION2 = 2 + """ This version fix some of the shortcoming of previous version. + + Callback have the same signature if using MQTTv5 or MQTTv3. `ReasonCode` are used in MQTTv3. + """ + + +class MessageType(enum.IntEnum): + CONNECT = 0x10 + CONNACK = 0x20 + PUBLISH = 0x30 + PUBACK = 0x40 + PUBREC = 0x50 + PUBREL = 0x60 + PUBCOMP = 0x70 + SUBSCRIBE = 0x80 + SUBACK = 0x90 + UNSUBSCRIBE = 0xA0 + UNSUBACK = 0xB0 + PINGREQ = 0xC0 + PINGRESP = 0xD0 + DISCONNECT = 0xE0 + AUTH = 0xF0 + + +class LogLevel(enum.IntEnum): + MQTT_LOG_INFO = 0x01 + MQTT_LOG_NOTICE = 0x02 + MQTT_LOG_WARNING = 0x04 + MQTT_LOG_ERR = 0x08 + MQTT_LOG_DEBUG = 0x10 + + +class ConnackCode(enum.IntEnum): + CONNACK_ACCEPTED = 0 + CONNACK_REFUSED_PROTOCOL_VERSION = 1 + CONNACK_REFUSED_IDENTIFIER_REJECTED = 2 + CONNACK_REFUSED_SERVER_UNAVAILABLE = 3 + CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4 + CONNACK_REFUSED_NOT_AUTHORIZED = 5 + + +class _ConnectionState(enum.Enum): + MQTT_CS_NEW = enum.auto() + MQTT_CS_CONNECT_ASYNC = enum.auto() + MQTT_CS_CONNECTING = enum.auto() + MQTT_CS_CONNECTED = enum.auto() + MQTT_CS_CONNECTION_LOST = enum.auto() + MQTT_CS_DISCONNECTING = enum.auto() + MQTT_CS_DISCONNECTED = enum.auto() + + +class MessageState(enum.IntEnum): + MQTT_MS_INVALID = 0 + MQTT_MS_PUBLISH = 1 + MQTT_MS_WAIT_FOR_PUBACK = 2 + MQTT_MS_WAIT_FOR_PUBREC = 3 + MQTT_MS_RESEND_PUBREL = 4 + MQTT_MS_WAIT_FOR_PUBREL = 5 + MQTT_MS_RESEND_PUBCOMP = 6 + MQTT_MS_WAIT_FOR_PUBCOMP = 7 + MQTT_MS_SEND_PUBREC = 8 + MQTT_MS_QUEUED = 9 + + +class PahoClientMode(enum.IntEnum): + MQTT_CLIENT = 0 + MQTT_BRIDGE = 1 diff --git a/sbapp/pmqtt/matcher.py b/sbapp/pmqtt/matcher.py new file mode 100644 index 0000000..b73c13a --- /dev/null +++ b/sbapp/pmqtt/matcher.py @@ -0,0 +1,78 @@ +class MQTTMatcher: + """Intended to manage topic filters including wildcards. + + Internally, MQTTMatcher use a prefix tree (trie) to store + values associated with filters, and has an iter_match() + method to iterate efficiently over all filters that match + some topic name.""" + + class Node: + __slots__ = '_children', '_content' + + def __init__(self): + self._children = {} + self._content = None + + def __init__(self): + self._root = self.Node() + + def __setitem__(self, key, value): + """Add a topic filter :key to the prefix tree + and associate it to :value""" + node = self._root + for sym in key.split('/'): + node = node._children.setdefault(sym, self.Node()) + node._content = value + + def __getitem__(self, key): + """Retrieve the value associated with some topic filter :key""" + try: + node = self._root + for sym in key.split('/'): + node = node._children[sym] + if node._content is None: + raise KeyError(key) + return node._content + except KeyError as ke: + raise KeyError(key) from ke + + def __delitem__(self, key): + """Delete the value associated with some topic filter :key""" + lst = [] + try: + parent, node = None, self._root + for k in key.split('/'): + parent, node = node, node._children[k] + lst.append((parent, k, node)) + # TODO + node._content = None + except KeyError as ke: + raise KeyError(key) from ke + else: # cleanup + for parent, k, node in reversed(lst): + if node._children or node._content is not None: + break + del parent._children[k] + + def iter_match(self, topic): + """Return an iterator on all values associated with filters + that match the :topic""" + lst = topic.split('/') + normal = not topic.startswith('$') + def rec(node, i=0): + if i == len(lst): + if node._content is not None: + yield node._content + else: + part = lst[i] + if part in node._children: + for content in rec(node._children[part], i + 1): + yield content + if '+' in node._children and (normal or i > 0): + for content in rec(node._children['+'], i + 1): + yield content + if '#' in node._children and (normal or i > 0): + content = node._children['#']._content + if content is not None: + yield content + return rec(self._root) diff --git a/sbapp/pmqtt/packettypes.py b/sbapp/pmqtt/packettypes.py new file mode 100644 index 0000000..d205149 --- /dev/null +++ b/sbapp/pmqtt/packettypes.py @@ -0,0 +1,43 @@ +""" +******************************************************************* + Copyright (c) 2017, 2019 IBM Corp. + + All rights reserved. This program and the accompanying materials + are made available under the terms of the Eclipse Public License v2.0 + and Eclipse Distribution License v1.0 which accompany this distribution. + + The Eclipse Public License is available at + http://www.eclipse.org/legal/epl-v20.html + and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + + Contributors: + Ian Craggs - initial implementation and/or documentation +******************************************************************* +""" + + +class PacketTypes: + + """ + Packet types class. Includes the AUTH packet for MQTT v5.0. + + Holds constants for each packet type such as PacketTypes.PUBLISH + and packet name strings: PacketTypes.Names[PacketTypes.PUBLISH]. + + """ + + indexes = range(1, 16) + + # Packet types + CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, \ + PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, \ + PINGREQ, PINGRESP, DISCONNECT, AUTH = indexes + + # Dummy packet type for properties use - will delay only applies to will + WILLMESSAGE = 99 + + Names = ( "reserved", \ + "Connect", "Connack", "Publish", "Puback", "Pubrec", "Pubrel", \ + "Pubcomp", "Subscribe", "Suback", "Unsubscribe", "Unsuback", \ + "Pingreq", "Pingresp", "Disconnect", "Auth") diff --git a/sbapp/pmqtt/properties.py b/sbapp/pmqtt/properties.py new file mode 100644 index 0000000..f307b86 --- /dev/null +++ b/sbapp/pmqtt/properties.py @@ -0,0 +1,421 @@ +# ******************************************************************* +# Copyright (c) 2017, 2019 IBM Corp. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Ian Craggs - initial implementation and/or documentation +# ******************************************************************* + +import struct + +from .packettypes import PacketTypes + + +class MQTTException(Exception): + pass + + +class MalformedPacket(MQTTException): + pass + + +def writeInt16(length): + # serialize a 16 bit integer to network format + return bytearray(struct.pack("!H", length)) + + +def readInt16(buf): + # deserialize a 16 bit integer from network format + return struct.unpack("!H", buf[:2])[0] + + +def writeInt32(length): + # serialize a 32 bit integer to network format + return bytearray(struct.pack("!L", length)) + + +def readInt32(buf): + # deserialize a 32 bit integer from network format + return struct.unpack("!L", buf[:4])[0] + + +def writeUTF(data): + # data could be a string, or bytes. If string, encode into bytes with utf-8 + if not isinstance(data, bytes): + data = bytes(data, "utf-8") + return writeInt16(len(data)) + data + + +def readUTF(buffer, maxlen): + if maxlen >= 2: + length = readInt16(buffer) + else: + raise MalformedPacket("Not enough data to read string length") + maxlen -= 2 + if length > maxlen: + raise MalformedPacket("Length delimited string too long") + buf = buffer[2:2+length].decode("utf-8") + # look for chars which are invalid for MQTT + for c in buf: # look for D800-DFFF in the UTF string + ord_c = ord(c) + if ord_c >= 0xD800 and ord_c <= 0xDFFF: + raise MalformedPacket("[MQTT-1.5.4-1] D800-DFFF found in UTF-8 data") + if ord_c == 0x00: # look for null in the UTF string + raise MalformedPacket("[MQTT-1.5.4-2] Null found in UTF-8 data") + if ord_c == 0xFEFF: + raise MalformedPacket("[MQTT-1.5.4-3] U+FEFF in UTF-8 data") + return buf, length+2 + + +def writeBytes(buffer): + return writeInt16(len(buffer)) + buffer + + +def readBytes(buffer): + length = readInt16(buffer) + return buffer[2:2+length], length+2 + + +class VariableByteIntegers: # Variable Byte Integer + """ + MQTT variable byte integer helper class. Used + in several places in MQTT v5.0 properties. + + """ + + @staticmethod + def encode(x): + """ + Convert an integer 0 <= x <= 268435455 into multi-byte format. + Returns the buffer converted from the integer. + """ + if not 0 <= x <= 268435455: + raise ValueError(f"Value {x!r} must be in range 0-268435455") + buffer = b'' + while 1: + digit = x % 128 + x //= 128 + if x > 0: + digit |= 0x80 + buffer += bytes([digit]) + if x == 0: + break + return buffer + + @staticmethod + def decode(buffer): + """ + Get the value of a multi-byte integer from a buffer + Return the value, and the number of bytes used. + + [MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value + """ + multiplier = 1 + value = 0 + bytes = 0 + while 1: + bytes += 1 + digit = buffer[0] + buffer = buffer[1:] + value += (digit & 127) * multiplier + if digit & 128 == 0: + break + multiplier *= 128 + return (value, bytes) + + +class Properties: + """MQTT v5.0 properties class. + + See Properties.names for a list of accepted property names along with their numeric values. + + See Properties.properties for the data type of each property. + + Example of use:: + + publish_properties = Properties(PacketTypes.PUBLISH) + publish_properties.UserProperty = ("a", "2") + publish_properties.UserProperty = ("c", "3") + + First the object is created with packet type as argument, no properties will be present at + this point. Then properties are added as attributes, the name of which is the string property + name without the spaces. + + """ + + def __init__(self, packetType): + self.packetType = packetType + self.types = ["Byte", "Two Byte Integer", "Four Byte Integer", "Variable Byte Integer", + "Binary Data", "UTF-8 Encoded String", "UTF-8 String Pair"] + + self.names = { + "Payload Format Indicator": 1, + "Message Expiry Interval": 2, + "Content Type": 3, + "Response Topic": 8, + "Correlation Data": 9, + "Subscription Identifier": 11, + "Session Expiry Interval": 17, + "Assigned Client Identifier": 18, + "Server Keep Alive": 19, + "Authentication Method": 21, + "Authentication Data": 22, + "Request Problem Information": 23, + "Will Delay Interval": 24, + "Request Response Information": 25, + "Response Information": 26, + "Server Reference": 28, + "Reason String": 31, + "Receive Maximum": 33, + "Topic Alias Maximum": 34, + "Topic Alias": 35, + "Maximum QoS": 36, + "Retain Available": 37, + "User Property": 38, + "Maximum Packet Size": 39, + "Wildcard Subscription Available": 40, + "Subscription Identifier Available": 41, + "Shared Subscription Available": 42 + } + + self.properties = { + # id: type, packets + # payload format indicator + 1: (self.types.index("Byte"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 2: (self.types.index("Four Byte Integer"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 3: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 8: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 9: (self.types.index("Binary Data"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), + 11: (self.types.index("Variable Byte Integer"), + [PacketTypes.PUBLISH, PacketTypes.SUBSCRIBE]), + 17: (self.types.index("Four Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.DISCONNECT]), + 18: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), + 19: (self.types.index("Two Byte Integer"), [PacketTypes.CONNACK]), + 21: (self.types.index("UTF-8 Encoded String"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), + 22: (self.types.index("Binary Data"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), + 23: (self.types.index("Byte"), + [PacketTypes.CONNECT]), + 24: (self.types.index("Four Byte Integer"), [PacketTypes.WILLMESSAGE]), + 25: (self.types.index("Byte"), [PacketTypes.CONNECT]), + 26: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), + 28: (self.types.index("UTF-8 Encoded String"), + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]), + 31: (self.types.index("UTF-8 Encoded String"), + [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, + PacketTypes.PUBREL, PacketTypes.PUBCOMP, PacketTypes.SUBACK, + PacketTypes.UNSUBACK, PacketTypes.DISCONNECT, PacketTypes.AUTH]), + 33: (self.types.index("Two Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK]), + 34: (self.types.index("Two Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK]), + 35: (self.types.index("Two Byte Integer"), [PacketTypes.PUBLISH]), + 36: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 37: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 38: (self.types.index("UTF-8 String Pair"), + [PacketTypes.CONNECT, PacketTypes.CONNACK, + PacketTypes.PUBLISH, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, + PacketTypes.SUBSCRIBE, PacketTypes.SUBACK, + PacketTypes.UNSUBSCRIBE, PacketTypes.UNSUBACK, + PacketTypes.DISCONNECT, PacketTypes.AUTH, PacketTypes.WILLMESSAGE]), + 39: (self.types.index("Four Byte Integer"), + [PacketTypes.CONNECT, PacketTypes.CONNACK]), + 40: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 41: (self.types.index("Byte"), [PacketTypes.CONNACK]), + 42: (self.types.index("Byte"), [PacketTypes.CONNACK]), + } + + def allowsMultiple(self, compressedName): + return self.getIdentFromName(compressedName) in [11, 38] + + def getIdentFromName(self, compressedName): + # return the identifier corresponding to the property name + result = -1 + for name in self.names.keys(): + if compressedName == name.replace(' ', ''): + result = self.names[name] + break + return result + + def __setattr__(self, name, value): + name = name.replace(' ', '') + privateVars = ["packetType", "types", "names", "properties"] + if name in privateVars: + object.__setattr__(self, name, value) + else: + # the name could have spaces in, or not. Remove spaces before assignment + if name not in [aname.replace(' ', '') for aname in self.names.keys()]: + raise MQTTException( + f"Property name must be one of {self.names.keys()}") + # check that this attribute applies to the packet type + if self.packetType not in self.properties[self.getIdentFromName(name)][1]: + raise MQTTException(f"Property {name} does not apply to packet type {PacketTypes.Names[self.packetType]}") + + # Check for forbidden values + if not isinstance(value, list): + if name in ["ReceiveMaximum", "TopicAlias"] \ + and (value < 1 or value > 65535): + + raise MQTTException(f"{name} property value must be in the range 1-65535") + elif name in ["TopicAliasMaximum"] \ + and (value < 0 or value > 65535): + + raise MQTTException(f"{name} property value must be in the range 0-65535") + elif name in ["MaximumPacketSize", "SubscriptionIdentifier"] \ + and (value < 1 or value > 268435455): + + raise MQTTException(f"{name} property value must be in the range 1-268435455") + elif name in ["RequestResponseInformation", "RequestProblemInformation", "PayloadFormatIndicator"] \ + and (value != 0 and value != 1): + + raise MQTTException( + f"{name} property value must be 0 or 1") + + if self.allowsMultiple(name): + if not isinstance(value, list): + value = [value] + if hasattr(self, name): + value = object.__getattribute__(self, name) + value + object.__setattr__(self, name, value) + + def __str__(self): + buffer = "[" + first = True + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + if not first: + buffer += ", " + buffer += f"{compressedName} : {getattr(self, compressedName)}" + first = False + buffer += "]" + return buffer + + def json(self): + data = {} + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + val = getattr(self, compressedName) + if compressedName == 'CorrelationData' and isinstance(val, bytes): + data[compressedName] = val.hex() + else: + data[compressedName] = val + return data + + def isEmpty(self): + rc = True + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + rc = False + break + return rc + + def clear(self): + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + delattr(self, compressedName) + + def writeProperty(self, identifier, type, value): + buffer = b"" + buffer += VariableByteIntegers.encode(identifier) # identifier + if type == self.types.index("Byte"): # value + buffer += bytes([value]) + elif type == self.types.index("Two Byte Integer"): + buffer += writeInt16(value) + elif type == self.types.index("Four Byte Integer"): + buffer += writeInt32(value) + elif type == self.types.index("Variable Byte Integer"): + buffer += VariableByteIntegers.encode(value) + elif type == self.types.index("Binary Data"): + buffer += writeBytes(value) + elif type == self.types.index("UTF-8 Encoded String"): + buffer += writeUTF(value) + elif type == self.types.index("UTF-8 String Pair"): + buffer += writeUTF(value[0]) + writeUTF(value[1]) + return buffer + + def pack(self): + # serialize properties into buffer for sending over network + buffer = b"" + for name in self.names.keys(): + compressedName = name.replace(' ', '') + if hasattr(self, compressedName): + identifier = self.getIdentFromName(compressedName) + attr_type = self.properties[identifier][0] + if self.allowsMultiple(compressedName): + for prop in getattr(self, compressedName): + buffer += self.writeProperty(identifier, + attr_type, prop) + else: + buffer += self.writeProperty(identifier, attr_type, + getattr(self, compressedName)) + return VariableByteIntegers.encode(len(buffer)) + buffer + + def readProperty(self, buffer, type, propslen): + if type == self.types.index("Byte"): + value = buffer[0] + valuelen = 1 + elif type == self.types.index("Two Byte Integer"): + value = readInt16(buffer) + valuelen = 2 + elif type == self.types.index("Four Byte Integer"): + value = readInt32(buffer) + valuelen = 4 + elif type == self.types.index("Variable Byte Integer"): + value, valuelen = VariableByteIntegers.decode(buffer) + elif type == self.types.index("Binary Data"): + value, valuelen = readBytes(buffer) + elif type == self.types.index("UTF-8 Encoded String"): + value, valuelen = readUTF(buffer, propslen) + elif type == self.types.index("UTF-8 String Pair"): + value, valuelen = readUTF(buffer, propslen) + buffer = buffer[valuelen:] # strip the bytes used by the value + value1, valuelen1 = readUTF(buffer, propslen - valuelen) + value = (value, value1) + valuelen += valuelen1 + return value, valuelen + + def getNameFromIdent(self, identifier): + rc = None + for name in self.names: + if self.names[name] == identifier: + rc = name + return rc + + def unpack(self, buffer): + self.clear() + # deserialize properties into attributes from buffer received from network + propslen, VBIlen = VariableByteIntegers.decode(buffer) + buffer = buffer[VBIlen:] # strip the bytes used by the VBI + propslenleft = propslen + while propslenleft > 0: # properties length is 0 if there are none + identifier, VBIlen2 = VariableByteIntegers.decode( + buffer) # property identifier + buffer = buffer[VBIlen2:] # strip the bytes used by the VBI + propslenleft -= VBIlen2 + attr_type = self.properties[identifier][0] + value, valuelen = self.readProperty( + buffer, attr_type, propslenleft) + buffer = buffer[valuelen:] # strip the bytes used by the value + propslenleft -= valuelen + propname = self.getNameFromIdent(identifier) + compressedName = propname.replace(' ', '') + if not self.allowsMultiple(compressedName) and hasattr(self, compressedName): + raise MQTTException( + f"Property '{property}' must not exist more than once") + setattr(self, propname, value) + return self, propslen + VBIlen diff --git a/sbapp/pmqtt/publish.py b/sbapp/pmqtt/publish.py new file mode 100644 index 0000000..b8b9476 --- /dev/null +++ b/sbapp/pmqtt/publish.py @@ -0,0 +1,306 @@ +# Copyright (c) 2014 Roger Light +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Roger Light - initial API and implementation + +""" +This module provides some helper functions to allow straightforward publishing +of messages in a one-shot manner. In other words, they are useful for the +situation where you have a single/multiple messages you want to publish to a +broker, then disconnect and nothing else is required. +""" +from __future__ import annotations + +import collections +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any, List, Tuple, Union + +from .enums import CallbackAPIVersion, MQTTProtocolVersion +from .properties import Properties +from .reasoncodes import ReasonCode + +from .. import mqtt +from . import client as paho + +if TYPE_CHECKING: + try: + from typing import NotRequired, Required, TypedDict # type: ignore + except ImportError: + from typing_extensions import NotRequired, Required, TypedDict + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal # type: ignore + + + + class AuthParameter(TypedDict, total=False): + username: Required[str] + password: NotRequired[str] + + + class TLSParameter(TypedDict, total=False): + ca_certs: Required[str] + certfile: NotRequired[str] + keyfile: NotRequired[str] + tls_version: NotRequired[int] + ciphers: NotRequired[str] + insecure: NotRequired[bool] + + + class MessageDict(TypedDict, total=False): + topic: Required[str] + payload: NotRequired[paho.PayloadType] + qos: NotRequired[int] + retain: NotRequired[bool] + + MessageTuple = Tuple[str, paho.PayloadType, int, bool] + + MessagesList = List[Union[MessageDict, MessageTuple]] + + +def _do_publish(client: paho.Client): + """Internal function""" + + message = client._userdata.popleft() + + if isinstance(message, dict): + client.publish(**message) + elif isinstance(message, (tuple, list)): + client.publish(*message) + else: + raise TypeError('message must be a dict, tuple, or list') + + +def _on_connect(client: paho.Client, userdata: MessagesList, flags, reason_code, properties): + """Internal v5 callback""" + if reason_code == 0: + if len(userdata) > 0: + _do_publish(client) + else: + raise mqtt.MQTTException(paho.connack_string(reason_code)) + + +def _on_publish( + client: paho.Client, userdata: collections.deque[MessagesList], mid: int, reason_codes: ReasonCode, properties: Properties, +) -> None: + """Internal callback""" + #pylint: disable=unused-argument + + if len(userdata) == 0: + client.disconnect() + else: + _do_publish(client) + + +def multiple( + msgs: MessagesList, + hostname: str = "localhost", + port: int = 1883, + client_id: str = "", + keepalive: int = 60, + will: MessageDict | None = None, + auth: AuthParameter | None = None, + tls: TLSParameter | None = None, + protocol: MQTTProtocolVersion = paho.MQTTv311, + transport: Literal["tcp", "websockets"] = "tcp", + proxy_args: Any | None = None, +) -> None: + """Publish multiple messages to a broker, then disconnect cleanly. + + This function creates an MQTT client, connects to a broker and publishes a + list of messages. Once the messages have been delivered, it disconnects + cleanly from the broker. + + :param msgs: a list of messages to publish. Each message is either a dict or a + tuple. + + If a dict, only the topic must be present. Default values will be + used for any missing arguments. The dict must be of the form: + + msg = {'topic':"", 'payload':"", 'qos':, + 'retain':} + topic must be present and may not be empty. + If payload is "", None or not present then a zero length payload + will be published. + If qos is not present, the default of 0 is used. + If retain is not present, the default of False is used. + + If a tuple, then it must be of the form: + ("", "", qos, retain) + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + auth = {'username':"", 'password':""} + Username is required, password is optional and will default to None + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + Defaults to None, which indicates that TLS should not be used. + + :param str transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param proxy_args: a dictionary that will be given to the client. + """ + + if not isinstance(msgs, Iterable): + raise TypeError('msgs must be an iterable') + if len(msgs) == 0: + raise ValueError('msgs is empty') + + client = paho.Client( + CallbackAPIVersion.VERSION2, + client_id=client_id, + userdata=collections.deque(msgs), + protocol=protocol, + transport=transport, + ) + + client.enable_logger() + client.on_publish = _on_publish + client.on_connect = _on_connect # type: ignore + + if proxy_args is not None: + client.proxy_set(**proxy_args) + + if auth: + username = auth.get('username') + if username: + password = auth.get('password') + client.username_pw_set(username, password) + else: + raise KeyError("The 'username' key was not found, this is " + "required for auth") + + if will is not None: + client.will_set(**will) + + if tls is not None: + if isinstance(tls, dict): + insecure = tls.pop('insecure', False) + # mypy don't get that tls no longer contains the key insecure + client.tls_set(**tls) # type: ignore[misc] + if insecure: + # Must be set *after* the `client.tls_set()` call since it sets + # up the SSL context that `client.tls_insecure_set` alters. + client.tls_insecure_set(insecure) + else: + # Assume input is SSLContext object + client.tls_set_context(tls) + + client.connect(hostname, port, keepalive) + client.loop_forever() + + +def single( + topic: str, + payload: paho.PayloadType = None, + qos: int = 0, + retain: bool = False, + hostname: str = "localhost", + port: int = 1883, + client_id: str = "", + keepalive: int = 60, + will: MessageDict | None = None, + auth: AuthParameter | None = None, + tls: TLSParameter | None = None, + protocol: MQTTProtocolVersion = paho.MQTTv311, + transport: Literal["tcp", "websockets"] = "tcp", + proxy_args: Any | None = None, +) -> None: + """Publish a single message to a broker, then disconnect cleanly. + + This function creates an MQTT client, connects to a broker and publishes a + single message. Once the message has been delivered, it disconnects cleanly + from the broker. + + :param str topic: the only required argument must be the topic string to which the + payload will be published. + + :param payload: the payload to be published. If "" or None, a zero length payload + will be published. + + :param int qos: the qos to use when publishing, default to 0. + + :param bool retain: set the message to be retained (True) or not (False). + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + Username is required, password is optional and will default to None + auth = {'username':"", 'password':""} + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Defaults to None, which indicates that TLS should not be used. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + + :param transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param proxy_args: a dictionary that will be given to the client. + """ + + msg: MessageDict = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain} + + multiple([msg], hostname, port, client_id, keepalive, will, auth, tls, + protocol, transport, proxy_args) diff --git a/sbapp/pmqtt/py.typed b/sbapp/pmqtt/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/sbapp/pmqtt/reasoncodes.py b/sbapp/pmqtt/reasoncodes.py new file mode 100644 index 0000000..243ac96 --- /dev/null +++ b/sbapp/pmqtt/reasoncodes.py @@ -0,0 +1,223 @@ +# ******************************************************************* +# Copyright (c) 2017, 2019 IBM Corp. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Ian Craggs - initial implementation and/or documentation +# ******************************************************************* + +import functools +import warnings +from typing import Any + +from .packettypes import PacketTypes + + +@functools.total_ordering +class ReasonCode: + """MQTT version 5.0 reason codes class. + + See ReasonCode.names for a list of possible numeric values along with their + names and the packets to which they apply. + + """ + + def __init__(self, packetType: int, aName: str ="Success", identifier: int =-1): + """ + packetType: the type of the packet, such as PacketTypes.CONNECT that + this reason code will be used with. Some reason codes have different + names for the same identifier when used a different packet type. + + aName: the String name of the reason code to be created. Ignored + if the identifier is set. + + identifier: an integer value of the reason code to be created. + + """ + + self.packetType = packetType + self.names = { + 0: {"Success": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, + PacketTypes.UNSUBACK, PacketTypes.AUTH], + "Normal disconnection": [PacketTypes.DISCONNECT], + "Granted QoS 0": [PacketTypes.SUBACK]}, + 1: {"Granted QoS 1": [PacketTypes.SUBACK]}, + 2: {"Granted QoS 2": [PacketTypes.SUBACK]}, + 4: {"Disconnect with will message": [PacketTypes.DISCONNECT]}, + 16: {"No matching subscribers": + [PacketTypes.PUBACK, PacketTypes.PUBREC]}, + 17: {"No subscription found": [PacketTypes.UNSUBACK]}, + 24: {"Continue authentication": [PacketTypes.AUTH]}, + 25: {"Re-authenticate": [PacketTypes.AUTH]}, + 128: {"Unspecified error": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, + PacketTypes.DISCONNECT], }, + 129: {"Malformed packet": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 130: {"Protocol error": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 131: {"Implementation specific error": [PacketTypes.CONNACK, + PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, + PacketTypes.UNSUBACK, PacketTypes.DISCONNECT], }, + 132: {"Unsupported protocol version": [PacketTypes.CONNACK]}, + 133: {"Client identifier not valid": [PacketTypes.CONNACK]}, + 134: {"Bad user name or password": [PacketTypes.CONNACK]}, + 135: {"Not authorized": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, + PacketTypes.DISCONNECT], }, + 136: {"Server unavailable": [PacketTypes.CONNACK]}, + 137: {"Server busy": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 138: {"Banned": [PacketTypes.CONNACK]}, + 139: {"Server shutting down": [PacketTypes.DISCONNECT]}, + 140: {"Bad authentication method": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 141: {"Keep alive timeout": [PacketTypes.DISCONNECT]}, + 142: {"Session taken over": [PacketTypes.DISCONNECT]}, + 143: {"Topic filter invalid": + [PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT]}, + 144: {"Topic name invalid": + [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, + 145: {"Packet identifier in use": + [PacketTypes.PUBACK, PacketTypes.PUBREC, + PacketTypes.SUBACK, PacketTypes.UNSUBACK]}, + 146: {"Packet identifier not found": + [PacketTypes.PUBREL, PacketTypes.PUBCOMP]}, + 147: {"Receive maximum exceeded": [PacketTypes.DISCONNECT]}, + 148: {"Topic alias invalid": [PacketTypes.DISCONNECT]}, + 149: {"Packet too large": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 150: {"Message rate too high": [PacketTypes.DISCONNECT]}, + 151: {"Quota exceeded": [PacketTypes.CONNACK, PacketTypes.PUBACK, + PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.DISCONNECT], }, + 152: {"Administrative action": [PacketTypes.DISCONNECT]}, + 153: {"Payload format invalid": + [PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, + 154: {"Retain not supported": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 155: {"QoS not supported": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 156: {"Use another server": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 157: {"Server moved": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 158: {"Shared subscription not supported": + [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, + 159: {"Connection rate exceeded": + [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, + 160: {"Maximum connect time": + [PacketTypes.DISCONNECT]}, + 161: {"Subscription identifiers not supported": + [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, + 162: {"Wildcard subscription not supported": + [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, + } + if identifier == -1: + if packetType == PacketTypes.DISCONNECT and aName == "Success": + aName = "Normal disconnection" + self.set(aName) + else: + self.value = identifier + self.getName() # check it's good + + def __getName__(self, packetType, identifier): + """ + Get the reason code string name for a specific identifier. + The name can vary by packet type for the same identifier, which + is why the packet type is also required. + + Used when displaying the reason code. + """ + if identifier not in self.names: + raise KeyError(identifier) + names = self.names[identifier] + namelist = [name for name in names.keys() if packetType in names[name]] + if len(namelist) != 1: + raise ValueError(f"Expected exactly one name, found {namelist!r}") + return namelist[0] + + def getId(self, name): + """ + Get the numeric id corresponding to a reason code name. + + Used when setting the reason code for a packetType + check that only valid codes for the packet are set. + """ + for code in self.names.keys(): + if name in self.names[code].keys(): + if self.packetType in self.names[code][name]: + return code + raise KeyError(f"Reason code name not found: {name}") + + def set(self, name): + self.value = self.getId(name) + + def unpack(self, buffer): + c = buffer[0] + name = self.__getName__(self.packetType, c) + self.value = self.getId(name) + return 1 + + def getName(self): + """Returns the reason code name corresponding to the numeric value which is set. + """ + return self.__getName__(self.packetType, self.value) + + def __eq__(self, other): + if isinstance(other, int): + return self.value == other + if isinstance(other, str): + return other == str(self) + if isinstance(other, ReasonCode): + return self.value == other.value + return False + + def __lt__(self, other): + if isinstance(other, int): + return self.value < other + if isinstance(other, ReasonCode): + return self.value < other.value + return NotImplemented + + def __repr__(self): + try: + packet_name = PacketTypes.Names[self.packetType] + except IndexError: + packet_name = "Unknown" + + return f"ReasonCode({packet_name}, {self.getName()!r})" + + def __str__(self): + return self.getName() + + def json(self): + return self.getName() + + def pack(self): + return bytearray([self.value]) + + @property + def is_failure(self) -> bool: + return self.value >= 0x80 + + +class _CompatibilityIsInstance(type): + def __instancecheck__(self, other: Any) -> bool: + return isinstance(other, ReasonCode) + + +class ReasonCodes(ReasonCode, metaclass=_CompatibilityIsInstance): + def __init__(self, *args, **kwargs): + warnings.warn("ReasonCodes is deprecated, use ReasonCode (singular) instead", + category=DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/sbapp/pmqtt/subscribe.py b/sbapp/pmqtt/subscribe.py new file mode 100644 index 0000000..b6c80f4 --- /dev/null +++ b/sbapp/pmqtt/subscribe.py @@ -0,0 +1,281 @@ +# Copyright (c) 2016 Roger Light +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v2.0 +# and Eclipse Distribution License v1.0 which accompany this distribution. +# +# The Eclipse Public License is available at +# http://www.eclipse.org/legal/epl-v20.html +# and the Eclipse Distribution License is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# Contributors: +# Roger Light - initial API and implementation + +""" +This module provides some helper functions to allow straightforward subscribing +to topics and retrieving messages. The two functions are simple(), which +returns one or messages matching a set of topics, and callback() which allows +you to pass a callback for processing of messages. +""" + +from .. import mqtt +from . import client as paho + + +def _on_connect(client, userdata, flags, reason_code, properties): + """Internal callback""" + if reason_code != 0: + raise mqtt.MQTTException(paho.connack_string(reason_code)) + + if isinstance(userdata['topics'], list): + for topic in userdata['topics']: + client.subscribe(topic, userdata['qos']) + else: + client.subscribe(userdata['topics'], userdata['qos']) + + +def _on_message_callback(client, userdata, message): + """Internal callback""" + userdata['callback'](client, userdata['userdata'], message) + + +def _on_message_simple(client, userdata, message): + """Internal callback""" + + if userdata['msg_count'] == 0: + return + + # Don't process stale retained messages if 'retained' was false + if message.retain and not userdata['retained']: + return + + userdata['msg_count'] = userdata['msg_count'] - 1 + + if userdata['messages'] is None and userdata['msg_count'] == 0: + userdata['messages'] = message + client.disconnect() + return + + userdata['messages'].append(message) + if userdata['msg_count'] == 0: + client.disconnect() + + +def callback(callback, topics, qos=0, userdata=None, hostname="localhost", + port=1883, client_id="", keepalive=60, will=None, auth=None, + tls=None, protocol=paho.MQTTv311, transport="tcp", + clean_session=True, proxy_args=None): + """Subscribe to a list of topics and process them in a callback function. + + This function creates an MQTT client, connects to a broker and subscribes + to a list of topics. Incoming messages are processed by the user provided + callback. This is a blocking function and will never return. + + :param callback: function with the same signature as `on_message` for + processing the messages received. + + :param topics: either a string containing a single topic to subscribe to, or a + list of topics to subscribe to. + + :param int qos: the qos to use when subscribing. This is applied to all topics. + + :param userdata: passed to the callback + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + auth = {'username':"", 'password':""} + Username is required, password is optional and will default to None + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + Defaults to None, which indicates that TLS should not be used. + + :param str transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param clean_session: a boolean that determines the client type. If True, + the broker will remove all information about this client + when it disconnects. If False, the client is a persistent + client and subscription information and queued messages + will be retained when the client disconnects. + Defaults to True. + + :param proxy_args: a dictionary that will be given to the client. + """ + + if qos < 0 or qos > 2: + raise ValueError('qos must be in the range 0-2') + + callback_userdata = { + 'callback':callback, + 'topics':topics, + 'qos':qos, + 'userdata':userdata} + + client = paho.Client( + paho.CallbackAPIVersion.VERSION2, + client_id=client_id, + userdata=callback_userdata, + protocol=protocol, + transport=transport, + clean_session=clean_session, + ) + client.enable_logger() + + client.on_message = _on_message_callback + client.on_connect = _on_connect + + if proxy_args is not None: + client.proxy_set(**proxy_args) + + if auth: + username = auth.get('username') + if username: + password = auth.get('password') + client.username_pw_set(username, password) + else: + raise KeyError("The 'username' key was not found, this is " + "required for auth") + + if will is not None: + client.will_set(**will) + + if tls is not None: + if isinstance(tls, dict): + insecure = tls.pop('insecure', False) + client.tls_set(**tls) + if insecure: + # Must be set *after* the `client.tls_set()` call since it sets + # up the SSL context that `client.tls_insecure_set` alters. + client.tls_insecure_set(insecure) + else: + # Assume input is SSLContext object + client.tls_set_context(tls) + + client.connect(hostname, port, keepalive) + client.loop_forever() + + +def simple(topics, qos=0, msg_count=1, retained=True, hostname="localhost", + port=1883, client_id="", keepalive=60, will=None, auth=None, + tls=None, protocol=paho.MQTTv311, transport="tcp", + clean_session=True, proxy_args=None): + """Subscribe to a list of topics and return msg_count messages. + + This function creates an MQTT client, connects to a broker and subscribes + to a list of topics. Once "msg_count" messages have been received, it + disconnects cleanly from the broker and returns the messages. + + :param topics: either a string containing a single topic to subscribe to, or a + list of topics to subscribe to. + + :param int qos: the qos to use when subscribing. This is applied to all topics. + + :param int msg_count: the number of messages to retrieve from the broker. + if msg_count == 1 then a single MQTTMessage will be returned. + if msg_count > 1 then a list of MQTTMessages will be returned. + + :param bool retained: If set to True, retained messages will be processed the same as + non-retained messages. If set to False, retained messages will + be ignored. This means that with retained=False and msg_count=1, + the function will return the first message received that does + not have the retained flag set. + + :param str hostname: the address of the broker to connect to. + Defaults to localhost. + + :param int port: the port to connect to the broker on. Defaults to 1883. + + :param str client_id: the MQTT client id to use. If "" or None, the Paho library will + generate a client id automatically. + + :param int keepalive: the keepalive timeout value for the client. Defaults to 60 + seconds. + + :param will: a dict containing will parameters for the client: will = {'topic': + "", 'payload':", 'qos':, 'retain':}. + Topic is required, all other parameters are optional and will + default to None, 0 and False respectively. + Defaults to None, which indicates no will should be used. + + :param auth: a dict containing authentication parameters for the client: + auth = {'username':"", 'password':""} + Username is required, password is optional and will default to None + if not provided. + Defaults to None, which indicates no authentication is to be used. + + :param tls: a dict containing TLS configuration parameters for the client: + dict = {'ca_certs':"", 'certfile':"", + 'keyfile':"", 'tls_version':"", + 'ciphers':", 'insecure':""} + ca_certs is required, all other parameters are optional and will + default to None if not provided, which results in the client using + the default behaviour - see the paho.mqtt.client documentation. + Alternatively, tls input can be an SSLContext object, which will be + processed using the tls_set_context method. + Defaults to None, which indicates that TLS should not be used. + + :param protocol: the MQTT protocol version to use. Defaults to MQTTv311. + + :param transport: set to "tcp" to use the default setting of transport which is + raw TCP. Set to "websockets" to use WebSockets as the transport. + + :param clean_session: a boolean that determines the client type. If True, + the broker will remove all information about this client + when it disconnects. If False, the client is a persistent + client and subscription information and queued messages + will be retained when the client disconnects. + Defaults to True. If protocol is MQTTv50, clean_session + is ignored. + + :param proxy_args: a dictionary that will be given to the client. + """ + + if msg_count < 1: + raise ValueError('msg_count must be > 0') + + # Set ourselves up to return a single message if msg_count == 1, or a list + # if > 1. + if msg_count == 1: + messages = None + else: + messages = [] + + # Ignore clean_session if protocol is MQTTv50, otherwise Client will raise + if protocol == paho.MQTTv5: + clean_session = None + + userdata = {'retained':retained, 'msg_count':msg_count, 'messages':messages} + + callback(_on_message_simple, topics, qos, userdata, hostname, port, + client_id, keepalive, will, auth, tls, protocol, transport, + clean_session, proxy_args) + + return userdata['messages'] diff --git a/sbapp/pmqtt/subscribeoptions.py b/sbapp/pmqtt/subscribeoptions.py new file mode 100644 index 0000000..7e0605d --- /dev/null +++ b/sbapp/pmqtt/subscribeoptions.py @@ -0,0 +1,113 @@ +""" +******************************************************************* + Copyright (c) 2017, 2019 IBM Corp. + + All rights reserved. This program and the accompanying materials + are made available under the terms of the Eclipse Public License v2.0 + and Eclipse Distribution License v1.0 which accompany this distribution. + + The Eclipse Public License is available at + http://www.eclipse.org/legal/epl-v20.html + and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + + Contributors: + Ian Craggs - initial implementation and/or documentation +******************************************************************* +""" + + + +class MQTTException(Exception): + pass + + +class SubscribeOptions: + """The MQTT v5.0 subscribe options class. + + The options are: + qos: As in MQTT v3.1.1. + noLocal: True or False. If set to True, the subscriber will not receive its own publications. + retainAsPublished: True or False. If set to True, the retain flag on received publications will be as set + by the publisher. + retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND + Controls when the broker should send retained messages: + - RETAIN_SEND_ON_SUBSCRIBE: on any successful subscribe request + - RETAIN_SEND_IF_NEW_SUB: only if the subscribe request is new + - RETAIN_DO_NOT_SEND: never send retained messages + """ + + # retain handling options + RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB, RETAIN_DO_NOT_SEND = range( + 0, 3) + + def __init__( + self, + qos: int = 0, + noLocal: bool = False, + retainAsPublished: bool = False, + retainHandling: int = RETAIN_SEND_ON_SUBSCRIBE, + ): + """ + qos: 0, 1 or 2. 0 is the default. + noLocal: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. + retainAsPublished: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. + retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND + RETAIN_SEND_ON_SUBSCRIBE is the default and corresponds to MQTT v3.1.1 behavior. + """ + object.__setattr__(self, "names", + ["QoS", "noLocal", "retainAsPublished", "retainHandling"]) + self.QoS = qos # bits 0,1 + self.noLocal = noLocal # bit 2 + self.retainAsPublished = retainAsPublished # bit 3 + self.retainHandling = retainHandling # bits 4 and 5: 0, 1 or 2 + if self.retainHandling not in (0, 1, 2): + raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") + if self.QoS not in (0, 1, 2): + raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") + + def __setattr__(self, name, value): + if name not in self.names: + raise MQTTException( + f"{name} Attribute name must be one of {self.names}") + object.__setattr__(self, name, value) + + def pack(self): + if self.retainHandling not in (0, 1, 2): + raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") + if self.QoS not in (0, 1, 2): + raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") + noLocal = 1 if self.noLocal else 0 + retainAsPublished = 1 if self.retainAsPublished else 0 + data = [(self.retainHandling << 4) | (retainAsPublished << 3) | + (noLocal << 2) | self.QoS] + return bytes(data) + + def unpack(self, buffer): + b0 = buffer[0] + self.retainHandling = ((b0 >> 4) & 0x03) + self.retainAsPublished = True if ((b0 >> 3) & 0x01) == 1 else False + self.noLocal = True if ((b0 >> 2) & 0x01) == 1 else False + self.QoS = (b0 & 0x03) + if self.retainHandling not in (0, 1, 2): + raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") + if self.QoS not in (0, 1, 2): + raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") + return 1 + + def __repr__(self): + return str(self) + + def __str__(self): + return "{QoS="+str(self.QoS)+", noLocal="+str(self.noLocal) +\ + ", retainAsPublished="+str(self.retainAsPublished) +\ + ", retainHandling="+str(self.retainHandling)+"}" + + def json(self): + data = { + "QoS": self.QoS, + "noLocal": self.noLocal, + "retainAsPublished": self.retainAsPublished, + "retainHandling": self.retainHandling, + } + return data From c873b9fa33ac187b14dd7fa857ee2f596d7124a8 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 14:12:13 +0100 Subject: [PATCH 57/76] Cleanup --- sbapp/mqtt/__init__.py | 5 - sbapp/mqtt/client.py | 5004 -------------------------------- sbapp/mqtt/enums.py | 113 - sbapp/mqtt/matcher.py | 78 - sbapp/mqtt/packettypes.py | 43 - sbapp/mqtt/properties.py | 421 --- sbapp/mqtt/publish.py | 306 -- sbapp/mqtt/py.typed | 0 sbapp/mqtt/reasoncodes.py | 223 -- sbapp/mqtt/subscribe.py | 281 -- sbapp/mqtt/subscribeoptions.py | 113 - sbapp/sideband/core.py | 7 +- sbapp/sideband/mqtt.py | 6 +- sbapp/sideband/sense.py | 4 - 14 files changed, 9 insertions(+), 6595 deletions(-) delete mode 100644 sbapp/mqtt/__init__.py delete mode 100644 sbapp/mqtt/client.py delete mode 100644 sbapp/mqtt/enums.py delete mode 100644 sbapp/mqtt/matcher.py delete mode 100644 sbapp/mqtt/packettypes.py delete mode 100644 sbapp/mqtt/properties.py delete mode 100644 sbapp/mqtt/publish.py delete mode 100644 sbapp/mqtt/py.typed delete mode 100644 sbapp/mqtt/reasoncodes.py delete mode 100644 sbapp/mqtt/subscribe.py delete mode 100644 sbapp/mqtt/subscribeoptions.py diff --git a/sbapp/mqtt/__init__.py b/sbapp/mqtt/__init__.py deleted file mode 100644 index 9372c8f..0000000 --- a/sbapp/mqtt/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -__version__ = "2.1.1.dev0" - - -class MQTTException(Exception): - pass diff --git a/sbapp/mqtt/client.py b/sbapp/mqtt/client.py deleted file mode 100644 index 4ccc869..0000000 --- a/sbapp/mqtt/client.py +++ /dev/null @@ -1,5004 +0,0 @@ -# Copyright (c) 2012-2019 Roger Light and others -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v2.0 -# and Eclipse Distribution License v1.0 which accompany this distribution. -# -# The Eclipse Public License is available at -# http://www.eclipse.org/legal/epl-v20.html -# and the Eclipse Distribution License is available at -# http://www.eclipse.org/org/documents/edl-v10.php. -# -# Contributors: -# Roger Light - initial API and implementation -# Ian Craggs - MQTT V5 support -""" -This is an MQTT client module. MQTT is a lightweight pub/sub messaging -protocol that is easy to implement and suitable for low powered devices. -""" -from __future__ import annotations - -import base64 -import collections -import errno -import hashlib -import logging -import os -import platform -import select -import socket -import string -import struct -import threading -import time -import urllib.parse -import urllib.request -import uuid -import warnings -from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, NamedTuple, Sequence, Tuple, Union, cast - -from paho.mqtt.packettypes import PacketTypes - -from .enums import CallbackAPIVersion, ConnackCode, LogLevel, MessageState, MessageType, MQTTErrorCode, MQTTProtocolVersion, PahoClientMode, _ConnectionState -from .matcher import MQTTMatcher -from .properties import Properties -from .reasoncodes import ReasonCode, ReasonCodes -from .subscribeoptions import SubscribeOptions - -try: - from typing import Literal -except ImportError: - from typing_extensions import Literal # type: ignore - -if TYPE_CHECKING: - try: - from typing import TypedDict # type: ignore - except ImportError: - from typing_extensions import TypedDict - - try: - from typing import Protocol # type: ignore - except ImportError: - from typing_extensions import Protocol # type: ignore - - class _InPacket(TypedDict): - command: int - have_remaining: int - remaining_count: list[int] - remaining_mult: int - remaining_length: int - packet: bytearray - to_process: int - pos: int - - - class _OutPacket(TypedDict): - command: int - mid: int - qos: int - pos: int - to_process: int - packet: bytes - info: MQTTMessageInfo | None - - class SocketLike(Protocol): - def recv(self, buffer_size: int) -> bytes: - ... - def send(self, buffer: bytes) -> int: - ... - def close(self) -> None: - ... - def fileno(self) -> int: - ... - def setblocking(self, flag: bool) -> None: - ... - - -try: - import ssl -except ImportError: - ssl = None # type: ignore[assignment] - - -try: - import socks # type: ignore[import-untyped] -except ImportError: - socks = None # type: ignore[assignment] - - -try: - # Use monotonic clock if available - time_func = time.monotonic -except AttributeError: - time_func = time.time - -try: - import dns.resolver - - HAVE_DNS = True -except ImportError: - HAVE_DNS = False - - -if platform.system() == 'Windows': - EAGAIN = errno.WSAEWOULDBLOCK # type: ignore[attr-defined] -else: - EAGAIN = errno.EAGAIN - -# Avoid linter complain. We kept importing it as ReasonCodes (plural) for compatibility -_ = ReasonCodes - -# Keep copy of enums values for compatibility. -CONNECT = MessageType.CONNECT -CONNACK = MessageType.CONNACK -PUBLISH = MessageType.PUBLISH -PUBACK = MessageType.PUBACK -PUBREC = MessageType.PUBREC -PUBREL = MessageType.PUBREL -PUBCOMP = MessageType.PUBCOMP -SUBSCRIBE = MessageType.SUBSCRIBE -SUBACK = MessageType.SUBACK -UNSUBSCRIBE = MessageType.UNSUBSCRIBE -UNSUBACK = MessageType.UNSUBACK -PINGREQ = MessageType.PINGREQ -PINGRESP = MessageType.PINGRESP -DISCONNECT = MessageType.DISCONNECT -AUTH = MessageType.AUTH - -# Log levels -MQTT_LOG_INFO = LogLevel.MQTT_LOG_INFO -MQTT_LOG_NOTICE = LogLevel.MQTT_LOG_NOTICE -MQTT_LOG_WARNING = LogLevel.MQTT_LOG_WARNING -MQTT_LOG_ERR = LogLevel.MQTT_LOG_ERR -MQTT_LOG_DEBUG = LogLevel.MQTT_LOG_DEBUG -LOGGING_LEVEL = { - LogLevel.MQTT_LOG_DEBUG: logging.DEBUG, - LogLevel.MQTT_LOG_INFO: logging.INFO, - LogLevel.MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level - LogLevel.MQTT_LOG_WARNING: logging.WARNING, - LogLevel.MQTT_LOG_ERR: logging.ERROR, -} - -# CONNACK codes -CONNACK_ACCEPTED = ConnackCode.CONNACK_ACCEPTED -CONNACK_REFUSED_PROTOCOL_VERSION = ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION -CONNACK_REFUSED_IDENTIFIER_REJECTED = ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED -CONNACK_REFUSED_SERVER_UNAVAILABLE = ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE -CONNACK_REFUSED_BAD_USERNAME_PASSWORD = ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD -CONNACK_REFUSED_NOT_AUTHORIZED = ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED - -# Message state -mqtt_ms_invalid = MessageState.MQTT_MS_INVALID -mqtt_ms_publish = MessageState.MQTT_MS_PUBLISH -mqtt_ms_wait_for_puback = MessageState.MQTT_MS_WAIT_FOR_PUBACK -mqtt_ms_wait_for_pubrec = MessageState.MQTT_MS_WAIT_FOR_PUBREC -mqtt_ms_resend_pubrel = MessageState.MQTT_MS_RESEND_PUBREL -mqtt_ms_wait_for_pubrel = MessageState.MQTT_MS_WAIT_FOR_PUBREL -mqtt_ms_resend_pubcomp = MessageState.MQTT_MS_RESEND_PUBCOMP -mqtt_ms_wait_for_pubcomp = MessageState.MQTT_MS_WAIT_FOR_PUBCOMP -mqtt_ms_send_pubrec = MessageState.MQTT_MS_SEND_PUBREC -mqtt_ms_queued = MessageState.MQTT_MS_QUEUED - -MQTT_ERR_AGAIN = MQTTErrorCode.MQTT_ERR_AGAIN -MQTT_ERR_SUCCESS = MQTTErrorCode.MQTT_ERR_SUCCESS -MQTT_ERR_NOMEM = MQTTErrorCode.MQTT_ERR_NOMEM -MQTT_ERR_PROTOCOL = MQTTErrorCode.MQTT_ERR_PROTOCOL -MQTT_ERR_INVAL = MQTTErrorCode.MQTT_ERR_INVAL -MQTT_ERR_NO_CONN = MQTTErrorCode.MQTT_ERR_NO_CONN -MQTT_ERR_CONN_REFUSED = MQTTErrorCode.MQTT_ERR_CONN_REFUSED -MQTT_ERR_NOT_FOUND = MQTTErrorCode.MQTT_ERR_NOT_FOUND -MQTT_ERR_CONN_LOST = MQTTErrorCode.MQTT_ERR_CONN_LOST -MQTT_ERR_TLS = MQTTErrorCode.MQTT_ERR_TLS -MQTT_ERR_PAYLOAD_SIZE = MQTTErrorCode.MQTT_ERR_PAYLOAD_SIZE -MQTT_ERR_NOT_SUPPORTED = MQTTErrorCode.MQTT_ERR_NOT_SUPPORTED -MQTT_ERR_AUTH = MQTTErrorCode.MQTT_ERR_AUTH -MQTT_ERR_ACL_DENIED = MQTTErrorCode.MQTT_ERR_ACL_DENIED -MQTT_ERR_UNKNOWN = MQTTErrorCode.MQTT_ERR_UNKNOWN -MQTT_ERR_ERRNO = MQTTErrorCode.MQTT_ERR_ERRNO -MQTT_ERR_QUEUE_SIZE = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE -MQTT_ERR_KEEPALIVE = MQTTErrorCode.MQTT_ERR_KEEPALIVE - -MQTTv31 = MQTTProtocolVersion.MQTTv31 -MQTTv311 = MQTTProtocolVersion.MQTTv311 -MQTTv5 = MQTTProtocolVersion.MQTTv5 - -MQTT_CLIENT = PahoClientMode.MQTT_CLIENT -MQTT_BRIDGE = PahoClientMode.MQTT_BRIDGE - -# For MQTT V5, use the clean start flag only on the first successful connect -MQTT_CLEAN_START_FIRST_ONLY: CleanStartOption = 3 - -sockpair_data = b"0" - -# Payload support all those type and will be converted to bytes: -# * str are utf8 encoded -# * int/float are converted to string and utf8 encoded (e.g. 1 is converted to b"1") -# * None is converted to a zero-length payload (i.e. b"") -PayloadType = Union[str, bytes, bytearray, int, float, None] - -HTTPHeader = Dict[str, str] -WebSocketHeaders = Union[Callable[[HTTPHeader], HTTPHeader], HTTPHeader] - -CleanStartOption = Union[bool, Literal[3]] - - -class ConnectFlags(NamedTuple): - """Contains additional information passed to `on_connect` callback""" - - session_present: bool - """ - this flag is useful for clients that are - using clean session set to False only (MQTTv3) or clean_start = False (MQTTv5). - In that case, if client that reconnects to a broker that it has previously - connected to, this flag indicates whether the broker still has the - session information for the client. If true, the session still exists. - """ - - -class DisconnectFlags(NamedTuple): - """Contains additional information passed to `on_disconnect` callback""" - - is_disconnect_packet_from_server: bool - """ - tells whether this on_disconnect call is the result - of receiving an DISCONNECT packet from the broker or if the on_disconnect is only - generated by the client library. - When true, the reason code is generated by the broker. - """ - - -CallbackOnConnect_v1_mqtt3 = Callable[["Client", Any, Dict[str, Any], MQTTErrorCode], None] -CallbackOnConnect_v1_mqtt5 = Callable[["Client", Any, Dict[str, Any], ReasonCode, Union[Properties, None]], None] -CallbackOnConnect_v1 = Union[CallbackOnConnect_v1_mqtt5, CallbackOnConnect_v1_mqtt3] -CallbackOnConnect_v2 = Callable[["Client", Any, ConnectFlags, ReasonCode, Union[Properties, None]], None] -CallbackOnConnect = Union[CallbackOnConnect_v1, CallbackOnConnect_v2] -CallbackOnConnectFail = Callable[["Client", Any], None] -CallbackOnDisconnect_v1_mqtt3 = Callable[["Client", Any, MQTTErrorCode], None] -CallbackOnDisconnect_v1_mqtt5 = Callable[["Client", Any, Union[ReasonCode, int, None], Union[Properties, None]], None] -CallbackOnDisconnect_v1 = Union[CallbackOnDisconnect_v1_mqtt3, CallbackOnDisconnect_v1_mqtt5] -CallbackOnDisconnect_v2 = Callable[["Client", Any, DisconnectFlags, ReasonCode, Union[Properties, None]], None] -CallbackOnDisconnect = Union[CallbackOnDisconnect_v1, CallbackOnDisconnect_v2] -CallbackOnLog = Callable[["Client", Any, int, str], None] -CallbackOnMessage = Callable[["Client", Any, "MQTTMessage"], None] -CallbackOnPreConnect = Callable[["Client", Any], None] -CallbackOnPublish_v1 = Callable[["Client", Any, int], None] -CallbackOnPublish_v2 = Callable[["Client", Any, int, ReasonCode, Properties], None] -CallbackOnPublish = Union[CallbackOnPublish_v1, CallbackOnPublish_v2] -CallbackOnSocket = Callable[["Client", Any, "SocketLike"], None] -CallbackOnSubscribe_v1_mqtt3 = Callable[["Client", Any, int, Tuple[int, ...]], None] -CallbackOnSubscribe_v1_mqtt5 = Callable[["Client", Any, int, List[ReasonCode], Properties], None] -CallbackOnSubscribe_v1 = Union[CallbackOnSubscribe_v1_mqtt3, CallbackOnSubscribe_v1_mqtt5] -CallbackOnSubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None] -CallbackOnSubscribe = Union[CallbackOnSubscribe_v1, CallbackOnSubscribe_v2] -CallbackOnUnsubscribe_v1_mqtt3 = Callable[["Client", Any, int], None] -CallbackOnUnsubscribe_v1_mqtt5 = Callable[["Client", Any, int, Properties, Union[ReasonCode, List[ReasonCode]]], None] -CallbackOnUnsubscribe_v1 = Union[CallbackOnUnsubscribe_v1_mqtt3, CallbackOnUnsubscribe_v1_mqtt5] -CallbackOnUnsubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None] -CallbackOnUnsubscribe = Union[CallbackOnUnsubscribe_v1, CallbackOnUnsubscribe_v2] - -# This is needed for typing because class Client redefined the name "socket" -_socket = socket - - -class WebsocketConnectionError(ConnectionError): - """ WebsocketConnectionError is a subclass of ConnectionError. - - It's raised when unable to perform the Websocket handshake. - """ - pass - - -def error_string(mqtt_errno: MQTTErrorCode | int) -> str: - """Return the error string associated with an mqtt error number.""" - if mqtt_errno == MQTT_ERR_SUCCESS: - return "No error." - elif mqtt_errno == MQTT_ERR_NOMEM: - return "Out of memory." - elif mqtt_errno == MQTT_ERR_PROTOCOL: - return "A network protocol error occurred when communicating with the broker." - elif mqtt_errno == MQTT_ERR_INVAL: - return "Invalid function arguments provided." - elif mqtt_errno == MQTT_ERR_NO_CONN: - return "The client is not currently connected." - elif mqtt_errno == MQTT_ERR_CONN_REFUSED: - return "The connection was refused." - elif mqtt_errno == MQTT_ERR_NOT_FOUND: - return "Message not found (internal error)." - elif mqtt_errno == MQTT_ERR_CONN_LOST: - return "The connection was lost." - elif mqtt_errno == MQTT_ERR_TLS: - return "A TLS error occurred." - elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE: - return "Payload too large." - elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED: - return "This feature is not supported." - elif mqtt_errno == MQTT_ERR_AUTH: - return "Authorisation failed." - elif mqtt_errno == MQTT_ERR_ACL_DENIED: - return "Access denied by ACL." - elif mqtt_errno == MQTT_ERR_UNKNOWN: - return "Unknown error." - elif mqtt_errno == MQTT_ERR_ERRNO: - return "Error defined by errno." - elif mqtt_errno == MQTT_ERR_QUEUE_SIZE: - return "Message queue full." - elif mqtt_errno == MQTT_ERR_KEEPALIVE: - return "Client or broker did not communicate in the keepalive interval." - else: - return "Unknown error." - - -def connack_string(connack_code: int|ReasonCode) -> str: - """Return the string associated with a CONNACK result or CONNACK reason code.""" - if isinstance(connack_code, ReasonCode): - return str(connack_code) - - if connack_code == CONNACK_ACCEPTED: - return "Connection Accepted." - elif connack_code == CONNACK_REFUSED_PROTOCOL_VERSION: - return "Connection Refused: unacceptable protocol version." - elif connack_code == CONNACK_REFUSED_IDENTIFIER_REJECTED: - return "Connection Refused: identifier rejected." - elif connack_code == CONNACK_REFUSED_SERVER_UNAVAILABLE: - return "Connection Refused: broker unavailable." - elif connack_code == CONNACK_REFUSED_BAD_USERNAME_PASSWORD: - return "Connection Refused: bad user name or password." - elif connack_code == CONNACK_REFUSED_NOT_AUTHORIZED: - return "Connection Refused: not authorised." - else: - return "Connection Refused: unknown reason." - - -def convert_connack_rc_to_reason_code(connack_code: ConnackCode) -> ReasonCode: - """Convert a MQTTv3 / MQTTv3.1.1 connack result to `ReasonCode`. - - This is used in `on_connect` callback to have a consistent API. - - Be careful that the numeric value isn't the same, for example: - - >>> ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE == 3 - >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == 136 - - It's recommended to compare by names - - >>> code_to_test = ReasonCode(PacketTypes.CONNACK, "Server unavailable") - >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == code_to_test - """ - if connack_code == ConnackCode.CONNACK_ACCEPTED: - return ReasonCode(PacketTypes.CONNACK, "Success") - if connack_code == ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION: - return ReasonCode(PacketTypes.CONNACK, "Unsupported protocol version") - if connack_code == ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED: - return ReasonCode(PacketTypes.CONNACK, "Client identifier not valid") - if connack_code == ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE: - return ReasonCode(PacketTypes.CONNACK, "Server unavailable") - if connack_code == ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD: - return ReasonCode(PacketTypes.CONNACK, "Bad user name or password") - if connack_code == ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED: - return ReasonCode(PacketTypes.CONNACK, "Not authorized") - - return ReasonCode(PacketTypes.CONNACK, "Unspecified error") - - -def convert_disconnect_error_code_to_reason_code(rc: MQTTErrorCode) -> ReasonCode: - """Convert an MQTTErrorCode to Reason code. - - This is used in `on_disconnect` callback to have a consistent API. - - Be careful that the numeric value isn't the same, for example: - - >>> MQTTErrorCode.MQTT_ERR_PROTOCOL == 2 - >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == 130 - - It's recommended to compare by names - - >>> code_to_test = ReasonCode(PacketTypes.DISCONNECT, "Protocol error") - >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == code_to_test - """ - if rc == MQTTErrorCode.MQTT_ERR_SUCCESS: - return ReasonCode(PacketTypes.DISCONNECT, "Success") - if rc == MQTTErrorCode.MQTT_ERR_KEEPALIVE: - return ReasonCode(PacketTypes.DISCONNECT, "Keep alive timeout") - if rc == MQTTErrorCode.MQTT_ERR_CONN_LOST: - return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error") - return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error") - - -def _base62( - num: int, - base: str = string.digits + string.ascii_letters, - padding: int = 1, -) -> str: - """Convert a number to base-62 representation.""" - if num < 0: - raise ValueError("Number must be positive or zero") - digits = [] - while num: - num, rest = divmod(num, 62) - digits.append(base[rest]) - digits.extend(base[0] for _ in range(len(digits), padding)) - return ''.join(reversed(digits)) - - -def topic_matches_sub(sub: str, topic: str) -> bool: - """Check whether a topic matches a subscription. - - For example: - - * Topic "foo/bar" would match the subscription "foo/#" or "+/bar" - * Topic "non/matching" would not match the subscription "non/+/+" - """ - matcher = MQTTMatcher() - matcher[sub] = True - try: - next(matcher.iter_match(topic)) - return True - except StopIteration: - return False - - -def _socketpair_compat() -> tuple[socket.socket, socket.socket]: - """TCP/IP socketpair including Windows support""" - listensock = socket.socket( - socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) - listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - listensock.bind(("127.0.0.1", 0)) - listensock.listen(1) - - iface, port = listensock.getsockname() - sock1 = socket.socket( - socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) - sock1.setblocking(False) - try: - sock1.connect(("127.0.0.1", port)) - except BlockingIOError: - pass - sock2, address = listensock.accept() - sock2.setblocking(False) - listensock.close() - return (sock1, sock2) - - -def _force_bytes(s: str | bytes) -> bytes: - if isinstance(s, str): - return s.encode("utf-8") - return s - - -def _encode_payload(payload: str | bytes | bytearray | int | float | None) -> bytes|bytearray: - if isinstance(payload, str): - return payload.encode("utf-8") - - if isinstance(payload, (int, float)): - return str(payload).encode("ascii") - - if payload is None: - return b"" - - if not isinstance(payload, (bytes, bytearray)): - raise TypeError( - "payload must be a string, bytearray, int, float or None." - ) - - return payload - - -class MQTTMessageInfo: - """This is a class returned from `Client.publish()` and can be used to find - out the mid of the message that was published, and to determine whether the - message has been published, and/or wait until it is published. - """ - - __slots__ = 'mid', '_published', '_condition', 'rc', '_iterpos' - - def __init__(self, mid: int): - self.mid = mid - """ The message Id (int)""" - self._published = False - self._condition = threading.Condition() - self.rc: MQTTErrorCode = MQTTErrorCode.MQTT_ERR_SUCCESS - """ The `MQTTErrorCode` that give status for this message. - This value could change until the message `is_published`""" - self._iterpos = 0 - - def __str__(self) -> str: - return str((self.rc, self.mid)) - - def __iter__(self) -> Iterator[MQTTErrorCode | int]: - self._iterpos = 0 - return self - - def __next__(self) -> MQTTErrorCode | int: - return self.next() - - def next(self) -> MQTTErrorCode | int: - if self._iterpos == 0: - self._iterpos = 1 - return self.rc - elif self._iterpos == 1: - self._iterpos = 2 - return self.mid - else: - raise StopIteration - - def __getitem__(self, index: int) -> MQTTErrorCode | int: - if index == 0: - return self.rc - elif index == 1: - return self.mid - else: - raise IndexError("index out of range") - - def _set_as_published(self) -> None: - with self._condition: - self._published = True - self._condition.notify() - - def wait_for_publish(self, timeout: float | None = None) -> None: - """Block until the message associated with this object is published, or - until the timeout occurs. If timeout is None, this will never time out. - Set timeout to a positive number of seconds, e.g. 1.2, to enable the - timeout. - - :raises ValueError: if the message was not queued due to the outgoing - queue being full. - - :raises RuntimeError: if the message was not published for another - reason. - """ - if self.rc == MQTT_ERR_QUEUE_SIZE: - raise ValueError('Message is not queued due to ERR_QUEUE_SIZE') - elif self.rc == MQTT_ERR_AGAIN: - pass - elif self.rc > 0: - raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') - - timeout_time = None if timeout is None else time_func() + timeout - timeout_tenth = None if timeout is None else timeout / 10. - def timed_out() -> bool: - return False if timeout_time is None else time_func() > timeout_time - - with self._condition: - while not self._published and not timed_out(): - self._condition.wait(timeout_tenth) - - if self.rc > 0: - raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') - - def is_published(self) -> bool: - """Returns True if the message associated with this object has been - published, else returns False. - - To wait for this to become true, look at `wait_for_publish`. - """ - if self.rc == MQTTErrorCode.MQTT_ERR_QUEUE_SIZE: - raise ValueError('Message is not queued due to ERR_QUEUE_SIZE') - elif self.rc == MQTTErrorCode.MQTT_ERR_AGAIN: - pass - elif self.rc > 0: - raise RuntimeError(f'Message publish failed: {error_string(self.rc)}') - - with self._condition: - return self._published - - -class MQTTMessage: - """ This is a class that describes an incoming message. It is - passed to the `on_message` callback as the message parameter. - """ - __slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info', 'properties' - - def __init__(self, mid: int = 0, topic: bytes = b""): - self.timestamp = 0.0 - self.state = mqtt_ms_invalid - self.dup = False - self.mid = mid - """ The message id (int).""" - self._topic = topic - self.payload = b"" - """the message payload (bytes)""" - self.qos = 0 - """ The message Quality of Service (0, 1 or 2).""" - self.retain = False - """ If true, the message is a retained message and not fresh.""" - self.info = MQTTMessageInfo(mid) - self.properties: Properties | None = None - """ In MQTT v5.0, the properties associated with the message. (`Properties`)""" - - def __eq__(self, other: object) -> bool: - """Override the default Equals behavior""" - if isinstance(other, self.__class__): - return self.mid == other.mid - return False - - def __ne__(self, other: object) -> bool: - """Define a non-equality test""" - return not self.__eq__(other) - - @property - def topic(self) -> str: - """topic that the message was published on. - - This property is read-only. - """ - return self._topic.decode('utf-8') - - @topic.setter - def topic(self, value: bytes) -> None: - self._topic = value - - -class Client: - """MQTT version 3.1/3.1.1/5.0 client class. - - This is the main class for use communicating with an MQTT broker. - - General usage flow: - - * Use `connect()`, `connect_async()` or `connect_srv()` to connect to a broker - * Use `loop_start()` to set a thread running to call `loop()` for you. - * Or use `loop_forever()` to handle calling `loop()` for you in a blocking function. - * Or call `loop()` frequently to maintain network traffic flow with the broker - * Use `subscribe()` to subscribe to a topic and receive messages - * Use `publish()` to send messages - * Use `disconnect()` to disconnect from the broker - - Data returned from the broker is made available with the use of callback - functions as described below. - - :param CallbackAPIVersion callback_api_version: define the API version for user-callback (on_connect, on_publish,...). - This field is required and it's recommended to use the latest version (CallbackAPIVersion.API_VERSION2). - See each callback for description of API for each version. The file docs/migrations.rst contains details on - how to migrate between version. - - :param str client_id: the unique client id string used when connecting to the - broker. If client_id is zero length or None, then the behaviour is - defined by which protocol version is in use. If using MQTT v3.1.1, then - a zero length client id will be sent to the broker and the broker will - generate a random for the client. If using MQTT v3.1 then an id will be - randomly generated. In both cases, clean_session must be True. If this - is not the case a ValueError will be raised. - - :param bool clean_session: a boolean that determines the client type. If True, - the broker will remove all information about this client when it - disconnects. If False, the client is a persistent client and - subscription information and queued messages will be retained when the - client disconnects. - Note that a client will never discard its own outgoing messages on - disconnect. Calling connect() or reconnect() will cause the messages to - be resent. Use reinitialise() to reset a client to its original state. - The clean_session argument only applies to MQTT versions v3.1.1 and v3.1. - It is not accepted if the MQTT version is v5.0 - use the clean_start - argument on connect() instead. - - :param userdata: user defined data of any type that is passed as the "userdata" - parameter to callbacks. It may be updated at a later point with the - user_data_set() function. - - :param int protocol: allows explicit setting of the MQTT version to - use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1), - paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0), - with the default being v3.1.1. - - :param transport: use "websockets" to use WebSockets as the transport - mechanism. Set to "tcp" to use raw TCP, which is the default. - Use "unix" to use Unix sockets as the transport mechanism; note that - this option is only available on platforms that support Unix sockets, - and the "host" argument is interpreted as the path to the Unix socket - file in this case. - - :param bool manual_ack: normally, when a message is received, the library automatically - acknowledges after on_message callback returns. manual_ack=True allows the application to - acknowledge receipt after it has completed processing of a message - using a the ack() method. This addresses vulnerability to message loss - if applications fails while processing a message, or while it pending - locally. - - Callbacks - ========= - - A number of callback functions are available to receive data back from the - broker. To use a callback, define a function and then assign it to the - client:: - - def on_connect(client, userdata, flags, reason_code, properties): - print(f"Connected with result code {reason_code}") - - client.on_connect = on_connect - - Callbacks can also be attached using decorators:: - - mqttc = paho.mqtt.Client() - - @mqttc.connect_callback() - def on_connect(client, userdata, flags, reason_code, properties): - print(f"Connected with result code {reason_code}") - - All of the callbacks as described below have a "client" and an "userdata" - argument. "client" is the `Client` instance that is calling the callback. - userdata" is user data of any type and can be set when creating a new client - instance or with `user_data_set()`. - - If you wish to suppress exceptions within a callback, you should set - ``mqttc.suppress_exceptions = True`` - - The callbacks are listed below, documentation for each of them can be found - at the same function name: - - `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`, - `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`, - `on_socket_register_write`, `on_socket_unregister_write` - """ - - def __init__( - self, - callback_api_version: CallbackAPIVersion = CallbackAPIVersion.VERSION1, - client_id: str | None = "", - clean_session: bool | None = None, - userdata: Any = None, - protocol: MQTTProtocolVersion = MQTTv311, - transport: Literal["tcp", "websockets", "unix"] = "tcp", - reconnect_on_failure: bool = True, - manual_ack: bool = False, - ) -> None: - transport = transport.lower() # type: ignore - if transport == "unix" and not hasattr(socket, "AF_UNIX"): - raise ValueError('"unix" transport not supported') - elif transport not in ("websockets", "tcp", "unix"): - raise ValueError( - f'transport must be "websockets", "tcp" or "unix", not {transport}') - - self._manual_ack = manual_ack - self._transport = transport - self._protocol = protocol - self._userdata = userdata - self._sock: SocketLike | None = None - self._sockpairR: socket.socket | None = None - self._sockpairW: socket.socket | None = None - self._keepalive = 60 - self._connect_timeout = 5.0 - self._client_mode = MQTT_CLIENT - self._callback_api_version = callback_api_version - - if self._callback_api_version == CallbackAPIVersion.VERSION1: - warnings.warn( - "Callback API version 1 is deprecated, update to latest version", - category=DeprecationWarning, - stacklevel=2, - ) - if isinstance(self._callback_api_version, str): - # Help user to migrate, it probably provided a client id - # as first arguments - raise ValueError( - "Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details" - ) - if self._callback_api_version not in CallbackAPIVersion: - raise ValueError("Unsupported callback API version") - - self._clean_start: int = MQTT_CLEAN_START_FIRST_ONLY - - if protocol == MQTTv5: - if clean_session is not None: - raise ValueError('Clean session is not used for MQTT 5.0') - else: - if clean_session is None: - clean_session = True - if not clean_session and (client_id == "" or client_id is None): - raise ValueError( - 'A client id must be provided if clean session is False.') - self._clean_session = clean_session - - # [MQTT-3.1.3-4] Client Id must be UTF-8 encoded string. - if client_id == "" or client_id is None: - if protocol == MQTTv31: - self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8") - else: - self._client_id = b"" - else: - self._client_id = _force_bytes(client_id) - - self._username: bytes | None = None - self._password: bytes | None = None - self._in_packet: _InPacket = { - "command": 0, - "have_remaining": 0, - "remaining_count": [], - "remaining_mult": 1, - "remaining_length": 0, - "packet": bytearray(b""), - "to_process": 0, - "pos": 0, - } - self._out_packet: collections.deque[_OutPacket] = collections.deque() - self._last_msg_in = time_func() - self._last_msg_out = time_func() - self._reconnect_min_delay = 1 - self._reconnect_max_delay = 120 - self._reconnect_delay: int | None = None - self._reconnect_on_failure = reconnect_on_failure - self._ping_t = 0.0 - self._last_mid = 0 - self._state = _ConnectionState.MQTT_CS_NEW - self._out_messages: collections.OrderedDict[ - int, MQTTMessage - ] = collections.OrderedDict() - self._in_messages: collections.OrderedDict[ - int, MQTTMessage - ] = collections.OrderedDict() - self._max_inflight_messages = 20 - self._inflight_messages = 0 - self._max_queued_messages = 0 - self._connect_properties: Properties | None = None - self._will_properties: Properties | None = None - self._will = False - self._will_topic = b"" - self._will_payload = b"" - self._will_qos = 0 - self._will_retain = False - self._on_message_filtered = MQTTMatcher() - self._host = "" - self._port = 1883 - self._bind_address = "" - self._bind_port = 0 - self._proxy: Any = {} - self._in_callback_mutex = threading.Lock() - self._callback_mutex = threading.RLock() - self._msgtime_mutex = threading.Lock() - self._out_message_mutex = threading.RLock() - self._in_message_mutex = threading.Lock() - self._reconnect_delay_mutex = threading.Lock() - self._mid_generate_mutex = threading.Lock() - self._thread: threading.Thread | None = None - self._thread_terminate = False - self._ssl = False - self._ssl_context: ssl.SSLContext | None = None - # Only used when SSL context does not have check_hostname attribute - self._tls_insecure = False - self._logger: logging.Logger | None = None - self._registered_write = False - # No default callbacks - self._on_log: CallbackOnLog | None = None - self._on_pre_connect: CallbackOnPreConnect | None = None - self._on_connect: CallbackOnConnect | None = None - self._on_connect_fail: CallbackOnConnectFail | None = None - self._on_subscribe: CallbackOnSubscribe | None = None - self._on_message: CallbackOnMessage | None = None - self._on_publish: CallbackOnPublish | None = None - self._on_unsubscribe: CallbackOnUnsubscribe | None = None - self._on_disconnect: CallbackOnDisconnect | None = None - self._on_socket_open: CallbackOnSocket | None = None - self._on_socket_close: CallbackOnSocket | None = None - self._on_socket_register_write: CallbackOnSocket | None = None - self._on_socket_unregister_write: CallbackOnSocket | None = None - self._websocket_path = "/mqtt" - self._websocket_extra_headers: WebSocketHeaders | None = None - # for clean_start == MQTT_CLEAN_START_FIRST_ONLY - self._mqttv5_first_connect = True - self.suppress_exceptions = False # For callbacks - - def __del__(self) -> None: - self._reset_sockets() - - @property - def host(self) -> str: - """ - Host to connect to. If `connect()` hasn't been called yet, returns an empty string. - - This property may not be changed if the connection is already open. - """ - return self._host - - @host.setter - def host(self, value: str) -> None: - if not self._connection_closed(): - raise RuntimeError("updating host on established connection is not supported") - - if not value: - raise ValueError("Invalid host.") - self._host = value - - @property - def port(self) -> int: - """ - Broker TCP port to connect to. - - This property may not be changed if the connection is already open. - """ - return self._port - - @port.setter - def port(self, value: int) -> None: - if not self._connection_closed(): - raise RuntimeError("updating port on established connection is not supported") - - if value <= 0: - raise ValueError("Invalid port number.") - self._port = value - - @property - def keepalive(self) -> int: - """ - Client keepalive interval (in seconds). - - This property may not be changed if the connection is already open. - """ - return self._keepalive - - @keepalive.setter - def keepalive(self, value: int) -> None: - if not self._connection_closed(): - # The issue here is that the previous value of keepalive matter to possibly - # sent ping packet. - raise RuntimeError("updating keepalive on established connection is not supported") - - if value < 0: - raise ValueError("Keepalive must be >=0.") - - self._keepalive = value - - @property - def transport(self) -> Literal["tcp", "websockets", "unix"]: - """ - Transport method used for the connection ("tcp" or "websockets"). - - This property may not be changed if the connection is already open. - """ - return self._transport - - @transport.setter - def transport(self, value: Literal["tcp", "websockets"]) -> None: - if not self._connection_closed(): - raise RuntimeError("updating transport on established connection is not supported") - - self._transport = value - - @property - def protocol(self) -> MQTTProtocolVersion: - """ - Protocol version used (MQTT v3, MQTT v3.11, MQTTv5) - - This property is read-only. - """ - return self._protocol - - @property - def connect_timeout(self) -> float: - """ - Connection establishment timeout in seconds. - - This property may not be changed if the connection is already open. - """ - return self._connect_timeout - - @connect_timeout.setter - def connect_timeout(self, value: float) -> None: - if not self._connection_closed(): - raise RuntimeError("updating connect_timeout on established connection is not supported") - - if value <= 0.0: - raise ValueError("timeout must be a positive number") - - self._connect_timeout = value - - @property - def username(self) -> str | None: - """The username used to connect to the MQTT broker, or None if no username is used. - - This property may not be changed if the connection is already open. - """ - if self._username is None: - return None - return self._username.decode("utf-8") - - @username.setter - def username(self, value: str | None) -> None: - if not self._connection_closed(): - raise RuntimeError("updating username on established connection is not supported") - - if value is None: - self._username = None - else: - self._username = value.encode("utf-8") - - @property - def password(self) -> str | None: - """The password used to connect to the MQTT broker, or None if no password is used. - - This property may not be changed if the connection is already open. - """ - if self._password is None: - return None - return self._password.decode("utf-8") - - @password.setter - def password(self, value: str | None) -> None: - if not self._connection_closed(): - raise RuntimeError("updating password on established connection is not supported") - - if value is None: - self._password = None - else: - self._password = value.encode("utf-8") - - @property - def max_inflight_messages(self) -> int: - """ - Maximum number of messages with QoS > 0 that can be partway through the network flow at once - - This property may not be changed if the connection is already open. - """ - return self._max_inflight_messages - - @max_inflight_messages.setter - def max_inflight_messages(self, value: int) -> None: - if not self._connection_closed(): - # Not tested. Some doubt that everything is okay when max_inflight change between 0 - # and > 0 value because _update_inflight is skipped when _max_inflight_messages == 0 - raise RuntimeError("updating max_inflight_messages on established connection is not supported") - - if value < 0: - raise ValueError("Invalid inflight.") - - self._max_inflight_messages = value - - @property - def max_queued_messages(self) -> int: - """ - Maximum number of message in the outgoing message queue, 0 means unlimited - - This property may not be changed if the connection is already open. - """ - return self._max_queued_messages - - @max_queued_messages.setter - def max_queued_messages(self, value: int) -> None: - if not self._connection_closed(): - # Not tested. - raise RuntimeError("updating max_queued_messages on established connection is not supported") - - if value < 0: - raise ValueError("Invalid queue size.") - - self._max_queued_messages = value - - @property - def will_topic(self) -> str | None: - """ - The topic name a will message is sent to when disconnecting unexpectedly. None if a will shall not be sent. - - This property is read-only. Use `will_set()` to change its value. - """ - if self._will_topic is None: - return None - - return self._will_topic.decode("utf-8") - - @property - def will_payload(self) -> bytes | None: - """ - The payload for the will message that is sent when disconnecting unexpectedly. None if a will shall not be sent. - - This property is read-only. Use `will_set()` to change its value. - """ - return self._will_payload - - @property - def logger(self) -> logging.Logger | None: - return self._logger - - @logger.setter - def logger(self, value: logging.Logger | None) -> None: - self._logger = value - - def _sock_recv(self, bufsize: int) -> bytes: - if self._sock is None: - raise ConnectionError("self._sock is None") - try: - return self._sock.recv(bufsize) - except ssl.SSLWantReadError as err: - raise BlockingIOError() from err - except ssl.SSLWantWriteError as err: - self._call_socket_register_write() - raise BlockingIOError() from err - except AttributeError as err: - self._easy_log( - MQTT_LOG_DEBUG, "socket was None: %s", err) - raise ConnectionError() from err - - def _sock_send(self, buf: bytes) -> int: - if self._sock is None: - raise ConnectionError("self._sock is None") - - try: - return self._sock.send(buf) - except ssl.SSLWantReadError as err: - raise BlockingIOError() from err - except ssl.SSLWantWriteError as err: - self._call_socket_register_write() - raise BlockingIOError() from err - except BlockingIOError as err: - self._call_socket_register_write() - raise BlockingIOError() from err - - def _sock_close(self) -> None: - """Close the connection to the server.""" - if not self._sock: - return - - try: - sock = self._sock - self._sock = None - self._call_socket_unregister_write(sock) - self._call_socket_close(sock) - finally: - # In case a callback fails, still close the socket to avoid leaking the file descriptor. - sock.close() - - def _reset_sockets(self, sockpair_only: bool = False) -> None: - if not sockpair_only: - self._sock_close() - - if self._sockpairR: - self._sockpairR.close() - self._sockpairR = None - if self._sockpairW: - self._sockpairW.close() - self._sockpairW = None - - def reinitialise( - self, - client_id: str = "", - clean_session: bool = True, - userdata: Any = None, - ) -> None: - self._reset_sockets() - - self.__init__(client_id, clean_session, userdata) # type: ignore[misc] - - def ws_set_options( - self, - path: str = "/mqtt", - headers: WebSocketHeaders | None = None, - ) -> None: - """ Set the path and headers for a websocket connection - - :param str path: a string starting with / which should be the endpoint of the - mqtt connection on the remote server - - :param headers: can be either a dict or a callable object. If it is a dict then - the extra items in the dict are added to the websocket headers. If it is - a callable, then the default websocket headers are passed into this - function and the result is used as the new headers. - """ - self._websocket_path = path - - if headers is not None: - if isinstance(headers, dict) or callable(headers): - self._websocket_extra_headers = headers - else: - raise ValueError( - "'headers' option to ws_set_options has to be either a dictionary or callable") - - def tls_set_context( - self, - context: ssl.SSLContext | None = None, - ) -> None: - """Configure network encryption and authentication context. Enables SSL/TLS support. - - :param context: an ssl.SSLContext object. By default this is given by - ``ssl.create_default_context()``, if available. - - Must be called before `connect()`, `connect_async()` or `connect_srv()`.""" - if self._ssl_context is not None: - raise ValueError('SSL/TLS has already been configured.') - - if context is None: - context = ssl.create_default_context() - - self._ssl = True - self._ssl_context = context - - # Ensure _tls_insecure is consistent with check_hostname attribute - if hasattr(context, 'check_hostname'): - self._tls_insecure = not context.check_hostname - - def tls_set( - self, - ca_certs: str | None = None, - certfile: str | None = None, - keyfile: str | None = None, - cert_reqs: ssl.VerifyMode | None = None, - tls_version: int | None = None, - ciphers: str | None = None, - keyfile_password: str | None = None, - alpn_protocols: list[str] | None = None, - ) -> None: - """Configure network encryption and authentication options. Enables SSL/TLS support. - - :param str ca_certs: a string path to the Certificate Authority certificate files - that are to be treated as trusted by this client. If this is the only - option given then the client will operate in a similar manner to a web - browser. That is to say it will require the broker to have a - certificate signed by the Certificate Authorities in ca_certs and will - communicate using TLS v1,2, but will not attempt any form of - authentication. This provides basic network encryption but may not be - sufficient depending on how the broker is configured. - - By default, on Python 2.7.9+ or 3.4+, the default certification - authority of the system is used. On older Python version this parameter - is mandatory. - :param str certfile: PEM encoded client certificate filename. Used with - keyfile for client TLS based authentication. Support for this feature is - broker dependent. Note that if the files in encrypted and needs a password to - decrypt it, then this can be passed using the keyfile_password argument - you - should take precautions to ensure that your password is - not hard coded into your program by loading the password from a file - for example. If you do not provide keyfile_password, the password will - be requested to be typed in at a terminal window. - :param str keyfile: PEM encoded client private keys filename. Used with - certfile for client TLS based authentication. Support for this feature is - broker dependent. Note that if the files in encrypted and needs a password to - decrypt it, then this can be passed using the keyfile_password argument - you - should take precautions to ensure that your password is - not hard coded into your program by loading the password from a file - for example. If you do not provide keyfile_password, the password will - be requested to be typed in at a terminal window. - :param cert_reqs: the certificate requirements that the client imposes - on the broker to be changed. By default this is ssl.CERT_REQUIRED, - which means that the broker must provide a certificate. See the ssl - pydoc for more information on this parameter. - :param tls_version: the version of the SSL/TLS protocol used to be - specified. By default TLS v1.2 is used. Previous versions are allowed - but not recommended due to possible security problems. - :param str ciphers: encryption ciphers that are allowed - for this connection, or None to use the defaults. See the ssl pydoc for - more information. - - Must be called before `connect()`, `connect_async()` or `connect_srv()`.""" - if ssl is None: - raise ValueError('This platform has no SSL/TLS.') - - if not hasattr(ssl, 'SSLContext'): - # Require Python version that has SSL context support in standard library - raise ValueError( - 'Python 2.7.9 and 3.2 are the minimum supported versions for TLS.') - - if ca_certs is None and not hasattr(ssl.SSLContext, 'load_default_certs'): - raise ValueError('ca_certs must not be None.') - - # Create SSLContext object - if tls_version is None: - tls_version = ssl.PROTOCOL_TLSv1_2 - # If the python version supports it, use highest TLS version automatically - if hasattr(ssl, "PROTOCOL_TLS_CLIENT"): - # This also enables CERT_REQUIRED and check_hostname by default. - tls_version = ssl.PROTOCOL_TLS_CLIENT - elif hasattr(ssl, "PROTOCOL_TLS"): - tls_version = ssl.PROTOCOL_TLS - context = ssl.SSLContext(tls_version) - - # Configure context - if ciphers is not None: - context.set_ciphers(ciphers) - - if certfile is not None: - context.load_cert_chain(certfile, keyfile, keyfile_password) - - if cert_reqs == ssl.CERT_NONE and hasattr(context, 'check_hostname'): - context.check_hostname = False - - context.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs - - if ca_certs is not None: - context.load_verify_locations(ca_certs) - else: - context.load_default_certs() - - if alpn_protocols is not None: - if not getattr(ssl, "HAS_ALPN", None): - raise ValueError("SSL library has no support for ALPN") - context.set_alpn_protocols(alpn_protocols) - - self.tls_set_context(context) - - if cert_reqs != ssl.CERT_NONE: - # Default to secure, sets context.check_hostname attribute - # if available - self.tls_insecure_set(False) - else: - # But with ssl.CERT_NONE, we can not check_hostname - self.tls_insecure_set(True) - - def tls_insecure_set(self, value: bool) -> None: - """Configure verification of the server hostname in the server certificate. - - If value is set to true, it is impossible to guarantee that the host - you are connecting to is not impersonating your server. This can be - useful in initial server testing, but makes it possible for a malicious - third party to impersonate your server through DNS spoofing, for - example. - - Do not use this function in a real system. Setting value to true means - there is no point using encryption. - - Must be called before `connect()` and after either `tls_set()` or - `tls_set_context()`.""" - - if self._ssl_context is None: - raise ValueError( - 'Must configure SSL context before using tls_insecure_set.') - - self._tls_insecure = value - - # Ensure check_hostname is consistent with _tls_insecure attribute - if hasattr(self._ssl_context, 'check_hostname'): - # Rely on SSLContext to check host name - # If verify_mode is CERT_NONE then the host name will never be checked - self._ssl_context.check_hostname = not value - - def proxy_set(self, **proxy_args: Any) -> None: - """Configure proxying of MQTT connection. Enables support for SOCKS or - HTTP proxies. - - Proxying is done through the PySocks library. Brief descriptions of the - proxy_args parameters are below; see the PySocks docs for more info. - - (Required) - - :param proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5} - :param proxy_addr: IP address or DNS name of proxy server - - (Optional) - - :param proxy_port: (int) port number of the proxy server. If not provided, - the PySocks package default value will be utilized, which differs by proxy_type. - :param proxy_rdns: boolean indicating whether proxy lookup should be performed - remotely (True, default) or locally (False) - :param proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy - :param proxy_password: password for SOCKS5 proxy - - Example:: - - mqttc.proxy_set(proxy_type=socks.HTTP, proxy_addr='1.2.3.4', proxy_port=4231) - """ - if socks is None: - raise ValueError("PySocks must be installed for proxy support.") - elif not self._proxy_is_valid(proxy_args): - raise ValueError("proxy_type and/or proxy_addr are invalid.") - else: - self._proxy = proxy_args - - def enable_logger(self, logger: logging.Logger | None = None) -> None: - """ - Enables a logger to send log messages to - - :param logging.Logger logger: if specified, that ``logging.Logger`` object will be used, otherwise - one will be created automatically. - - See `disable_logger` to undo this action. - """ - if logger is None: - if self._logger is not None: - # Do not replace existing logger - return - logger = logging.getLogger(__name__) - self.logger = logger - - def disable_logger(self) -> None: - """ - Disable logging using standard python logging package. This has no effect on the `on_log` callback. - """ - self._logger = None - - def connect( - self, - host: str, - port: int = 1883, - keepalive: int = 60, - bind_address: str = "", - bind_port: int = 0, - clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, - properties: Properties | None = None, - ) -> MQTTErrorCode: - """Connect to a remote broker. This is a blocking call that establishes - the underlying connection and transmits a CONNECT packet. - Note that the connection status will not be updated until a CONNACK is received and - processed (this requires a running network loop, see `loop_start`, `loop_forever`, `loop`...). - - :param str host: the hostname or IP address of the remote broker. - :param int port: the network port of the server host to connect to. Defaults to - 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you - are using `tls_set()` the port may need providing. - :param int keepalive: Maximum period in seconds between communications with the - broker. If no other messages are being exchanged, this controls the - rate at which the client will send ping messages to the broker. - :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. - Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, - respectively. MQTT session data (such as outstanding messages and subscriptions) - is cleared on successful connect when the clean_start flag is set. - For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar - result. - :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the - MQTT connect packet. - """ - - if self._protocol == MQTTv5: - self._mqttv5_first_connect = True - else: - if clean_start != MQTT_CLEAN_START_FIRST_ONLY: - raise ValueError("Clean start only applies to MQTT V5") - if properties: - raise ValueError("Properties only apply to MQTT V5") - - self.connect_async(host, port, keepalive, - bind_address, bind_port, clean_start, properties) - return self.reconnect() - - def connect_srv( - self, - domain: str | None = None, - keepalive: int = 60, - bind_address: str = "", - bind_port: int = 0, - clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, - properties: Properties | None = None, - ) -> MQTTErrorCode: - """Connect to a remote broker. - - :param str domain: the DNS domain to search for SRV records; if None, - try to determine local domain name. - :param keepalive, bind_address, clean_start and properties: see `connect()` - """ - - if HAVE_DNS is False: - raise ValueError( - 'No DNS resolver library found, try "pip install dnspython".') - - if domain is None: - domain = socket.getfqdn() - domain = domain[domain.find('.') + 1:] - - try: - rr = f'_mqtt._tcp.{domain}' - if self._ssl: - # IANA specifies secure-mqtt (not mqtts) for port 8883 - rr = f'_secure-mqtt._tcp.{domain}' - answers = [] - for answer in dns.resolver.query(rr, dns.rdatatype.SRV): - addr = answer.target.to_text()[:-1] - answers.append( - (addr, answer.port, answer.priority, answer.weight)) - except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers) as err: - raise ValueError(f"No answer/NXDOMAIN for SRV in {domain}") from err - - # FIXME: doesn't account for weight - for answer in answers: - host, port, prio, weight = answer - - try: - return self.connect(host, port, keepalive, bind_address, bind_port, clean_start, properties) - except Exception: # noqa: S110 - pass - - raise ValueError("No SRV hosts responded") - - def connect_async( - self, - host: str, - port: int = 1883, - keepalive: int = 60, - bind_address: str = "", - bind_port: int = 0, - clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY, - properties: Properties | None = None, - ) -> None: - """Connect to a remote broker asynchronously. This is a non-blocking - connect call that can be used with `loop_start()` to provide very quick - start. - - Any already established connection will be terminated immediately. - - :param str host: the hostname or IP address of the remote broker. - :param int port: the network port of the server host to connect to. Defaults to - 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you - are using `tls_set()` the port may need providing. - :param int keepalive: Maximum period in seconds between communications with the - broker. If no other messages are being exchanged, this controls the - rate at which the client will send ping messages to the broker. - :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. - Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, - respectively. MQTT session data (such as outstanding messages and subscriptions) - is cleared on successful connect when the clean_start flag is set. - For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar - result. - :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the - MQTT connect packet. - """ - if bind_port < 0: - raise ValueError('Invalid bind port number.') - - # Switch to state NEW to allow update of host, port & co. - self._sock_close() - self._state = _ConnectionState.MQTT_CS_NEW - - self.host = host - self.port = port - self.keepalive = keepalive - self._bind_address = bind_address - self._bind_port = bind_port - self._clean_start = clean_start - self._connect_properties = properties - self._state = _ConnectionState.MQTT_CS_CONNECT_ASYNC - - def reconnect_delay_set(self, min_delay: int = 1, max_delay: int = 120) -> None: - """ Configure the exponential reconnect delay - - When connection is lost, wait initially min_delay seconds and - double this time every attempt. The wait is capped at max_delay. - Once the client is fully connected (e.g. not only TCP socket, but - received a success CONNACK), the wait timer is reset to min_delay. - """ - with self._reconnect_delay_mutex: - self._reconnect_min_delay = min_delay - self._reconnect_max_delay = max_delay - self._reconnect_delay = None - - def reconnect(self) -> MQTTErrorCode: - """Reconnect the client after a disconnect. Can only be called after - connect()/connect_async().""" - if len(self._host) == 0: - raise ValueError('Invalid host.') - if self._port <= 0: - raise ValueError('Invalid port number.') - - self._in_packet = { - "command": 0, - "have_remaining": 0, - "remaining_count": [], - "remaining_mult": 1, - "remaining_length": 0, - "packet": bytearray(b""), - "to_process": 0, - "pos": 0, - } - - self._ping_t = 0.0 - self._state = _ConnectionState.MQTT_CS_CONNECTING - - self._sock_close() - - # Mark all currently outgoing QoS = 0 packets as lost, - # or `wait_for_publish()` could hang forever - for pkt in self._out_packet: - if pkt["command"] & 0xF0 == PUBLISH and pkt["qos"] == 0 and pkt["info"] is not None: - pkt["info"].rc = MQTT_ERR_CONN_LOST - pkt["info"]._set_as_published() - - self._out_packet.clear() - - with self._msgtime_mutex: - self._last_msg_in = time_func() - self._last_msg_out = time_func() - - # Put messages in progress in a valid state. - self._messages_reconnect_reset() - - with self._callback_mutex: - on_pre_connect = self.on_pre_connect - - if on_pre_connect: - try: - on_pre_connect(self, self._userdata) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_pre_connect: %s', err) - if not self.suppress_exceptions: - raise - - self._sock = self._create_socket() - - self._sock.setblocking(False) # type: ignore[attr-defined] - self._registered_write = False - self._call_socket_open(self._sock) - - return self._send_connect(self._keepalive) - - def loop(self, timeout: float = 1.0) -> MQTTErrorCode: - """Process network events. - - It is strongly recommended that you use `loop_start()`, or - `loop_forever()`, or if you are using an external event loop using - `loop_read()`, `loop_write()`, and `loop_misc()`. Using loop() on it's own is - no longer recommended. - - This function must be called regularly to ensure communication with the - broker is carried out. It calls select() on the network socket to wait - for network events. If incoming data is present it will then be - processed. Outgoing commands, from e.g. `publish()`, are normally sent - immediately that their function is called, but this is not always - possible. loop() will also attempt to send any remaining outgoing - messages, which also includes commands that are part of the flow for - messages with QoS>0. - - :param int timeout: The time in seconds to wait for incoming/outgoing network - traffic before timing out and returning. - - Returns MQTT_ERR_SUCCESS on success. - Returns >0 on error. - - A ValueError will be raised if timeout < 0""" - - if self._sockpairR is None or self._sockpairW is None: - self._reset_sockets(sockpair_only=True) - self._sockpairR, self._sockpairW = _socketpair_compat() - - return self._loop(timeout) - - def _loop(self, timeout: float = 1.0) -> MQTTErrorCode: - if timeout < 0.0: - raise ValueError('Invalid timeout.') - - if self.want_write(): - wlist = [self._sock] - else: - wlist = [] - - # used to check if there are any bytes left in the (SSL) socket - pending_bytes = 0 - if hasattr(self._sock, 'pending'): - pending_bytes = self._sock.pending() # type: ignore[union-attr] - - # if bytes are pending do not wait in select - if pending_bytes > 0: - timeout = 0.0 - - # sockpairR is used to break out of select() before the timeout, on a - # call to publish() etc. - if self._sockpairR is None: - rlist = [self._sock] - else: - rlist = [self._sock, self._sockpairR] - - try: - socklist = select.select(rlist, wlist, [], timeout) - except TypeError: - # Socket isn't correct type, in likelihood connection is lost - # ... or we called disconnect(). In that case the socket will - # be closed but some loop (like loop_forever) will continue to - # call _loop(). We still want to break that loop by returning an - # rc != MQTT_ERR_SUCCESS and we don't want state to change from - # mqtt_cs_disconnecting. - if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): - self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST - return MQTTErrorCode.MQTT_ERR_CONN_LOST - except ValueError: - # Can occur if we just reconnected but rlist/wlist contain a -1 for - # some reason. - if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): - self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST - return MQTTErrorCode.MQTT_ERR_CONN_LOST - except Exception: - # Note that KeyboardInterrupt, etc. can still terminate since they - # are not derived from Exception - return MQTTErrorCode.MQTT_ERR_UNKNOWN - - if self._sock in socklist[0] or pending_bytes > 0: - rc = self.loop_read() - if rc or self._sock is None: - return rc - - if self._sockpairR and self._sockpairR in socklist[0]: - # Stimulate output write even though we didn't ask for it, because - # at that point the publish or other command wasn't present. - socklist[1].insert(0, self._sock) - # Clear sockpairR - only ever a single byte written. - try: - # Read many bytes at once - this allows up to 10000 calls to - # publish() inbetween calls to loop(). - self._sockpairR.recv(10000) - except BlockingIOError: - pass - - if self._sock in socklist[1]: - rc = self.loop_write() - if rc or self._sock is None: - return rc - - return self.loop_misc() - - def publish( - self, - topic: str, - payload: PayloadType = None, - qos: int = 0, - retain: bool = False, - properties: Properties | None = None, - ) -> MQTTMessageInfo: - """Publish a message on a topic. - - This causes a message to be sent to the broker and subsequently from - the broker to any clients subscribing to matching topics. - - :param str topic: The topic that the message should be published on. - :param payload: The actual message to send. If not given, or set to None a - zero length message will be used. Passing an int or float will result - in the payload being converted to a string representing that number. If - you wish to send a true int/float, use struct.pack() to create the - payload you require. - :param int qos: The quality of service level to use. - :param bool retain: If set to true, the message will be set as the "last known - good"/retained message for the topic. - :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included. - - Returns a `MQTTMessageInfo` class, which can be used to determine whether - the message has been delivered (using `is_published()`) or to block - waiting for the message to be delivered (`wait_for_publish()`). The - message ID and return code of the publish() call can be found at - :py:attr:`info.mid ` and :py:attr:`info.rc `. - - For backwards compatibility, the `MQTTMessageInfo` class is iterable so - the old construct of ``(rc, mid) = client.publish(...)`` is still valid. - - rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the - client is not currently connected. mid is the message ID for the - publish request. The mid value can be used to track the publish request - by checking against the mid argument in the on_publish() callback if it - is defined. - - :raises ValueError: if topic is None, has zero length or is - invalid (contains a wildcard), except if the MQTT version used is v5.0. - For v5.0, a zero length topic can be used when a Topic Alias has been set. - :raises ValueError: if qos is not one of 0, 1 or 2 - :raises ValueError: if the length of the payload is greater than 268435455 bytes. - """ - if self._protocol != MQTTv5: - if topic is None or len(topic) == 0: - raise ValueError('Invalid topic.') - - topic_bytes = topic.encode('utf-8') - - self._raise_for_invalid_topic(topic_bytes) - - if qos < 0 or qos > 2: - raise ValueError('Invalid QoS level.') - - local_payload = _encode_payload(payload) - - if len(local_payload) > 268435455: - raise ValueError('Payload too large.') - - local_mid = self._mid_generate() - - if qos == 0: - info = MQTTMessageInfo(local_mid) - rc = self._send_publish( - local_mid, topic_bytes, local_payload, qos, retain, False, info, properties) - info.rc = rc - return info - else: - message = MQTTMessage(local_mid, topic_bytes) - message.timestamp = time_func() - message.payload = local_payload - message.qos = qos - message.retain = retain - message.dup = False - message.properties = properties - - with self._out_message_mutex: - if self._max_queued_messages > 0 and len(self._out_messages) >= self._max_queued_messages: - message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE - return message.info - - if local_mid in self._out_messages: - message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE - return message.info - - self._out_messages[message.mid] = message - if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages: - self._inflight_messages += 1 - if qos == 1: - message.state = mqtt_ms_wait_for_puback - elif qos == 2: - message.state = mqtt_ms_wait_for_pubrec - - rc = self._send_publish(message.mid, topic_bytes, message.payload, message.qos, message.retain, - message.dup, message.info, message.properties) - - # remove from inflight messages so it will be send after a connection is made - if rc == MQTTErrorCode.MQTT_ERR_NO_CONN: - self._inflight_messages -= 1 - message.state = mqtt_ms_publish - - message.info.rc = rc - return message.info - else: - message.state = mqtt_ms_queued - message.info.rc = MQTTErrorCode.MQTT_ERR_SUCCESS - return message.info - - def username_pw_set( - self, username: str | None, password: str | None = None - ) -> None: - """Set a username and optionally a password for broker authentication. - - Must be called before connect() to have any effect. - Requires a broker that supports MQTT v3.1 or more. - - :param str username: The username to authenticate with. Need have no relationship to the client id. Must be str - [MQTT-3.1.3-11]. - Set to None to reset client back to not using username/password for broker authentication. - :param str password: The password to authenticate with. Optional, set to None if not required. If it is str, then it - will be encoded as UTF-8. - """ - - # [MQTT-3.1.3-11] User name must be UTF-8 encoded string - self._username = None if username is None else username.encode('utf-8') - if isinstance(password, str): - self._password = password.encode('utf-8') - else: - self._password = password - - def enable_bridge_mode(self) -> None: - """Sets the client in a bridge mode instead of client mode. - - Must be called before `connect()` to have any effect. - Requires brokers that support bridge mode. - - Under bridge mode, the broker will identify the client as a bridge and - not send it's own messages back to it. Hence a subsciption of # is - possible without message loops. This feature also correctly propagates - the retain flag on the messages. - - Currently Mosquitto and RSMB support this feature. This feature can - be used to create a bridge between multiple broker. - """ - self._client_mode = MQTT_BRIDGE - - def _connection_closed(self) -> bool: - """ - Return true if the connection is closed (and not trying to be opened). - """ - return ( - self._state == _ConnectionState.MQTT_CS_NEW - or (self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) and self._sock is None)) - - def is_connected(self) -> bool: - """Returns the current status of the connection - - True if connection exists - False if connection is closed - """ - return self._state == _ConnectionState.MQTT_CS_CONNECTED - - def disconnect( - self, - reasoncode: ReasonCode | None = None, - properties: Properties | None = None, - ) -> MQTTErrorCode: - """Disconnect a connected client from the broker. - - :param ReasonCode reasoncode: (MQTT v5.0 only) a ReasonCode instance setting the MQTT v5.0 - reasoncode to be sent with the disconnect packet. It is optional, the receiver - then assuming that 0 (success) is the value. - :param Properties properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties - to be included. Optional - if not set, no properties are sent. - """ - if self._sock is None: - self._state = _ConnectionState.MQTT_CS_DISCONNECTED - return MQTT_ERR_NO_CONN - else: - self._state = _ConnectionState.MQTT_CS_DISCONNECTING - - return self._send_disconnect(reasoncode, properties) - - def subscribe( - self, - topic: str | tuple[str, int] | tuple[str, SubscribeOptions] | list[tuple[str, int]] | list[tuple[str, SubscribeOptions]], - qos: int = 0, - options: SubscribeOptions | None = None, - properties: Properties | None = None, - ) -> tuple[MQTTErrorCode, int | None]: - """Subscribe the client to one or more topics. - - This function may be called in three different ways (and a further three for MQTT v5.0): - - Simple string and integer - ------------------------- - e.g. subscribe("my/topic", 2) - - :topic: A string specifying the subscription topic to subscribe to. - :qos: The desired quality of service level for the subscription. - Defaults to 0. - :options and properties: Not used. - - Simple string and subscribe options (MQTT v5.0 only) - ---------------------------------------------------- - e.g. subscribe("my/topic", options=SubscribeOptions(qos=2)) - - :topic: A string specifying the subscription topic to subscribe to. - :qos: Not used. - :options: The MQTT v5.0 subscribe options. - :properties: a Properties instance setting the MQTT v5.0 properties - to be included. Optional - if not set, no properties are sent. - - String and integer tuple - ------------------------ - e.g. subscribe(("my/topic", 1)) - - :topic: A tuple of (topic, qos). Both topic and qos must be present in - the tuple. - :qos and options: Not used. - :properties: Only used for MQTT v5.0. A Properties instance setting the - MQTT v5.0 properties. Optional - if not set, no properties are sent. - - String and subscribe options tuple (MQTT v5.0 only) - --------------------------------------------------- - e.g. subscribe(("my/topic", SubscribeOptions(qos=1))) - - :topic: A tuple of (topic, SubscribeOptions). Both topic and subscribe - options must be present in the tuple. - :qos and options: Not used. - :properties: a Properties instance setting the MQTT v5.0 properties - to be included. Optional - if not set, no properties are sent. - - List of string and integer tuples - --------------------------------- - e.g. subscribe([("my/topic", 0), ("another/topic", 2)]) - - This allows multiple topic subscriptions in a single SUBSCRIPTION - command, which is more efficient than using multiple calls to - subscribe(). - - :topic: A list of tuple of format (topic, qos). Both topic and qos must - be present in all of the tuples. - :qos, options and properties: Not used. - - List of string and subscribe option tuples (MQTT v5.0 only) - ----------------------------------------------------------- - e.g. subscribe([("my/topic", SubscribeOptions(qos=0), ("another/topic", SubscribeOptions(qos=2)]) - - This allows multiple topic subscriptions in a single SUBSCRIPTION - command, which is more efficient than using multiple calls to - subscribe(). - - :topic: A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe - options must be present in all of the tuples. - :qos and options: Not used. - :properties: a Properties instance setting the MQTT v5.0 properties - to be included. Optional - if not set, no properties are sent. - - The function returns a tuple (result, mid), where result is - MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the - client is not currently connected. mid is the message ID for the - subscribe request. The mid value can be used to track the subscribe - request by checking against the mid argument in the on_subscribe() - callback if it is defined. - - Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has - zero string length, or if topic is not a string, tuple or list. - """ - topic_qos_list = None - - if isinstance(topic, tuple): - if self._protocol == MQTTv5: - topic, options = topic # type: ignore - if not isinstance(options, SubscribeOptions): - raise ValueError( - 'Subscribe options must be instance of SubscribeOptions class.') - else: - topic, qos = topic # type: ignore - - if isinstance(topic, (bytes, str)): - if qos < 0 or qos > 2: - raise ValueError('Invalid QoS level.') - if self._protocol == MQTTv5: - if options is None: - # if no options are provided, use the QoS passed instead - options = SubscribeOptions(qos=qos) - elif qos != 0: - raise ValueError( - 'Subscribe options and qos parameters cannot be combined.') - if not isinstance(options, SubscribeOptions): - raise ValueError( - 'Subscribe options must be instance of SubscribeOptions class.') - topic_qos_list = [(topic.encode('utf-8'), options)] - else: - if topic is None or len(topic) == 0: - raise ValueError('Invalid topic.') - topic_qos_list = [(topic.encode('utf-8'), qos)] # type: ignore - elif isinstance(topic, list): - if len(topic) == 0: - raise ValueError('Empty topic list') - topic_qos_list = [] - if self._protocol == MQTTv5: - for t, o in topic: - if not isinstance(o, SubscribeOptions): - # then the second value should be QoS - if o < 0 or o > 2: - raise ValueError('Invalid QoS level.') - o = SubscribeOptions(qos=o) - topic_qos_list.append((t.encode('utf-8'), o)) - else: - for t, q in topic: - if isinstance(q, SubscribeOptions) or q < 0 or q > 2: - raise ValueError('Invalid QoS level.') - if t is None or len(t) == 0 or not isinstance(t, (bytes, str)): - raise ValueError('Invalid topic.') - topic_qos_list.append((t.encode('utf-8'), q)) # type: ignore - - if topic_qos_list is None: - raise ValueError("No topic specified, or incorrect topic type.") - - if any(self._filter_wildcard_len_check(topic) != MQTT_ERR_SUCCESS for topic, _ in topic_qos_list): - raise ValueError('Invalid subscription filter.') - - if self._sock is None: - return (MQTT_ERR_NO_CONN, None) - - return self._send_subscribe(False, topic_qos_list, properties) - - def unsubscribe( - self, topic: str | list[str], properties: Properties | None = None - ) -> tuple[MQTTErrorCode, int | None]: - """Unsubscribe the client from one or more topics. - - :param topic: A single string, or list of strings that are the subscription - topics to unsubscribe from. - :param properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties - to be included. Optional - if not set, no properties are sent. - - Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS - to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not - currently connected. - mid is the message ID for the unsubscribe request. The mid value can be - used to track the unsubscribe request by checking against the mid - argument in the on_unsubscribe() callback if it is defined. - - :raises ValueError: if topic is None or has zero string length, or is - not a string or list. - """ - topic_list = None - if topic is None: - raise ValueError('Invalid topic.') - if isinstance(topic, (bytes, str)): - if len(topic) == 0: - raise ValueError('Invalid topic.') - topic_list = [topic.encode('utf-8')] - elif isinstance(topic, list): - topic_list = [] - for t in topic: - if len(t) == 0 or not isinstance(t, (bytes, str)): - raise ValueError('Invalid topic.') - topic_list.append(t.encode('utf-8')) - - if topic_list is None: - raise ValueError("No topic specified, or incorrect topic type.") - - if self._sock is None: - return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) - - return self._send_unsubscribe(False, topic_list, properties) - - def loop_read(self, max_packets: int = 1) -> MQTTErrorCode: - """Process read network events. Use in place of calling `loop()` if you - wish to handle your client reads as part of your own application. - - Use `socket()` to obtain the client socket to call select() or equivalent - on. - - Do not use if you are using `loop_start()` or `loop_forever()`.""" - if self._sock is None: - return MQTTErrorCode.MQTT_ERR_NO_CONN - - max_packets = len(self._out_messages) + len(self._in_messages) - if max_packets < 1: - max_packets = 1 - - for _ in range(0, max_packets): - if self._sock is None: - return MQTTErrorCode.MQTT_ERR_NO_CONN - rc = self._packet_read() - if rc > 0: - return self._loop_rc_handle(rc) - elif rc == MQTTErrorCode.MQTT_ERR_AGAIN: - return MQTTErrorCode.MQTT_ERR_SUCCESS - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def loop_write(self) -> MQTTErrorCode: - """Process write network events. Use in place of calling `loop()` if you - wish to handle your client writes as part of your own application. - - Use `socket()` to obtain the client socket to call select() or equivalent - on. - - Use `want_write()` to determine if there is data waiting to be written. - - Do not use if you are using `loop_start()` or `loop_forever()`.""" - if self._sock is None: - return MQTTErrorCode.MQTT_ERR_NO_CONN - - try: - rc = self._packet_write() - if rc == MQTTErrorCode.MQTT_ERR_AGAIN: - return MQTTErrorCode.MQTT_ERR_SUCCESS - elif rc > 0: - return self._loop_rc_handle(rc) - else: - return MQTTErrorCode.MQTT_ERR_SUCCESS - finally: - if self.want_write(): - self._call_socket_register_write() - else: - self._call_socket_unregister_write() - - def want_write(self) -> bool: - """Call to determine if there is network data waiting to be written. - Useful if you are calling select() yourself rather than using `loop()`, `loop_start()` or `loop_forever()`. - """ - return len(self._out_packet) > 0 - - def loop_misc(self) -> MQTTErrorCode: - """Process miscellaneous network events. Use in place of calling `loop()` if you - wish to call select() or equivalent on. - - Do not use if you are using `loop_start()` or `loop_forever()`.""" - if self._sock is None: - return MQTTErrorCode.MQTT_ERR_NO_CONN - - now = time_func() - self._check_keepalive() - - if self._ping_t > 0 and now - self._ping_t >= self._keepalive: - # client->ping_t != 0 means we are waiting for a pingresp. - # This hasn't happened in the keepalive time so we should disconnect. - self._sock_close() - - if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): - self._state = _ConnectionState.MQTT_CS_DISCONNECTED - rc = MQTTErrorCode.MQTT_ERR_SUCCESS - else: - self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST - rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE - - self._do_on_disconnect( - packet_from_broker=False, - v1_rc=rc, - ) - - return MQTTErrorCode.MQTT_ERR_CONN_LOST - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def max_inflight_messages_set(self, inflight: int) -> None: - """Set the maximum number of messages with QoS>0 that can be part way - through their network flow at once. Defaults to 20.""" - self.max_inflight_messages = inflight - - def max_queued_messages_set(self, queue_size: int) -> Client: - """Set the maximum number of messages in the outgoing message queue. - 0 means unlimited.""" - if not isinstance(queue_size, int): - raise ValueError('Invalid type of queue size.') - self.max_queued_messages = queue_size - return self - - def user_data_set(self, userdata: Any) -> None: - """Set the user data variable passed to callbacks. May be any data type.""" - self._userdata = userdata - - def user_data_get(self) -> Any: - """Get the user data variable passed to callbacks. May be any data type.""" - return self._userdata - - def will_set( - self, - topic: str, - payload: PayloadType = None, - qos: int = 0, - retain: bool = False, - properties: Properties | None = None, - ) -> None: - """Set a Will to be sent by the broker in case the client disconnects unexpectedly. - - This must be called before connect() to have any effect. - - :param str topic: The topic that the will message should be published on. - :param payload: The message to send as a will. If not given, or set to None a - zero length message will be used as the will. Passing an int or float - will result in the payload being converted to a string representing - that number. If you wish to send a true int/float, use struct.pack() to - create the payload you require. - :param int qos: The quality of service level to use for the will. - :param bool retain: If set to true, the will message will be set as the "last known - good"/retained message for the topic. - :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties - to be included with the will message. Optional - if not set, no properties are sent. - - :raises ValueError: if qos is not 0, 1 or 2, or if topic is None or has - zero string length. - - See `will_clear` to clear will. Note that will are NOT send if the client disconnect cleanly - for example by calling `disconnect()`. - """ - if topic is None or len(topic) == 0: - raise ValueError('Invalid topic.') - - if qos < 0 or qos > 2: - raise ValueError('Invalid QoS level.') - - if properties and not isinstance(properties, Properties): - raise ValueError( - "The properties argument must be an instance of the Properties class.") - - self._will_payload = _encode_payload(payload) - self._will = True - self._will_topic = topic.encode('utf-8') - self._will_qos = qos - self._will_retain = retain - self._will_properties = properties - - def will_clear(self) -> None: - """ Removes a will that was previously configured with `will_set()`. - - Must be called before connect() to have any effect.""" - self._will = False - self._will_topic = b"" - self._will_payload = b"" - self._will_qos = 0 - self._will_retain = False - - def socket(self) -> SocketLike | None: - """Return the socket or ssl object for this client.""" - return self._sock - - def loop_forever( - self, - timeout: float = 1.0, - retry_first_connection: bool = False, - ) -> MQTTErrorCode: - """This function calls the network loop functions for you in an - infinite blocking loop. It is useful for the case where you only want - to run the MQTT client loop in your program. - - loop_forever() will handle reconnecting for you if reconnect_on_failure is - true (this is the default behavior). If you call `disconnect()` in a callback - it will return. - - :param int timeout: The time in seconds to wait for incoming/outgoing network - traffic before timing out and returning. - :param bool retry_first_connection: Should the first connection attempt be retried on failure. - This is independent of the reconnect_on_failure setting. - - :raises OSError: if the first connection fail unless retry_first_connection=True - """ - - run = True - - while run: - if self._thread_terminate is True: - break - - if self._state == _ConnectionState.MQTT_CS_CONNECT_ASYNC: - try: - self.reconnect() - except OSError: - self._handle_on_connect_fail() - if not retry_first_connection: - raise - self._easy_log( - MQTT_LOG_DEBUG, "Connection failed, retrying") - self._reconnect_wait() - else: - break - - while run: - rc = MQTTErrorCode.MQTT_ERR_SUCCESS - while rc == MQTTErrorCode.MQTT_ERR_SUCCESS: - rc = self._loop(timeout) - # We don't need to worry about locking here, because we've - # either called loop_forever() when in single threaded mode, or - # in multi threaded mode when loop_stop() has been called and - # so no other threads can access _out_packet or _messages. - if (self._thread_terminate is True - and len(self._out_packet) == 0 - and len(self._out_messages) == 0): - rc = MQTTErrorCode.MQTT_ERR_NOMEM - run = False - - def should_exit() -> bool: - return ( - self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) or - run is False or # noqa: B023 (uses the run variable from the outer scope on purpose) - self._thread_terminate is True - ) - - if should_exit() or not self._reconnect_on_failure: - run = False - else: - self._reconnect_wait() - - if should_exit(): - run = False - else: - try: - self.reconnect() - except OSError: - self._handle_on_connect_fail() - self._easy_log( - MQTT_LOG_DEBUG, "Connection failed, retrying") - - return rc - - def loop_start(self) -> MQTTErrorCode: - """This is part of the threaded client interface. Call this once to - start a new thread to process network traffic. This provides an - alternative to repeatedly calling `loop()` yourself. - - Under the hood, this will call `loop_forever` in a thread, which means that - the thread will terminate if you call `disconnect()` - """ - if self._thread is not None: - return MQTTErrorCode.MQTT_ERR_INVAL - - self._sockpairR, self._sockpairW = _socketpair_compat() - self._thread_terminate = False - self._thread = threading.Thread(target=self._thread_main, name=f"paho-mqtt-client-{self._client_id.decode()}") - self._thread.daemon = True - self._thread.start() - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def loop_stop(self) -> MQTTErrorCode: - """This is part of the threaded client interface. Call this once to - stop the network thread previously created with `loop_start()`. This call - will block until the network thread finishes. - - This don't guarantee that publish packet are sent, use `wait_for_publish` or - `on_publish` to ensure `publish` are sent. - """ - if self._thread is None: - return MQTTErrorCode.MQTT_ERR_INVAL - - self._thread_terminate = True - if threading.current_thread() != self._thread: - self._thread.join() - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - @property - def callback_api_version(self) -> CallbackAPIVersion: - """ - Return the callback API version used for user-callback. See docstring for - each user-callback (`on_connect`, `on_publish`, ...) for details. - - This property is read-only. - """ - return self._callback_api_version - - @property - def on_log(self) -> CallbackOnLog | None: - """The callback called when the client has log information. - Defined to allow debugging. - - Expected signature is:: - - log_callback(client, userdata, level, buf) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param int level: gives the severity of the message and will be one of - MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, - MQTT_LOG_ERR, and MQTT_LOG_DEBUG. - :param str buf: the message itself - - Decorator: @client.log_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_log - - @on_log.setter - def on_log(self, func: CallbackOnLog | None) -> None: - self._on_log = func - - def log_callback(self) -> Callable[[CallbackOnLog], CallbackOnLog]: - def decorator(func: CallbackOnLog) -> CallbackOnLog: - self.on_log = func - return func - return decorator - - @property - def on_pre_connect(self) -> CallbackOnPreConnect | None: - """The callback called immediately prior to the connection is made - request. - - Expected signature (for all callback API version):: - - connect_callback(client, userdata) - - :parama Client client: the client instance for this callback - :parama userdata: the private user data as set in Client() or user_data_set() - - Decorator: @client.pre_connect_callback() (``client`` is the name of the - instance which this callback is being attached to) - - """ - return self._on_pre_connect - - @on_pre_connect.setter - def on_pre_connect(self, func: CallbackOnPreConnect | None) -> None: - with self._callback_mutex: - self._on_pre_connect = func - - def pre_connect_callback( - self, - ) -> Callable[[CallbackOnPreConnect], CallbackOnPreConnect]: - def decorator(func: CallbackOnPreConnect) -> CallbackOnPreConnect: - self.on_pre_connect = func - return func - return decorator - - @property - def on_connect(self) -> CallbackOnConnect | None: - """The callback called when the broker reponds to our connection request. - - Expected signature for callback API version 2:: - - connect_callback(client, userdata, connect_flags, reason_code, properties) - - Expected signature for callback API version 1 change with MQTT protocol version: - * For MQTT v3.1 and v3.1.1 it's:: - - connect_callback(client, userdata, flags, rc) - - * For MQTT v5.0 it's:: - - connect_callback(client, userdata, flags, reason_code, properties) - - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param ConnectFlags connect_flags: the flags for this connection - :param ReasonCode reason_code: the connection reason code received from the broken. - In MQTT v5.0 it's the reason code defined by the standard. - In MQTT v3, we convert return code to a reason code, see - `convert_connack_rc_to_reason_code()`. - `ReasonCode` may be compared to integer. - :param Properties properties: the MQTT v5.0 properties received from the broker. - For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties - object is always used. - :param dict flags: response flags sent by the broker - :param int rc: the connection result, should have a value of `ConnackCode` - - flags is a dict that contains response flags from the broker: - flags['session present'] - this flag is useful for clients that are - using clean session set to 0 only. If a client with clean - session=0, that reconnects to a broker that it has previously - connected to, this flag indicates whether the broker still has the - session information for the client. If 1, the session still exists. - - The value of rc indicates success or not: - - 0: Connection successful - - 1: Connection refused - incorrect protocol version - - 2: Connection refused - invalid client identifier - - 3: Connection refused - server unavailable - - 4: Connection refused - bad username or password - - 5: Connection refused - not authorised - - 6-255: Currently unused. - - Decorator: @client.connect_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_connect - - @on_connect.setter - def on_connect(self, func: CallbackOnConnect | None) -> None: - with self._callback_mutex: - self._on_connect = func - - def connect_callback( - self, - ) -> Callable[[CallbackOnConnect], CallbackOnConnect]: - def decorator(func: CallbackOnConnect) -> CallbackOnConnect: - self.on_connect = func - return func - return decorator - - @property - def on_connect_fail(self) -> CallbackOnConnectFail | None: - """The callback called when the client failed to connect - to the broker. - - Expected signature is (for all callback_api_version):: - - connect_fail_callback(client, userdata) - - :param Client client: the client instance for this callback - :parama userdata: the private user data as set in Client() or user_data_set() - - Decorator: @client.connect_fail_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_connect_fail - - @on_connect_fail.setter - def on_connect_fail(self, func: CallbackOnConnectFail | None) -> None: - with self._callback_mutex: - self._on_connect_fail = func - - def connect_fail_callback( - self, - ) -> Callable[[CallbackOnConnectFail], CallbackOnConnectFail]: - def decorator(func: CallbackOnConnectFail) -> CallbackOnConnectFail: - self.on_connect_fail = func - return func - return decorator - - @property - def on_subscribe(self) -> CallbackOnSubscribe | None: - """The callback called when the broker responds to a subscribe - request. - - Expected signature for callback API version 2:: - - subscribe_callback(client, userdata, mid, reason_code_list, properties) - - Expected signature for callback API version 1 change with MQTT protocol version: - * For MQTT v3.1 and v3.1.1 it's:: - - subscribe_callback(client, userdata, mid, granted_qos) - - * For MQTT v5.0 it's:: - - subscribe_callback(client, userdata, mid, reason_code_list, properties) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param int mid: matches the mid variable returned from the corresponding - subscribe() call. - :param list[ReasonCode] reason_code_list: reason codes received from the broker for each subscription. - In MQTT v5.0 it's the reason code defined by the standard. - In MQTT v3, we convert granted QoS to a reason code. - It's a list of ReasonCode instances. - :param Properties properties: the MQTT v5.0 properties received from the broker. - For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties - object is always used. - :param list[int] granted_qos: list of integers that give the QoS level the broker has - granted for each of the different subscription requests. - - Decorator: @client.subscribe_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_subscribe - - @on_subscribe.setter - def on_subscribe(self, func: CallbackOnSubscribe | None) -> None: - with self._callback_mutex: - self._on_subscribe = func - - def subscribe_callback( - self, - ) -> Callable[[CallbackOnSubscribe], CallbackOnSubscribe]: - def decorator(func: CallbackOnSubscribe) -> CallbackOnSubscribe: - self.on_subscribe = func - return func - return decorator - - @property - def on_message(self) -> CallbackOnMessage | None: - """The callback called when a message has been received on a topic - that the client subscribes to. - - This callback will be called for every message received unless a - `message_callback_add()` matched the message. - - Expected signature is (for all callback API version): - message_callback(client, userdata, message) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param MQTTMessage message: the received message. - This is a class with members topic, payload, qos, retain. - - Decorator: @client.message_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_message - - @on_message.setter - def on_message(self, func: CallbackOnMessage | None) -> None: - with self._callback_mutex: - self._on_message = func - - def message_callback( - self, - ) -> Callable[[CallbackOnMessage], CallbackOnMessage]: - def decorator(func: CallbackOnMessage) -> CallbackOnMessage: - self.on_message = func - return func - return decorator - - @property - def on_publish(self) -> CallbackOnPublish | None: - """The callback called when a message that was to be sent using the - `publish()` call has completed transmission to the broker. - - For messages with QoS levels 1 and 2, this means that the appropriate - handshakes have completed. For QoS 0, this simply means that the message - has left the client. - This callback is important because even if the `publish()` call returns - success, it does not always mean that the message has been sent. - - See also `wait_for_publish` which could be simpler to use. - - Expected signature for callback API version 2:: - - publish_callback(client, userdata, mid, reason_code, properties) - - Expected signature for callback API version 1:: - - publish_callback(client, userdata, mid) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param int mid: matches the mid variable returned from the corresponding - `publish()` call, to allow outgoing messages to be tracked. - :param ReasonCode reason_code: the connection reason code received from the broken. - In MQTT v5.0 it's the reason code defined by the standard. - In MQTT v3 it's always the reason code Success - :parama Properties properties: the MQTT v5.0 properties received from the broker. - For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties - object is always used. - - Note: for QoS = 0, the reason_code and the properties don't really exist, it's the client - library that generate them. It's always an empty properties and a success reason code. - Because the (MQTTv5) standard don't have reason code for PUBLISH packet, the library create them - at PUBACK packet, as if the message was sent with QoS = 1. - - Decorator: @client.publish_callback() (``client`` is the name of the - instance which this callback is being attached to) - - """ - return self._on_publish - - @on_publish.setter - def on_publish(self, func: CallbackOnPublish | None) -> None: - with self._callback_mutex: - self._on_publish = func - - def publish_callback( - self, - ) -> Callable[[CallbackOnPublish], CallbackOnPublish]: - def decorator(func: CallbackOnPublish) -> CallbackOnPublish: - self.on_publish = func - return func - return decorator - - @property - def on_unsubscribe(self) -> CallbackOnUnsubscribe | None: - """The callback called when the broker responds to an unsubscribe - request. - - Expected signature for callback API version 2:: - - unsubscribe_callback(client, userdata, mid, reason_code_list, properties) - - Expected signature for callback API version 1 change with MQTT protocol version: - * For MQTT v3.1 and v3.1.1 it's:: - - unsubscribe_callback(client, userdata, mid) - - * For MQTT v5.0 it's:: - - unsubscribe_callback(client, userdata, mid, properties, v1_reason_codes) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param mid: matches the mid variable returned from the corresponding - unsubscribe() call. - :param list[ReasonCode] reason_code_list: reason codes received from the broker for each unsubscription. - In MQTT v5.0 it's the reason code defined by the standard. - In MQTT v3, there is not equivalent from broken and empty list - is always used. - :param Properties properties: the MQTT v5.0 properties received from the broker. - For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties - object is always used. - :param v1_reason_codes: the MQTT v5.0 reason codes received from the broker for each - unsubscribe topic. A list of ReasonCode instances OR a single - ReasonCode when we unsubscribe from a single topic. - - Decorator: @client.unsubscribe_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_unsubscribe - - @on_unsubscribe.setter - def on_unsubscribe(self, func: CallbackOnUnsubscribe | None) -> None: - with self._callback_mutex: - self._on_unsubscribe = func - - def unsubscribe_callback( - self, - ) -> Callable[[CallbackOnUnsubscribe], CallbackOnUnsubscribe]: - def decorator(func: CallbackOnUnsubscribe) -> CallbackOnUnsubscribe: - self.on_unsubscribe = func - return func - return decorator - - @property - def on_disconnect(self) -> CallbackOnDisconnect | None: - """The callback called when the client disconnects from the broker. - - Expected signature for callback API version 2:: - - disconnect_callback(client, userdata, disconnect_flags, reason_code, properties) - - Expected signature for callback API version 1 change with MQTT protocol version: - * For MQTT v3.1 and v3.1.1 it's:: - - disconnect_callback(client, userdata, rc) - - * For MQTT v5.0 it's:: - - disconnect_callback(client, userdata, reason_code, properties) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param DisconnectFlag disconnect_flags: the flags for this disconnection. - :param ReasonCode reason_code: the disconnection reason code possibly received from the broker (see disconnect_flags). - In MQTT v5.0 it's the reason code defined by the standard. - In MQTT v3 it's never received from the broker, we convert an MQTTErrorCode, - see `convert_disconnect_error_code_to_reason_code()`. - `ReasonCode` may be compared to integer. - :param Properties properties: the MQTT v5.0 properties received from the broker. - For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties - object is always used. - :param int rc: the disconnection result - The rc parameter indicates the disconnection state. If - MQTT_ERR_SUCCESS (0), the callback was called in response to - a disconnect() call. If any other value the disconnection - was unexpected, such as might be caused by a network error. - - Decorator: @client.disconnect_callback() (``client`` is the name of the - instance which this callback is being attached to) - - """ - return self._on_disconnect - - @on_disconnect.setter - def on_disconnect(self, func: CallbackOnDisconnect | None) -> None: - with self._callback_mutex: - self._on_disconnect = func - - def disconnect_callback( - self, - ) -> Callable[[CallbackOnDisconnect], CallbackOnDisconnect]: - def decorator(func: CallbackOnDisconnect) -> CallbackOnDisconnect: - self.on_disconnect = func - return func - return decorator - - @property - def on_socket_open(self) -> CallbackOnSocket | None: - """The callback called just after the socket was opend. - - This should be used to register the socket to an external event loop for reading. - - Expected signature is (for all callback API version):: - - socket_open_callback(client, userdata, socket) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param SocketLike sock: the socket which was just opened. - - Decorator: @client.socket_open_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_socket_open - - @on_socket_open.setter - def on_socket_open(self, func: CallbackOnSocket | None) -> None: - with self._callback_mutex: - self._on_socket_open = func - - def socket_open_callback( - self, - ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: - def decorator(func: CallbackOnSocket) -> CallbackOnSocket: - self.on_socket_open = func - return func - return decorator - - def _call_socket_open(self, sock: SocketLike) -> None: - """Call the socket_open callback with the just-opened socket""" - with self._callback_mutex: - on_socket_open = self.on_socket_open - - if on_socket_open: - with self._in_callback_mutex: - try: - on_socket_open(self, self._userdata, sock) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_socket_open: %s', err) - if not self.suppress_exceptions: - raise - - @property - def on_socket_close(self) -> CallbackOnSocket | None: - """The callback called just before the socket is closed. - - This should be used to unregister the socket from an external event loop for reading. - - Expected signature is (for all callback API version):: - - socket_close_callback(client, userdata, socket) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param SocketLike sock: the socket which is about to be closed. - - Decorator: @client.socket_close_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_socket_close - - @on_socket_close.setter - def on_socket_close(self, func: CallbackOnSocket | None) -> None: - with self._callback_mutex: - self._on_socket_close = func - - def socket_close_callback( - self, - ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: - def decorator(func: CallbackOnSocket) -> CallbackOnSocket: - self.on_socket_close = func - return func - return decorator - - def _call_socket_close(self, sock: SocketLike) -> None: - """Call the socket_close callback with the about-to-be-closed socket""" - with self._callback_mutex: - on_socket_close = self.on_socket_close - - if on_socket_close: - with self._in_callback_mutex: - try: - on_socket_close(self, self._userdata, sock) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_socket_close: %s', err) - if not self.suppress_exceptions: - raise - - @property - def on_socket_register_write(self) -> CallbackOnSocket | None: - """The callback called when the socket needs writing but can't. - - This should be used to register the socket with an external event loop for writing. - - Expected signature is (for all callback API version):: - - socket_register_write_callback(client, userdata, socket) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param SocketLike sock: the socket which should be registered for writing - - Decorator: @client.socket_register_write_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_socket_register_write - - @on_socket_register_write.setter - def on_socket_register_write(self, func: CallbackOnSocket | None) -> None: - with self._callback_mutex: - self._on_socket_register_write = func - - def socket_register_write_callback( - self, - ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: - def decorator(func: CallbackOnSocket) -> CallbackOnSocket: - self._on_socket_register_write = func - return func - return decorator - - def _call_socket_register_write(self) -> None: - """Call the socket_register_write callback with the unwritable socket""" - if not self._sock or self._registered_write: - return - self._registered_write = True - with self._callback_mutex: - on_socket_register_write = self.on_socket_register_write - - if on_socket_register_write: - try: - on_socket_register_write( - self, self._userdata, self._sock) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_socket_register_write: %s', err) - if not self.suppress_exceptions: - raise - - @property - def on_socket_unregister_write( - self, - ) -> CallbackOnSocket | None: - """The callback called when the socket doesn't need writing anymore. - - This should be used to unregister the socket from an external event loop for writing. - - Expected signature is (for all callback API version):: - - socket_unregister_write_callback(client, userdata, socket) - - :param Client client: the client instance for this callback - :param userdata: the private user data as set in Client() or user_data_set() - :param SocketLike sock: the socket which should be unregistered for writing - - Decorator: @client.socket_unregister_write_callback() (``client`` is the name of the - instance which this callback is being attached to) - """ - return self._on_socket_unregister_write - - @on_socket_unregister_write.setter - def on_socket_unregister_write( - self, func: CallbackOnSocket | None - ) -> None: - with self._callback_mutex: - self._on_socket_unregister_write = func - - def socket_unregister_write_callback( - self, - ) -> Callable[[CallbackOnSocket], CallbackOnSocket]: - def decorator( - func: CallbackOnSocket, - ) -> CallbackOnSocket: - self._on_socket_unregister_write = func - return func - return decorator - - def _call_socket_unregister_write( - self, sock: SocketLike | None = None - ) -> None: - """Call the socket_unregister_write callback with the writable socket""" - sock = sock or self._sock - if not sock or not self._registered_write: - return - self._registered_write = False - - with self._callback_mutex: - on_socket_unregister_write = self.on_socket_unregister_write - - if on_socket_unregister_write: - try: - on_socket_unregister_write(self, self._userdata, sock) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_socket_unregister_write: %s', err) - if not self.suppress_exceptions: - raise - - def message_callback_add(self, sub: str, callback: CallbackOnMessage) -> None: - """Register a message callback for a specific topic. - Messages that match 'sub' will be passed to 'callback'. Any - non-matching messages will be passed to the default `on_message` - callback. - - Call multiple times with different 'sub' to define multiple topic - specific callbacks. - - Topic specific callbacks may be removed with - `message_callback_remove()`. - - See `on_message` for the expected signature of the callback. - - Decorator: @client.topic_callback(sub) (``client`` is the name of the - instance which this callback is being attached to) - - Example:: - - @client.topic_callback("mytopic/#") - def handle_mytopic(client, userdata, message): - ... - """ - if callback is None or sub is None: - raise ValueError("sub and callback must both be defined.") - - with self._callback_mutex: - self._on_message_filtered[sub] = callback - - def topic_callback( - self, sub: str - ) -> Callable[[CallbackOnMessage], CallbackOnMessage]: - def decorator(func: CallbackOnMessage) -> CallbackOnMessage: - self.message_callback_add(sub, func) - return func - return decorator - - def message_callback_remove(self, sub: str) -> None: - """Remove a message callback previously registered with - `message_callback_add()`.""" - if sub is None: - raise ValueError("sub must defined.") - - with self._callback_mutex: - try: - del self._on_message_filtered[sub] - except KeyError: # no such subscription - pass - - # ============================================================ - # Private functions - # ============================================================ - - def _loop_rc_handle( - self, - rc: MQTTErrorCode, - ) -> MQTTErrorCode: - if rc: - self._sock_close() - - if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): - self._state = _ConnectionState.MQTT_CS_DISCONNECTED - rc = MQTTErrorCode.MQTT_ERR_SUCCESS - - self._do_on_disconnect(packet_from_broker=False, v1_rc=rc) - - if rc == MQTT_ERR_CONN_LOST: - self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST - - return rc - - def _packet_read(self) -> MQTTErrorCode: - # This gets called if pselect() indicates that there is network data - # available - ie. at least one byte. What we do depends on what data we - # already have. - # If we've not got a command, attempt to read one and save it. This should - # always work because it's only a single byte. - # Then try to read the remaining length. This may fail because it is may - # be more than one byte - will need to save data pending next read if it - # does fail. - # Then try to read the remaining payload, where 'payload' here means the - # combined variable header and actual payload. This is the most likely to - # fail due to longer length, so save current data and current position. - # After all data is read, send to _mqtt_handle_packet() to deal with. - # Finally, free the memory and reset everything to starting conditions. - if self._in_packet['command'] == 0: - try: - command = self._sock_recv(1) - except BlockingIOError: - return MQTTErrorCode.MQTT_ERR_AGAIN - except TimeoutError as err: - self._easy_log( - MQTT_LOG_ERR, 'timeout on socket: %s', err) - return MQTTErrorCode.MQTT_ERR_CONN_LOST - except OSError as err: - self._easy_log( - MQTT_LOG_ERR, 'failed to receive on socket: %s', err) - return MQTTErrorCode.MQTT_ERR_CONN_LOST - else: - if len(command) == 0: - return MQTTErrorCode.MQTT_ERR_CONN_LOST - self._in_packet['command'] = command[0] - - if self._in_packet['have_remaining'] == 0: - # Read remaining - # Algorithm for decoding taken from pseudo code at - # http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm - while True: - try: - byte = self._sock_recv(1) - except BlockingIOError: - return MQTTErrorCode.MQTT_ERR_AGAIN - except OSError as err: - self._easy_log( - MQTT_LOG_ERR, 'failed to receive on socket: %s', err) - return MQTTErrorCode.MQTT_ERR_CONN_LOST - else: - if len(byte) == 0: - return MQTTErrorCode.MQTT_ERR_CONN_LOST - byte_value = byte[0] - self._in_packet['remaining_count'].append(byte_value) - # Max 4 bytes length for remaining length as defined by protocol. - # Anything more likely means a broken/malicious client. - if len(self._in_packet['remaining_count']) > 4: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - self._in_packet['remaining_length'] += ( - byte_value & 127) * self._in_packet['remaining_mult'] - self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128 - - if (byte_value & 128) == 0: - break - - self._in_packet['have_remaining'] = 1 - self._in_packet['to_process'] = self._in_packet['remaining_length'] - - count = 100 # Don't get stuck in this loop if we have a huge message. - while self._in_packet['to_process'] > 0: - try: - data = self._sock_recv(self._in_packet['to_process']) - except BlockingIOError: - return MQTTErrorCode.MQTT_ERR_AGAIN - except OSError as err: - self._easy_log( - MQTT_LOG_ERR, 'failed to receive on socket: %s', err) - return MQTTErrorCode.MQTT_ERR_CONN_LOST - else: - if len(data) == 0: - return MQTTErrorCode.MQTT_ERR_CONN_LOST - self._in_packet['to_process'] -= len(data) - self._in_packet['packet'] += data - count -= 1 - if count == 0: - with self._msgtime_mutex: - self._last_msg_in = time_func() - return MQTTErrorCode.MQTT_ERR_AGAIN - - # All data for this packet is read. - self._in_packet['pos'] = 0 - rc = self._packet_handle() - - # Free data and reset values - self._in_packet = { - "command": 0, - "have_remaining": 0, - "remaining_count": [], - "remaining_mult": 1, - "remaining_length": 0, - "packet": bytearray(b""), - "to_process": 0, - "pos": 0, - } - - with self._msgtime_mutex: - self._last_msg_in = time_func() - return rc - - def _packet_write(self) -> MQTTErrorCode: - while True: - try: - packet = self._out_packet.popleft() - except IndexError: - return MQTTErrorCode.MQTT_ERR_SUCCESS - - try: - write_length = self._sock_send( - packet['packet'][packet['pos']:]) - except (AttributeError, ValueError): - self._out_packet.appendleft(packet) - return MQTTErrorCode.MQTT_ERR_SUCCESS - except BlockingIOError: - self._out_packet.appendleft(packet) - return MQTTErrorCode.MQTT_ERR_AGAIN - except OSError as err: - self._out_packet.appendleft(packet) - self._easy_log( - MQTT_LOG_ERR, 'failed to receive on socket: %s', err) - return MQTTErrorCode.MQTT_ERR_CONN_LOST - - if write_length > 0: - packet['to_process'] -= write_length - packet['pos'] += write_length - - if packet['to_process'] == 0: - if (packet['command'] & 0xF0) == PUBLISH and packet['qos'] == 0: - with self._callback_mutex: - on_publish = self.on_publish - - if on_publish: - with self._in_callback_mutex: - try: - if self._callback_api_version == CallbackAPIVersion.VERSION1: - on_publish = cast(CallbackOnPublish_v1, on_publish) - - on_publish(self, self._userdata, packet["mid"]) - elif self._callback_api_version == CallbackAPIVersion.VERSION2: - on_publish = cast(CallbackOnPublish_v2, on_publish) - - on_publish( - self, - self._userdata, - packet["mid"], - ReasonCode(PacketTypes.PUBACK), - Properties(PacketTypes.PUBACK), - ) - else: - raise RuntimeError("Unsupported callback API version") - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err) - if not self.suppress_exceptions: - raise - - # TODO: Something is odd here. I don't see why packet["info"] can't be None. - # A packet could be produced by _handle_connack with qos=0 and no info - # (around line 3645). Ignore the mypy check for now but I feel there is a bug - # somewhere. - packet['info']._set_as_published() # type: ignore - - if (packet['command'] & 0xF0) == DISCONNECT: - with self._msgtime_mutex: - self._last_msg_out = time_func() - - self._do_on_disconnect( - packet_from_broker=False, - v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, - ) - self._sock_close() - # Only change to disconnected if the disconnection was wanted - # by the client (== state was disconnecting). If the broker disconnected - # use unilaterally don't change the state and client may reconnect. - if self._state == _ConnectionState.MQTT_CS_DISCONNECTING: - self._state = _ConnectionState.MQTT_CS_DISCONNECTED - return MQTTErrorCode.MQTT_ERR_SUCCESS - - else: - # We haven't finished with this packet - self._out_packet.appendleft(packet) - else: - break - - with self._msgtime_mutex: - self._last_msg_out = time_func() - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _easy_log(self, level: LogLevel, fmt: str, *args: Any) -> None: - if self.on_log is not None: - buf = fmt % args - try: - self.on_log(self, self._userdata, level, buf) - except Exception: # noqa: S110 - # Can't _easy_log this, as we'll recurse until we break - pass # self._logger will pick this up, so we're fine - if self._logger is not None: - level_std = LOGGING_LEVEL[level] - self._logger.log(level_std, fmt, *args) - - def _check_keepalive(self) -> None: - if self._keepalive == 0: - return - - now = time_func() - - with self._msgtime_mutex: - last_msg_out = self._last_msg_out - last_msg_in = self._last_msg_in - - if self._sock is not None and (now - last_msg_out >= self._keepalive or now - last_msg_in >= self._keepalive): - if self._state == _ConnectionState.MQTT_CS_CONNECTED and self._ping_t == 0: - try: - self._send_pingreq() - except Exception: - self._sock_close() - self._do_on_disconnect( - packet_from_broker=False, - v1_rc=MQTTErrorCode.MQTT_ERR_CONN_LOST, - ) - else: - with self._msgtime_mutex: - self._last_msg_out = now - self._last_msg_in = now - else: - self._sock_close() - - if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED): - self._state = _ConnectionState.MQTT_CS_DISCONNECTED - rc = MQTTErrorCode.MQTT_ERR_SUCCESS - else: - rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE - - self._do_on_disconnect( - packet_from_broker=False, - v1_rc=rc, - ) - - def _mid_generate(self) -> int: - with self._mid_generate_mutex: - self._last_mid += 1 - if self._last_mid == 65536: - self._last_mid = 1 - return self._last_mid - - @staticmethod - def _raise_for_invalid_topic(topic: bytes) -> None: - """ Check if the topic is a topic without wildcard and valid length. - - Raise ValueError if the topic isn't valid. - """ - if b'+' in topic or b'#' in topic: - raise ValueError('Publish topic cannot contain wildcards.') - if len(topic) > 65535: - raise ValueError('Publish topic is too long.') - - @staticmethod - def _filter_wildcard_len_check(sub: bytes) -> MQTTErrorCode: - if (len(sub) == 0 or len(sub) > 65535 - or any(b'+' in p or b'#' in p for p in sub.split(b'/') if len(p) > 1) - or b'#/' in sub): - return MQTTErrorCode.MQTT_ERR_INVAL - else: - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _send_pingreq(self) -> MQTTErrorCode: - self._easy_log(MQTT_LOG_DEBUG, "Sending PINGREQ") - rc = self._send_simple_command(PINGREQ) - if rc == MQTTErrorCode.MQTT_ERR_SUCCESS: - self._ping_t = time_func() - return rc - - def _send_pingresp(self) -> MQTTErrorCode: - self._easy_log(MQTT_LOG_DEBUG, "Sending PINGRESP") - return self._send_simple_command(PINGRESP) - - def _send_puback(self, mid: int) -> MQTTErrorCode: - self._easy_log(MQTT_LOG_DEBUG, "Sending PUBACK (Mid: %d)", mid) - return self._send_command_with_mid(PUBACK, mid, False) - - def _send_pubcomp(self, mid: int) -> MQTTErrorCode: - self._easy_log(MQTT_LOG_DEBUG, "Sending PUBCOMP (Mid: %d)", mid) - return self._send_command_with_mid(PUBCOMP, mid, False) - - def _pack_remaining_length( - self, packet: bytearray, remaining_length: int - ) -> bytearray: - remaining_bytes = [] - while True: - byte = remaining_length % 128 - remaining_length = remaining_length // 128 - # If there are more digits to encode, set the top bit of this digit - if remaining_length > 0: - byte |= 0x80 - - remaining_bytes.append(byte) - packet.append(byte) - if remaining_length == 0: - # FIXME - this doesn't deal with incorrectly large payloads - return packet - - def _pack_str16(self, packet: bytearray, data: bytes | str) -> None: - data = _force_bytes(data) - packet.extend(struct.pack("!H", len(data))) - packet.extend(data) - - def _send_publish( - self, - mid: int, - topic: bytes, - payload: bytes|bytearray = b"", - qos: int = 0, - retain: bool = False, - dup: bool = False, - info: MQTTMessageInfo | None = None, - properties: Properties | None = None, - ) -> MQTTErrorCode: - # we assume that topic and payload are already properly encoded - if not isinstance(topic, bytes): - raise TypeError('topic must be bytes, not str') - if payload and not isinstance(payload, (bytes, bytearray)): - raise TypeError('payload must be bytes if set') - - if self._sock is None: - return MQTTErrorCode.MQTT_ERR_NO_CONN - - command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain - packet = bytearray() - packet.append(command) - - payloadlen = len(payload) - remaining_length = 2 + len(topic) + payloadlen - - if payloadlen == 0: - if self._protocol == MQTTv5: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s (NULL payload)", - dup, qos, retain, mid, topic, properties - ) - else: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s' (NULL payload)", - dup, qos, retain, mid, topic - ) - else: - if self._protocol == MQTTv5: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)", - dup, qos, retain, mid, topic, properties, payloadlen - ) - else: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)", - dup, qos, retain, mid, topic, payloadlen - ) - - if qos > 0: - # For message id - remaining_length += 2 - - if self._protocol == MQTTv5: - if properties is None: - packed_properties = b'\x00' - else: - packed_properties = properties.pack() - remaining_length += len(packed_properties) - - self._pack_remaining_length(packet, remaining_length) - self._pack_str16(packet, topic) - - if qos > 0: - # For message id - packet.extend(struct.pack("!H", mid)) - - if self._protocol == MQTTv5: - packet.extend(packed_properties) - - packet.extend(payload) - - return self._packet_queue(PUBLISH, packet, mid, qos, info) - - def _send_pubrec(self, mid: int) -> MQTTErrorCode: - self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREC (Mid: %d)", mid) - return self._send_command_with_mid(PUBREC, mid, False) - - def _send_pubrel(self, mid: int) -> MQTTErrorCode: - self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREL (Mid: %d)", mid) - return self._send_command_with_mid(PUBREL | 2, mid, False) - - def _send_command_with_mid(self, command: int, mid: int, dup: int) -> MQTTErrorCode: - # For PUBACK, PUBCOMP, PUBREC, and PUBREL - if dup: - command |= 0x8 - - remaining_length = 2 - packet = struct.pack('!BBH', command, remaining_length, mid) - return self._packet_queue(command, packet, mid, 1) - - def _send_simple_command(self, command: int) -> MQTTErrorCode: - # For DISCONNECT, PINGREQ and PINGRESP - remaining_length = 0 - packet = struct.pack('!BB', command, remaining_length) - return self._packet_queue(command, packet, 0, 0) - - def _send_connect(self, keepalive: int) -> MQTTErrorCode: - proto_ver = int(self._protocol) - # hard-coded UTF-8 encoded string - protocol = b"MQTT" if proto_ver >= MQTTv311 else b"MQIsdp" - - remaining_length = 2 + len(protocol) + 1 + \ - 1 + 2 + 2 + len(self._client_id) - - connect_flags = 0 - if self._protocol == MQTTv5: - if self._clean_start is True: - connect_flags |= 0x02 - elif self._clean_start == MQTT_CLEAN_START_FIRST_ONLY and self._mqttv5_first_connect: - connect_flags |= 0x02 - elif self._clean_session: - connect_flags |= 0x02 - - if self._will: - remaining_length += 2 + \ - len(self._will_topic) + 2 + len(self._will_payload) - connect_flags |= 0x04 | ((self._will_qos & 0x03) << 3) | ( - (self._will_retain & 0x01) << 5) - - if self._username is not None: - remaining_length += 2 + len(self._username) - connect_flags |= 0x80 - if self._password is not None: - connect_flags |= 0x40 - remaining_length += 2 + len(self._password) - - if self._protocol == MQTTv5: - if self._connect_properties is None: - packed_connect_properties = b'\x00' - else: - packed_connect_properties = self._connect_properties.pack() - remaining_length += len(packed_connect_properties) - if self._will: - if self._will_properties is None: - packed_will_properties = b'\x00' - else: - packed_will_properties = self._will_properties.pack() - remaining_length += len(packed_will_properties) - - command = CONNECT - packet = bytearray() - packet.append(command) - - # as per the mosquitto broker, if the MSB of this version is set - # to 1, then it treats the connection as a bridge - if self._client_mode == MQTT_BRIDGE: - proto_ver |= 0x80 - - self._pack_remaining_length(packet, remaining_length) - packet.extend(struct.pack( - f"!H{len(protocol)}sBBH", - len(protocol), protocol, proto_ver, connect_flags, keepalive, - )) - - if self._protocol == MQTTv5: - packet += packed_connect_properties - - self._pack_str16(packet, self._client_id) - - if self._will: - if self._protocol == MQTTv5: - packet += packed_will_properties - self._pack_str16(packet, self._will_topic) - self._pack_str16(packet, self._will_payload) - - if self._username is not None: - self._pack_str16(packet, self._username) - - if self._password is not None: - self._pack_str16(packet, self._password) - - self._keepalive = keepalive - if self._protocol == MQTTv5: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%s", - (connect_flags & 0x80) >> 7, - (connect_flags & 0x40) >> 6, - (connect_flags & 0x20) >> 5, - (connect_flags & 0x18) >> 3, - (connect_flags & 0x4) >> 2, - (connect_flags & 0x2) >> 1, - keepalive, - self._client_id, - self._connect_properties - ) - else: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s", - (connect_flags & 0x80) >> 7, - (connect_flags & 0x40) >> 6, - (connect_flags & 0x20) >> 5, - (connect_flags & 0x18) >> 3, - (connect_flags & 0x4) >> 2, - (connect_flags & 0x2) >> 1, - keepalive, - self._client_id - ) - return self._packet_queue(command, packet, 0, 0) - - def _send_disconnect( - self, - reasoncode: ReasonCode | None = None, - properties: Properties | None = None, - ) -> MQTTErrorCode: - if self._protocol == MQTTv5: - self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT reasonCode=%s properties=%s", - reasoncode, - properties - ) - else: - self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT") - - remaining_length = 0 - - command = DISCONNECT - packet = bytearray() - packet.append(command) - - if self._protocol == MQTTv5: - if properties is not None or reasoncode is not None: - if reasoncode is None: - reasoncode = ReasonCode(DISCONNECT >> 4, identifier=0) - remaining_length += 1 - if properties is not None: - packed_props = properties.pack() - remaining_length += len(packed_props) - - self._pack_remaining_length(packet, remaining_length) - - if self._protocol == MQTTv5: - if reasoncode is not None: - packet += reasoncode.pack() - if properties is not None: - packet += packed_props - - return self._packet_queue(command, packet, 0, 0) - - def _send_subscribe( - self, - dup: int, - topics: Sequence[tuple[bytes, SubscribeOptions | int]], - properties: Properties | None = None, - ) -> tuple[MQTTErrorCode, int]: - remaining_length = 2 - if self._protocol == MQTTv5: - if properties is None: - packed_subscribe_properties = b'\x00' - else: - packed_subscribe_properties = properties.pack() - remaining_length += len(packed_subscribe_properties) - for t, _ in topics: - remaining_length += 2 + len(t) + 1 - - command = SUBSCRIBE | (dup << 3) | 0x2 - packet = bytearray() - packet.append(command) - self._pack_remaining_length(packet, remaining_length) - local_mid = self._mid_generate() - packet.extend(struct.pack("!H", local_mid)) - - if self._protocol == MQTTv5: - packet += packed_subscribe_properties - - for t, q in topics: - self._pack_str16(packet, t) - if self._protocol == MQTTv5: - packet += q.pack() # type: ignore - else: - packet.append(q) # type: ignore - - self._easy_log( - MQTT_LOG_DEBUG, - "Sending SUBSCRIBE (d%d, m%d) %s", - dup, - local_mid, - topics, - ) - return (self._packet_queue(command, packet, local_mid, 1), local_mid) - - def _send_unsubscribe( - self, - dup: int, - topics: list[bytes], - properties: Properties | None = None, - ) -> tuple[MQTTErrorCode, int]: - remaining_length = 2 - if self._protocol == MQTTv5: - if properties is None: - packed_unsubscribe_properties = b'\x00' - else: - packed_unsubscribe_properties = properties.pack() - remaining_length += len(packed_unsubscribe_properties) - for t in topics: - remaining_length += 2 + len(t) - - command = UNSUBSCRIBE | (dup << 3) | 0x2 - packet = bytearray() - packet.append(command) - self._pack_remaining_length(packet, remaining_length) - local_mid = self._mid_generate() - packet.extend(struct.pack("!H", local_mid)) - - if self._protocol == MQTTv5: - packet += packed_unsubscribe_properties - - for t in topics: - self._pack_str16(packet, t) - - # topics_repr = ", ".join("'"+topic.decode('utf8')+"'" for topic in topics) - if self._protocol == MQTTv5: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending UNSUBSCRIBE (d%d, m%d) %s %s", - dup, - local_mid, - properties, - topics, - ) - else: - self._easy_log( - MQTT_LOG_DEBUG, - "Sending UNSUBSCRIBE (d%d, m%d) %s", - dup, - local_mid, - topics, - ) - return (self._packet_queue(command, packet, local_mid, 1), local_mid) - - def _check_clean_session(self) -> bool: - if self._protocol == MQTTv5: - if self._clean_start == MQTT_CLEAN_START_FIRST_ONLY: - return self._mqttv5_first_connect - else: - return self._clean_start # type: ignore - else: - return self._clean_session - - def _messages_reconnect_reset_out(self) -> None: - with self._out_message_mutex: - self._inflight_messages = 0 - for m in self._out_messages.values(): - m.timestamp = 0 - if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages: - if m.qos == 0: - m.state = mqtt_ms_publish - elif m.qos == 1: - # self._inflight_messages = self._inflight_messages + 1 - if m.state == mqtt_ms_wait_for_puback: - m.dup = True - m.state = mqtt_ms_publish - elif m.qos == 2: - # self._inflight_messages = self._inflight_messages + 1 - if self._check_clean_session(): - if m.state != mqtt_ms_publish: - m.dup = True - m.state = mqtt_ms_publish - else: - if m.state == mqtt_ms_wait_for_pubcomp: - m.state = mqtt_ms_resend_pubrel - else: - if m.state == mqtt_ms_wait_for_pubrec: - m.dup = True - m.state = mqtt_ms_publish - else: - m.state = mqtt_ms_queued - - def _messages_reconnect_reset_in(self) -> None: - with self._in_message_mutex: - if self._check_clean_session(): - self._in_messages = collections.OrderedDict() - return - for m in self._in_messages.values(): - m.timestamp = 0 - if m.qos != 2: - self._in_messages.pop(m.mid) - else: - # Preserve current state - pass - - def _messages_reconnect_reset(self) -> None: - self._messages_reconnect_reset_out() - self._messages_reconnect_reset_in() - - def _packet_queue( - self, - command: int, - packet: bytes, - mid: int, - qos: int, - info: MQTTMessageInfo | None = None, - ) -> MQTTErrorCode: - mpkt: _OutPacket = { - "command": command, - "mid": mid, - "qos": qos, - "pos": 0, - "to_process": len(packet), - "packet": packet, - "info": info, - } - - self._out_packet.append(mpkt) - - # Write a single byte to sockpairW (connected to sockpairR) to break - # out of select() if in threaded mode. - if self._sockpairW is not None: - try: - self._sockpairW.send(sockpair_data) - except BlockingIOError: - pass - - # If we have an external event loop registered, use that instead - # of calling loop_write() directly. - if self._thread is None and self._on_socket_register_write is None: - if self._in_callback_mutex.acquire(False): - self._in_callback_mutex.release() - return self.loop_write() - - self._call_socket_register_write() - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _packet_handle(self) -> MQTTErrorCode: - cmd = self._in_packet['command'] & 0xF0 - if cmd == PINGREQ: - return self._handle_pingreq() - elif cmd == PINGRESP: - return self._handle_pingresp() - elif cmd == PUBACK: - return self._handle_pubackcomp("PUBACK") - elif cmd == PUBCOMP: - return self._handle_pubackcomp("PUBCOMP") - elif cmd == PUBLISH: - return self._handle_publish() - elif cmd == PUBREC: - return self._handle_pubrec() - elif cmd == PUBREL: - return self._handle_pubrel() - elif cmd == CONNACK: - return self._handle_connack() - elif cmd == SUBACK: - self._handle_suback() - return MQTTErrorCode.MQTT_ERR_SUCCESS - elif cmd == UNSUBACK: - return self._handle_unsuback() - elif cmd == DISCONNECT and self._protocol == MQTTv5: # only allowed in MQTT 5.0 - self._handle_disconnect() - return MQTTErrorCode.MQTT_ERR_SUCCESS - else: - # If we don't recognise the command, return an error straight away. - self._easy_log(MQTT_LOG_ERR, "Error: Unrecognised command %s", cmd) - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - def _handle_pingreq(self) -> MQTTErrorCode: - if self._in_packet['remaining_length'] != 0: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - self._easy_log(MQTT_LOG_DEBUG, "Received PINGREQ") - return self._send_pingresp() - - def _handle_pingresp(self) -> MQTTErrorCode: - if self._in_packet['remaining_length'] != 0: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - # No longer waiting for a PINGRESP. - self._ping_t = 0 - self._easy_log(MQTT_LOG_DEBUG, "Received PINGRESP") - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _handle_connack(self) -> MQTTErrorCode: - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] < 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - elif self._in_packet['remaining_length'] != 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - if self._protocol == MQTTv5: - (flags, result) = struct.unpack( - "!BB", self._in_packet['packet'][:2]) - if result == 1: - # This is probably a failure from a broker that doesn't support - # MQTT v5. - reason = ReasonCode(CONNACK >> 4, aName="Unsupported protocol version") - properties = None - else: - reason = ReasonCode(CONNACK >> 4, identifier=result) - properties = Properties(CONNACK >> 4) - properties.unpack(self._in_packet['packet'][2:]) - else: - (flags, result) = struct.unpack("!BB", self._in_packet['packet']) - reason = convert_connack_rc_to_reason_code(result) - properties = None - if self._protocol == MQTTv311: - if result == CONNACK_REFUSED_PROTOCOL_VERSION: - if not self._reconnect_on_failure: - return MQTT_ERR_PROTOCOL - self._easy_log( - MQTT_LOG_DEBUG, - "Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.", - flags, result - ) - # Downgrade to MQTT v3.1 - self._protocol = MQTTv31 - return self.reconnect() - elif (result == CONNACK_REFUSED_IDENTIFIER_REJECTED - and self._client_id == b''): - if not self._reconnect_on_failure: - return MQTT_ERR_PROTOCOL - self._easy_log( - MQTT_LOG_DEBUG, - "Received CONNACK (%s, %s), attempting to use non-empty CID", - flags, result, - ) - self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8") - return self.reconnect() - - if result == 0: - self._state = _ConnectionState.MQTT_CS_CONNECTED - self._reconnect_delay = None - - if self._protocol == MQTTv5: - self._easy_log( - MQTT_LOG_DEBUG, "Received CONNACK (%s, %s) properties=%s", flags, reason, properties) - else: - self._easy_log( - MQTT_LOG_DEBUG, "Received CONNACK (%s, %s)", flags, result) - - # it won't be the first successful connect any more - self._mqttv5_first_connect = False - - with self._callback_mutex: - on_connect = self.on_connect - - if on_connect: - flags_dict = {} - flags_dict['session present'] = flags & 0x01 - with self._in_callback_mutex: - try: - if self._callback_api_version == CallbackAPIVersion.VERSION1: - if self._protocol == MQTTv5: - on_connect = cast(CallbackOnConnect_v1_mqtt5, on_connect) - - on_connect(self, self._userdata, - flags_dict, reason, properties) - else: - on_connect = cast(CallbackOnConnect_v1_mqtt3, on_connect) - - on_connect( - self, self._userdata, flags_dict, result) - elif self._callback_api_version == CallbackAPIVersion.VERSION2: - on_connect = cast(CallbackOnConnect_v2, on_connect) - - connect_flags = ConnectFlags( - session_present=flags_dict['session present'] > 0 - ) - - if properties is None: - properties = Properties(PacketTypes.CONNACK) - - on_connect( - self, - self._userdata, - connect_flags, - reason, - properties, - ) - else: - raise RuntimeError("Unsupported callback API version") - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_connect: %s', err) - if not self.suppress_exceptions: - raise - - if result == 0: - rc = MQTTErrorCode.MQTT_ERR_SUCCESS - with self._out_message_mutex: - for m in self._out_messages.values(): - m.timestamp = time_func() - if m.state == mqtt_ms_queued: - self.loop_write() # Process outgoing messages that have just been queued up - return MQTT_ERR_SUCCESS - - if m.qos == 0: - with self._in_callback_mutex: # Don't call loop_write after _send_publish() - rc = self._send_publish( - m.mid, - m.topic.encode('utf-8'), - m.payload, - m.qos, - m.retain, - m.dup, - properties=m.properties - ) - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - elif m.qos == 1: - if m.state == mqtt_ms_publish: - self._inflight_messages += 1 - m.state = mqtt_ms_wait_for_puback - with self._in_callback_mutex: # Don't call loop_write after _send_publish() - rc = self._send_publish( - m.mid, - m.topic.encode('utf-8'), - m.payload, - m.qos, - m.retain, - m.dup, - properties=m.properties - ) - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - elif m.qos == 2: - if m.state == mqtt_ms_publish: - self._inflight_messages += 1 - m.state = mqtt_ms_wait_for_pubrec - with self._in_callback_mutex: # Don't call loop_write after _send_publish() - rc = self._send_publish( - m.mid, - m.topic.encode('utf-8'), - m.payload, - m.qos, - m.retain, - m.dup, - properties=m.properties - ) - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - elif m.state == mqtt_ms_resend_pubrel: - self._inflight_messages += 1 - m.state = mqtt_ms_wait_for_pubcomp - with self._in_callback_mutex: # Don't call loop_write after _send_publish() - rc = self._send_pubrel(m.mid) - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - self.loop_write() # Process outgoing messages that have just been queued up - - return rc - elif result > 0 and result < 6: - return MQTTErrorCode.MQTT_ERR_CONN_REFUSED - else: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - def _handle_disconnect(self) -> None: - packet_type = DISCONNECT >> 4 - reasonCode = properties = None - if self._in_packet['remaining_length'] > 2: - reasonCode = ReasonCode(packet_type) - reasonCode.unpack(self._in_packet['packet']) - if self._in_packet['remaining_length'] > 3: - properties = Properties(packet_type) - props, props_len = properties.unpack( - self._in_packet['packet'][1:]) - self._easy_log(MQTT_LOG_DEBUG, "Received DISCONNECT %s %s", - reasonCode, - properties - ) - - self._sock_close() - self._do_on_disconnect( - packet_from_broker=True, - v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, # If reason is absent (remaining length < 1), it means normal disconnection - reason=reasonCode, - properties=properties, - ) - - def _handle_suback(self) -> None: - self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK") - pack_format = f"!H{len(self._in_packet['packet']) - 2}s" - (mid, packet) = struct.unpack(pack_format, self._in_packet['packet']) - - if self._protocol == MQTTv5: - properties = Properties(SUBACK >> 4) - props, props_len = properties.unpack(packet) - reasoncodes = [ReasonCode(SUBACK >> 4, identifier=c) for c in packet[props_len:]] - else: - pack_format = f"!{'B' * len(packet)}" - granted_qos = struct.unpack(pack_format, packet) - reasoncodes = [ReasonCode(SUBACK >> 4, identifier=c) for c in granted_qos] - properties = Properties(SUBACK >> 4) - - with self._callback_mutex: - on_subscribe = self.on_subscribe - - if on_subscribe: - with self._in_callback_mutex: # Don't call loop_write after _send_publish() - try: - if self._callback_api_version == CallbackAPIVersion.VERSION1: - if self._protocol == MQTTv5: - on_subscribe = cast(CallbackOnSubscribe_v1_mqtt5, on_subscribe) - - on_subscribe( - self, self._userdata, mid, reasoncodes, properties) - else: - on_subscribe = cast(CallbackOnSubscribe_v1_mqtt3, on_subscribe) - - on_subscribe( - self, self._userdata, mid, granted_qos) - elif self._callback_api_version == CallbackAPIVersion.VERSION2: - on_subscribe = cast(CallbackOnSubscribe_v2, on_subscribe) - - on_subscribe( - self, - self._userdata, - mid, - reasoncodes, - properties, - ) - else: - raise RuntimeError("Unsupported callback API version") - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_subscribe: %s', err) - if not self.suppress_exceptions: - raise - - def _handle_publish(self) -> MQTTErrorCode: - header = self._in_packet['command'] - message = MQTTMessage() - message.dup = ((header & 0x08) >> 3) != 0 - message.qos = (header & 0x06) >> 1 - message.retain = (header & 0x01) != 0 - - pack_format = f"!H{len(self._in_packet['packet']) - 2}s" - (slen, packet) = struct.unpack(pack_format, self._in_packet['packet']) - pack_format = f"!{slen}s{len(packet) - slen}s" - (topic, packet) = struct.unpack(pack_format, packet) - - if self._protocol != MQTTv5 and len(topic) == 0: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - # Handle topics with invalid UTF-8 - # This replaces an invalid topic with a message and the hex - # representation of the topic for logging. When the user attempts to - # access message.topic in the callback, an exception will be raised. - try: - print_topic = topic.decode('utf-8') - except UnicodeDecodeError: - print_topic = f"TOPIC WITH INVALID UTF-8: {topic!r}" - - message.topic = topic - - if message.qos > 0: - pack_format = f"!H{len(packet) - 2}s" - (message.mid, packet) = struct.unpack(pack_format, packet) - - if self._protocol == MQTTv5: - message.properties = Properties(PUBLISH >> 4) - props, props_len = message.properties.unpack(packet) - packet = packet[props_len:] - - message.payload = packet - - if self._protocol == MQTTv5: - self._easy_log( - MQTT_LOG_DEBUG, - "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)", - message.dup, message.qos, message.retain, message.mid, - print_topic, message.properties, len(message.payload) - ) - else: - self._easy_log( - MQTT_LOG_DEBUG, - "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)", - message.dup, message.qos, message.retain, message.mid, - print_topic, len(message.payload) - ) - - message.timestamp = time_func() - if message.qos == 0: - self._handle_on_message(message) - return MQTTErrorCode.MQTT_ERR_SUCCESS - elif message.qos == 1: - self._handle_on_message(message) - if self._manual_ack: - return MQTTErrorCode.MQTT_ERR_SUCCESS - else: - return self._send_puback(message.mid) - elif message.qos == 2: - - rc = self._send_pubrec(message.mid) - - message.state = mqtt_ms_wait_for_pubrel - with self._in_message_mutex: - self._in_messages[message.mid] = message - - return rc - else: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - def ack(self, mid: int, qos: int) -> MQTTErrorCode: - """ - send an acknowledgement for a given message id (stored in :py:attr:`message.mid `). - only useful in QoS>=1 and ``manual_ack=True`` (option of `Client`) - """ - if self._manual_ack : - if qos == 1: - return self._send_puback(mid) - elif qos == 2: - return self._send_pubcomp(mid) - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def manual_ack_set(self, on: bool) -> None: - """ - The paho library normally acknowledges messages as soon as they are delivered to the caller. - If manual_ack is turned on, then the caller MUST manually acknowledge every message once - application processing is complete using `ack()` - """ - self._manual_ack = on - - - def _handle_pubrel(self) -> MQTTErrorCode: - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] < 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - elif self._in_packet['remaining_length'] != 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - mid, = struct.unpack("!H", self._in_packet['packet'][:2]) - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] > 2: - reasonCode = ReasonCode(PUBREL >> 4) - reasonCode.unpack(self._in_packet['packet'][2:]) - if self._in_packet['remaining_length'] > 3: - properties = Properties(PUBREL >> 4) - props, props_len = properties.unpack( - self._in_packet['packet'][3:]) - self._easy_log(MQTT_LOG_DEBUG, "Received PUBREL (Mid: %d)", mid) - - with self._in_message_mutex: - if mid in self._in_messages: - # Only pass the message on if we have removed it from the queue - this - # prevents multiple callbacks for the same message. - message = self._in_messages.pop(mid) - self._handle_on_message(message) - self._inflight_messages -= 1 - if self._max_inflight_messages > 0: - with self._out_message_mutex: - rc = self._update_inflight() - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - - # FIXME: this should only be done if the message is known - # If unknown it's a protocol error and we should close the connection. - # But since we don't have (on disk) persistence for the session, it - # is possible that we must known about this message. - # Choose to acknowledge this message (thus losing a message) but - # avoid hanging. See #284. - if self._manual_ack: - return MQTTErrorCode.MQTT_ERR_SUCCESS - else: - return self._send_pubcomp(mid) - - def _update_inflight(self) -> MQTTErrorCode: - # Dont lock message_mutex here - for m in self._out_messages.values(): - if self._inflight_messages < self._max_inflight_messages: - if m.qos > 0 and m.state == mqtt_ms_queued: - self._inflight_messages += 1 - if m.qos == 1: - m.state = mqtt_ms_wait_for_puback - elif m.qos == 2: - m.state = mqtt_ms_wait_for_pubrec - rc = self._send_publish( - m.mid, - m.topic.encode('utf-8'), - m.payload, - m.qos, - m.retain, - m.dup, - properties=m.properties, - ) - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - else: - return MQTTErrorCode.MQTT_ERR_SUCCESS - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _handle_pubrec(self) -> MQTTErrorCode: - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] < 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - elif self._in_packet['remaining_length'] != 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - mid, = struct.unpack("!H", self._in_packet['packet'][:2]) - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] > 2: - reasonCode = ReasonCode(PUBREC >> 4) - reasonCode.unpack(self._in_packet['packet'][2:]) - if self._in_packet['remaining_length'] > 3: - properties = Properties(PUBREC >> 4) - props, props_len = properties.unpack( - self._in_packet['packet'][3:]) - self._easy_log(MQTT_LOG_DEBUG, "Received PUBREC (Mid: %d)", mid) - - with self._out_message_mutex: - if mid in self._out_messages: - msg = self._out_messages[mid] - msg.state = mqtt_ms_wait_for_pubcomp - msg.timestamp = time_func() - return self._send_pubrel(mid) - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _handle_unsuback(self) -> MQTTErrorCode: - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] < 4: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - elif self._in_packet['remaining_length'] != 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - mid, = struct.unpack("!H", self._in_packet['packet'][:2]) - if self._protocol == MQTTv5: - packet = self._in_packet['packet'][2:] - properties = Properties(UNSUBACK >> 4) - props, props_len = properties.unpack(packet) - reasoncodes_list = [ - ReasonCode(UNSUBACK >> 4, identifier=c) - for c in packet[props_len:] - ] - else: - reasoncodes_list = [] - properties = Properties(UNSUBACK >> 4) - - self._easy_log(MQTT_LOG_DEBUG, "Received UNSUBACK (Mid: %d)", mid) - with self._callback_mutex: - on_unsubscribe = self.on_unsubscribe - - if on_unsubscribe: - with self._in_callback_mutex: - try: - if self._callback_api_version == CallbackAPIVersion.VERSION1: - if self._protocol == MQTTv5: - on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt5, on_unsubscribe) - - reasoncodes: ReasonCode | list[ReasonCode] = reasoncodes_list - if len(reasoncodes_list) == 1: - reasoncodes = reasoncodes_list[0] - - on_unsubscribe( - self, self._userdata, mid, properties, reasoncodes) - else: - on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt3, on_unsubscribe) - - on_unsubscribe(self, self._userdata, mid) - elif self._callback_api_version == CallbackAPIVersion.VERSION2: - on_unsubscribe = cast(CallbackOnUnsubscribe_v2, on_unsubscribe) - - if properties is None: - properties = Properties(PacketTypes.CONNACK) - - on_unsubscribe( - self, - self._userdata, - mid, - reasoncodes_list, - properties, - ) - else: - raise RuntimeError("Unsupported callback API version") - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_unsubscribe: %s', err) - if not self.suppress_exceptions: - raise - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _do_on_disconnect( - self, - packet_from_broker: bool, - v1_rc: MQTTErrorCode, - reason: ReasonCode | None = None, - properties: Properties | None = None, - ) -> None: - with self._callback_mutex: - on_disconnect = self.on_disconnect - - if on_disconnect: - with self._in_callback_mutex: - try: - if self._callback_api_version == CallbackAPIVersion.VERSION1: - if self._protocol == MQTTv5: - on_disconnect = cast(CallbackOnDisconnect_v1_mqtt5, on_disconnect) - - if packet_from_broker: - on_disconnect(self, self._userdata, reason, properties) - else: - on_disconnect(self, self._userdata, v1_rc, None) - else: - on_disconnect = cast(CallbackOnDisconnect_v1_mqtt3, on_disconnect) - - on_disconnect(self, self._userdata, v1_rc) - elif self._callback_api_version == CallbackAPIVersion.VERSION2: - on_disconnect = cast(CallbackOnDisconnect_v2, on_disconnect) - - disconnect_flags = DisconnectFlags( - is_disconnect_packet_from_server=packet_from_broker - ) - - if reason is None: - reason = convert_disconnect_error_code_to_reason_code(v1_rc) - - if properties is None: - properties = Properties(PacketTypes.DISCONNECT) - - on_disconnect( - self, - self._userdata, - disconnect_flags, - reason, - properties, - ) - else: - raise RuntimeError("Unsupported callback API version") - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_disconnect: %s', err) - if not self.suppress_exceptions: - raise - - def _do_on_publish(self, mid: int, reason_code: ReasonCode, properties: Properties) -> MQTTErrorCode: - with self._callback_mutex: - on_publish = self.on_publish - - if on_publish: - with self._in_callback_mutex: - try: - if self._callback_api_version == CallbackAPIVersion.VERSION1: - on_publish = cast(CallbackOnPublish_v1, on_publish) - - on_publish(self, self._userdata, mid) - elif self._callback_api_version == CallbackAPIVersion.VERSION2: - on_publish = cast(CallbackOnPublish_v2, on_publish) - - on_publish( - self, - self._userdata, - mid, - reason_code, - properties, - ) - else: - raise RuntimeError("Unsupported callback API version") - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err) - if not self.suppress_exceptions: - raise - - msg = self._out_messages.pop(mid) - msg.info._set_as_published() - if msg.qos > 0: - self._inflight_messages -= 1 - if self._max_inflight_messages > 0: - rc = self._update_inflight() - if rc != MQTTErrorCode.MQTT_ERR_SUCCESS: - return rc - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _handle_pubackcomp( - self, cmd: Literal['PUBACK'] | Literal['PUBCOMP'] - ) -> MQTTErrorCode: - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] < 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - elif self._in_packet['remaining_length'] != 2: - return MQTTErrorCode.MQTT_ERR_PROTOCOL - - packet_type_enum = PUBACK if cmd == "PUBACK" else PUBCOMP - packet_type = packet_type_enum.value >> 4 - mid, = struct.unpack("!H", self._in_packet['packet'][:2]) - reasonCode = ReasonCode(packet_type) - properties = Properties(packet_type) - if self._protocol == MQTTv5: - if self._in_packet['remaining_length'] > 2: - reasonCode.unpack(self._in_packet['packet'][2:]) - if self._in_packet['remaining_length'] > 3: - props, props_len = properties.unpack( - self._in_packet['packet'][3:]) - self._easy_log(MQTT_LOG_DEBUG, "Received %s (Mid: %d)", cmd, mid) - - with self._out_message_mutex: - if mid in self._out_messages: - # Only inform the client the message has been sent once. - rc = self._do_on_publish(mid, reasonCode, properties) - return rc - - return MQTTErrorCode.MQTT_ERR_SUCCESS - - def _handle_on_message(self, message: MQTTMessage) -> None: - - try: - topic = message.topic - except UnicodeDecodeError: - topic = None - - on_message_callbacks = [] - with self._callback_mutex: - if topic is not None: - on_message_callbacks = list(self._on_message_filtered.iter_match(message.topic)) - - if len(on_message_callbacks) == 0: - on_message = self.on_message - else: - on_message = None - - for callback in on_message_callbacks: - with self._in_callback_mutex: - try: - callback(self, self._userdata, message) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, - 'Caught exception in user defined callback function %s: %s', - callback.__name__, - err - ) - if not self.suppress_exceptions: - raise - - if on_message: - with self._in_callback_mutex: - try: - on_message(self, self._userdata, message) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_message: %s', err) - if not self.suppress_exceptions: - raise - - - def _handle_on_connect_fail(self) -> None: - with self._callback_mutex: - on_connect_fail = self.on_connect_fail - - if on_connect_fail: - with self._in_callback_mutex: - try: - on_connect_fail(self, self._userdata) - except Exception as err: - self._easy_log( - MQTT_LOG_ERR, 'Caught exception in on_connect_fail: %s', err) - - def _thread_main(self) -> None: - try: - self.loop_forever(retry_first_connection=True) - finally: - self._thread = None - - def _reconnect_wait(self) -> None: - # See reconnect_delay_set for details - now = time_func() - with self._reconnect_delay_mutex: - if self._reconnect_delay is None: - self._reconnect_delay = self._reconnect_min_delay - else: - self._reconnect_delay = min( - self._reconnect_delay * 2, - self._reconnect_max_delay, - ) - - target_time = now + self._reconnect_delay - - remaining = target_time - now - while (self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) - and not self._thread_terminate - and remaining > 0): - - time.sleep(min(remaining, 1)) - remaining = target_time - time_func() - - @staticmethod - def _proxy_is_valid(p) -> bool: # type: ignore[no-untyped-def] - def check(t, a) -> bool: # type: ignore[no-untyped-def] - return (socks is not None and - t in {socks.HTTP, socks.SOCKS4, socks.SOCKS5} and a) - - if isinstance(p, dict): - return check(p.get("proxy_type"), p.get("proxy_addr")) - elif isinstance(p, (list, tuple)): - return len(p) == 6 and check(p[0], p[1]) - else: - return False - - def _get_proxy(self) -> dict[str, Any] | None: - if socks is None: - return None - - # First, check if the user explicitly passed us a proxy to use - if self._proxy_is_valid(self._proxy): - return self._proxy - - # Next, check for an mqtt_proxy environment variable as long as the host - # we're trying to connect to isn't listed under the no_proxy environment - # variable (matches built-in module urllib's behavior) - if not (hasattr(urllib.request, "proxy_bypass") and - urllib.request.proxy_bypass(self._host)): - env_proxies = urllib.request.getproxies() - if "mqtt" in env_proxies: - parts = urllib.parse.urlparse(env_proxies["mqtt"]) - if parts.scheme == "http": - proxy = { - "proxy_type": socks.HTTP, - "proxy_addr": parts.hostname, - "proxy_port": parts.port - } - return proxy - elif parts.scheme == "socks": - proxy = { - "proxy_type": socks.SOCKS5, - "proxy_addr": parts.hostname, - "proxy_port": parts.port - } - return proxy - - # Finally, check if the user has monkeypatched the PySocks library with - # a default proxy - socks_default = socks.get_default_proxy() - if self._proxy_is_valid(socks_default): - proxy_keys = ("proxy_type", "proxy_addr", "proxy_port", - "proxy_rdns", "proxy_username", "proxy_password") - return dict(zip(proxy_keys, socks_default)) - - # If we didn't find a proxy through any of the above methods, return - # None to indicate that the connection should be handled normally - return None - - def _create_socket(self) -> SocketLike: - if self._transport == "unix": - sock = self._create_unix_socket_connection() - else: - sock = self._create_socket_connection() - - if self._ssl: - sock = self._ssl_wrap_socket(sock) - - if self._transport == "websockets": - sock.settimeout(self._keepalive) - return _WebsocketWrapper( - socket=sock, - host=self._host, - port=self._port, - is_ssl=self._ssl, - path=self._websocket_path, - extra_headers=self._websocket_extra_headers, - ) - - return sock - - def _create_unix_socket_connection(self) -> _socket.socket: - unix_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - unix_socket.connect(self._host) - return unix_socket - - def _create_socket_connection(self) -> _socket.socket: - proxy = self._get_proxy() - addr = (self._host, self._port) - source = (self._bind_address, self._bind_port) - - if proxy: - return socks.create_connection(addr, timeout=self._connect_timeout, source_address=source, **proxy) - else: - return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source) - - def _ssl_wrap_socket(self, tcp_sock: _socket.socket) -> ssl.SSLSocket: - if self._ssl_context is None: - raise ValueError( - "Impossible condition. _ssl_context should never be None if _ssl is True" - ) - - verify_host = not self._tls_insecure - try: - # Try with server_hostname, even it's not supported in certain scenarios - ssl_sock = self._ssl_context.wrap_socket( - tcp_sock, - server_hostname=self._host, - do_handshake_on_connect=False, - ) - except ssl.CertificateError: - # CertificateError is derived from ValueError - raise - except ValueError: - # Python version requires SNI in order to handle server_hostname, but SNI is not available - ssl_sock = self._ssl_context.wrap_socket( - tcp_sock, - do_handshake_on_connect=False, - ) - else: - # If SSL context has already checked hostname, then don't need to do it again - if getattr(self._ssl_context, 'check_hostname', False): # type: ignore - verify_host = False - - ssl_sock.settimeout(self._keepalive) - ssl_sock.do_handshake() - - if verify_host: - # TODO: this type error is a true error: - # error: Module has no attribute "match_hostname" [attr-defined] - # Python 3.12 no longer have this method. - ssl.match_hostname(ssl_sock.getpeercert(), self._host) # type: ignore - - return ssl_sock - -class _WebsocketWrapper: - OPCODE_CONTINUATION = 0x0 - OPCODE_TEXT = 0x1 - OPCODE_BINARY = 0x2 - OPCODE_CONNCLOSE = 0x8 - OPCODE_PING = 0x9 - OPCODE_PONG = 0xa - - def __init__( - self, - socket: socket.socket | ssl.SSLSocket, - host: str, - port: int, - is_ssl: bool, - path: str, - extra_headers: WebSocketHeaders | None, - ): - self.connected = False - - self._ssl = is_ssl - self._host = host - self._port = port - self._socket = socket - self._path = path - - self._sendbuffer = bytearray() - self._readbuffer = bytearray() - - self._requested_size = 0 - self._payload_head = 0 - self._readbuffer_head = 0 - - self._do_handshake(extra_headers) - - def __del__(self) -> None: - self._sendbuffer = bytearray() - self._readbuffer = bytearray() - - def _do_handshake(self, extra_headers: WebSocketHeaders | None) -> None: - - sec_websocket_key = uuid.uuid4().bytes - sec_websocket_key = base64.b64encode(sec_websocket_key) - - if self._ssl: - default_port = 443 - http_schema = "https" - else: - default_port = 80 - http_schema = "http" - - if default_port == self._port: - host_port = f"{self._host}" - else: - host_port = f"{self._host}:{self._port}" - - websocket_headers = { - "Host": host_port, - "Upgrade": "websocket", - "Connection": "Upgrade", - "Origin": f"{http_schema}://{host_port}", - "Sec-WebSocket-Key": sec_websocket_key.decode("utf8"), - "Sec-Websocket-Version": "13", - "Sec-Websocket-Protocol": "mqtt", - } - - # This is checked in ws_set_options so it will either be None, a - # dictionary, or a callable - if isinstance(extra_headers, dict): - websocket_headers.update(extra_headers) - elif callable(extra_headers): - websocket_headers = extra_headers(websocket_headers) - - header = "\r\n".join([ - f"GET {self._path} HTTP/1.1", - "\r\n".join(f"{i}: {j}" for i, j in websocket_headers.items()), - "\r\n", - ]).encode("utf8") - - self._socket.send(header) - - has_secret = False - has_upgrade = False - - while True: - # read HTTP response header as lines - try: - byte = self._socket.recv(1) - except ConnectionResetError: - byte = b"" - - self._readbuffer.extend(byte) - - # line end - if byte == b"\n": - if len(self._readbuffer) > 2: - # check upgrade - if b"connection" in str(self._readbuffer).lower().encode('utf-8'): - if b"upgrade" not in str(self._readbuffer).lower().encode('utf-8'): - raise WebsocketConnectionError( - "WebSocket handshake error, connection not upgraded") - else: - has_upgrade = True - - # check key hash - if b"sec-websocket-accept" in str(self._readbuffer).lower().encode('utf-8'): - GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - - server_hash_str = self._readbuffer.decode( - 'utf-8').split(": ", 1)[1] - server_hash = server_hash_str.strip().encode('utf-8') - - client_hash_key = sec_websocket_key.decode('utf-8') + GUID - # Use of SHA-1 is OK here; it's according to the Websocket spec. - client_hash_digest = hashlib.sha1(client_hash_key.encode('utf-8')) # noqa: S324 - client_hash = base64.b64encode(client_hash_digest.digest()) - - if server_hash != client_hash: - raise WebsocketConnectionError( - "WebSocket handshake error, invalid secret key") - else: - has_secret = True - else: - # ending linebreak - break - - # reset linebuffer - self._readbuffer = bytearray() - - # connection reset - elif not byte: - raise WebsocketConnectionError("WebSocket handshake error") - - if not has_upgrade or not has_secret: - raise WebsocketConnectionError("WebSocket handshake error") - - self._readbuffer = bytearray() - self.connected = True - - def _create_frame( - self, opcode: int, data: bytearray, do_masking: int = 1 - ) -> bytearray: - header = bytearray() - length = len(data) - - mask_key = bytearray(os.urandom(4)) - mask_flag = do_masking - - # 1 << 7 is the final flag, we don't send continuated data - header.append(1 << 7 | opcode) - - if length < 126: - header.append(mask_flag << 7 | length) - - elif length < 65536: - header.append(mask_flag << 7 | 126) - header += struct.pack("!H", length) - - elif length < 0x8000000000000001: - header.append(mask_flag << 7 | 127) - header += struct.pack("!Q", length) - - else: - raise ValueError("Maximum payload size is 2^63") - - if mask_flag == 1: - for index in range(length): - data[index] ^= mask_key[index % 4] - data = mask_key + data - - return header + data - - def _buffered_read(self, length: int) -> bytearray: - - # try to recv and store needed bytes - wanted_bytes = length - (len(self._readbuffer) - self._readbuffer_head) - if wanted_bytes > 0: - - data = self._socket.recv(wanted_bytes) - - if not data: - raise ConnectionAbortedError - else: - self._readbuffer.extend(data) - - if len(data) < wanted_bytes: - raise BlockingIOError - - self._readbuffer_head += length - return self._readbuffer[self._readbuffer_head - length:self._readbuffer_head] - - def _recv_impl(self, length: int) -> bytes: - - # try to decode websocket payload part from data - try: - - self._readbuffer_head = 0 - - result = b"" - - chunk_startindex = self._payload_head - chunk_endindex = self._payload_head + length - - header1 = self._buffered_read(1) - header2 = self._buffered_read(1) - - opcode = (header1[0] & 0x0f) - maskbit = (header2[0] & 0x80) == 0x80 - lengthbits = (header2[0] & 0x7f) - payload_length = lengthbits - mask_key = None - - # read length - if lengthbits == 0x7e: - - value = self._buffered_read(2) - payload_length, = struct.unpack("!H", value) - - elif lengthbits == 0x7f: - - value = self._buffered_read(8) - payload_length, = struct.unpack("!Q", value) - - # read mask - if maskbit: - mask_key = self._buffered_read(4) - - # if frame payload is shorter than the requested data, read only the possible part - readindex = chunk_endindex - if payload_length < readindex: - readindex = payload_length - - if readindex > 0: - # get payload chunk - payload = self._buffered_read(readindex) - - # unmask only the needed part - if mask_key is not None: - for index in range(chunk_startindex, readindex): - payload[index] ^= mask_key[index % 4] - - result = payload[chunk_startindex:readindex] - self._payload_head = readindex - else: - payload = bytearray() - - # check if full frame arrived and reset readbuffer and payloadhead if needed - if readindex == payload_length: - self._readbuffer = bytearray() - self._payload_head = 0 - - # respond to non-binary opcodes, their arrival is not guaranteed because of non-blocking sockets - if opcode == _WebsocketWrapper.OPCODE_CONNCLOSE: - frame = self._create_frame( - _WebsocketWrapper.OPCODE_CONNCLOSE, payload, 0) - self._socket.send(frame) - - if opcode == _WebsocketWrapper.OPCODE_PING: - frame = self._create_frame( - _WebsocketWrapper.OPCODE_PONG, payload, 0) - self._socket.send(frame) - - # This isn't *proper* handling of continuation frames, but given - # that we only support binary frames, it is *probably* good enough. - if (opcode == _WebsocketWrapper.OPCODE_BINARY or opcode == _WebsocketWrapper.OPCODE_CONTINUATION) \ - and payload_length > 0: - return result - else: - raise BlockingIOError - - except ConnectionError: - self.connected = False - return b'' - - def _send_impl(self, data: bytes) -> int: - - # if previous frame was sent successfully - if len(self._sendbuffer) == 0: - # create websocket frame - frame = self._create_frame( - _WebsocketWrapper.OPCODE_BINARY, bytearray(data)) - self._sendbuffer.extend(frame) - self._requested_size = len(data) - - # try to write out as much as possible - length = self._socket.send(self._sendbuffer) - - self._sendbuffer = self._sendbuffer[length:] - - if len(self._sendbuffer) == 0: - # buffer sent out completely, return with payload's size - return self._requested_size - else: - # couldn't send whole data, request the same data again with 0 as sent length - return 0 - - def recv(self, length: int) -> bytes: - return self._recv_impl(length) - - def read(self, length: int) -> bytes: - return self._recv_impl(length) - - def send(self, data: bytes) -> int: - return self._send_impl(data) - - def write(self, data: bytes) -> int: - return self._send_impl(data) - - def close(self) -> None: - self._socket.close() - - def fileno(self) -> int: - return self._socket.fileno() - - def pending(self) -> int: - # Fix for bug #131: a SSL socket may still have data available - # for reading without select() being aware of it. - if self._ssl: - return self._socket.pending() # type: ignore[union-attr] - else: - # normal socket rely only on select() - return 0 - - def setblocking(self, flag: bool) -> None: - self._socket.setblocking(flag) diff --git a/sbapp/mqtt/enums.py b/sbapp/mqtt/enums.py deleted file mode 100644 index 5428769..0000000 --- a/sbapp/mqtt/enums.py +++ /dev/null @@ -1,113 +0,0 @@ -import enum - - -class MQTTErrorCode(enum.IntEnum): - MQTT_ERR_AGAIN = -1 - MQTT_ERR_SUCCESS = 0 - MQTT_ERR_NOMEM = 1 - MQTT_ERR_PROTOCOL = 2 - MQTT_ERR_INVAL = 3 - MQTT_ERR_NO_CONN = 4 - MQTT_ERR_CONN_REFUSED = 5 - MQTT_ERR_NOT_FOUND = 6 - MQTT_ERR_CONN_LOST = 7 - MQTT_ERR_TLS = 8 - MQTT_ERR_PAYLOAD_SIZE = 9 - MQTT_ERR_NOT_SUPPORTED = 10 - MQTT_ERR_AUTH = 11 - MQTT_ERR_ACL_DENIED = 12 - MQTT_ERR_UNKNOWN = 13 - MQTT_ERR_ERRNO = 14 - MQTT_ERR_QUEUE_SIZE = 15 - MQTT_ERR_KEEPALIVE = 16 - - -class MQTTProtocolVersion(enum.IntEnum): - MQTTv31 = 3 - MQTTv311 = 4 - MQTTv5 = 5 - - -class CallbackAPIVersion(enum.Enum): - """Defined the arguments passed to all user-callback. - - See each callbacks for details: `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`, - `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`, - `on_socket_register_write`, `on_socket_unregister_write` - """ - VERSION1 = 1 - """The version used with paho-mqtt 1.x before introducing CallbackAPIVersion. - - This version had different arguments depending if MQTTv5 or MQTTv3 was used. `Properties` & `ReasonCode` were missing - on some callback (apply only to MQTTv5). - - This version is deprecated and will be removed in version 3.0. - """ - VERSION2 = 2 - """ This version fix some of the shortcoming of previous version. - - Callback have the same signature if using MQTTv5 or MQTTv3. `ReasonCode` are used in MQTTv3. - """ - - -class MessageType(enum.IntEnum): - CONNECT = 0x10 - CONNACK = 0x20 - PUBLISH = 0x30 - PUBACK = 0x40 - PUBREC = 0x50 - PUBREL = 0x60 - PUBCOMP = 0x70 - SUBSCRIBE = 0x80 - SUBACK = 0x90 - UNSUBSCRIBE = 0xA0 - UNSUBACK = 0xB0 - PINGREQ = 0xC0 - PINGRESP = 0xD0 - DISCONNECT = 0xE0 - AUTH = 0xF0 - - -class LogLevel(enum.IntEnum): - MQTT_LOG_INFO = 0x01 - MQTT_LOG_NOTICE = 0x02 - MQTT_LOG_WARNING = 0x04 - MQTT_LOG_ERR = 0x08 - MQTT_LOG_DEBUG = 0x10 - - -class ConnackCode(enum.IntEnum): - CONNACK_ACCEPTED = 0 - CONNACK_REFUSED_PROTOCOL_VERSION = 1 - CONNACK_REFUSED_IDENTIFIER_REJECTED = 2 - CONNACK_REFUSED_SERVER_UNAVAILABLE = 3 - CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4 - CONNACK_REFUSED_NOT_AUTHORIZED = 5 - - -class _ConnectionState(enum.Enum): - MQTT_CS_NEW = enum.auto() - MQTT_CS_CONNECT_ASYNC = enum.auto() - MQTT_CS_CONNECTING = enum.auto() - MQTT_CS_CONNECTED = enum.auto() - MQTT_CS_CONNECTION_LOST = enum.auto() - MQTT_CS_DISCONNECTING = enum.auto() - MQTT_CS_DISCONNECTED = enum.auto() - - -class MessageState(enum.IntEnum): - MQTT_MS_INVALID = 0 - MQTT_MS_PUBLISH = 1 - MQTT_MS_WAIT_FOR_PUBACK = 2 - MQTT_MS_WAIT_FOR_PUBREC = 3 - MQTT_MS_RESEND_PUBREL = 4 - MQTT_MS_WAIT_FOR_PUBREL = 5 - MQTT_MS_RESEND_PUBCOMP = 6 - MQTT_MS_WAIT_FOR_PUBCOMP = 7 - MQTT_MS_SEND_PUBREC = 8 - MQTT_MS_QUEUED = 9 - - -class PahoClientMode(enum.IntEnum): - MQTT_CLIENT = 0 - MQTT_BRIDGE = 1 diff --git a/sbapp/mqtt/matcher.py b/sbapp/mqtt/matcher.py deleted file mode 100644 index b73c13a..0000000 --- a/sbapp/mqtt/matcher.py +++ /dev/null @@ -1,78 +0,0 @@ -class MQTTMatcher: - """Intended to manage topic filters including wildcards. - - Internally, MQTTMatcher use a prefix tree (trie) to store - values associated with filters, and has an iter_match() - method to iterate efficiently over all filters that match - some topic name.""" - - class Node: - __slots__ = '_children', '_content' - - def __init__(self): - self._children = {} - self._content = None - - def __init__(self): - self._root = self.Node() - - def __setitem__(self, key, value): - """Add a topic filter :key to the prefix tree - and associate it to :value""" - node = self._root - for sym in key.split('/'): - node = node._children.setdefault(sym, self.Node()) - node._content = value - - def __getitem__(self, key): - """Retrieve the value associated with some topic filter :key""" - try: - node = self._root - for sym in key.split('/'): - node = node._children[sym] - if node._content is None: - raise KeyError(key) - return node._content - except KeyError as ke: - raise KeyError(key) from ke - - def __delitem__(self, key): - """Delete the value associated with some topic filter :key""" - lst = [] - try: - parent, node = None, self._root - for k in key.split('/'): - parent, node = node, node._children[k] - lst.append((parent, k, node)) - # TODO - node._content = None - except KeyError as ke: - raise KeyError(key) from ke - else: # cleanup - for parent, k, node in reversed(lst): - if node._children or node._content is not None: - break - del parent._children[k] - - def iter_match(self, topic): - """Return an iterator on all values associated with filters - that match the :topic""" - lst = topic.split('/') - normal = not topic.startswith('$') - def rec(node, i=0): - if i == len(lst): - if node._content is not None: - yield node._content - else: - part = lst[i] - if part in node._children: - for content in rec(node._children[part], i + 1): - yield content - if '+' in node._children and (normal or i > 0): - for content in rec(node._children['+'], i + 1): - yield content - if '#' in node._children and (normal or i > 0): - content = node._children['#']._content - if content is not None: - yield content - return rec(self._root) diff --git a/sbapp/mqtt/packettypes.py b/sbapp/mqtt/packettypes.py deleted file mode 100644 index d205149..0000000 --- a/sbapp/mqtt/packettypes.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -******************************************************************* - Copyright (c) 2017, 2019 IBM Corp. - - All rights reserved. This program and the accompanying materials - are made available under the terms of the Eclipse Public License v2.0 - and Eclipse Distribution License v1.0 which accompany this distribution. - - The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v20.html - and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - - Contributors: - Ian Craggs - initial implementation and/or documentation -******************************************************************* -""" - - -class PacketTypes: - - """ - Packet types class. Includes the AUTH packet for MQTT v5.0. - - Holds constants for each packet type such as PacketTypes.PUBLISH - and packet name strings: PacketTypes.Names[PacketTypes.PUBLISH]. - - """ - - indexes = range(1, 16) - - # Packet types - CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, \ - PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, \ - PINGREQ, PINGRESP, DISCONNECT, AUTH = indexes - - # Dummy packet type for properties use - will delay only applies to will - WILLMESSAGE = 99 - - Names = ( "reserved", \ - "Connect", "Connack", "Publish", "Puback", "Pubrec", "Pubrel", \ - "Pubcomp", "Subscribe", "Suback", "Unsubscribe", "Unsuback", \ - "Pingreq", "Pingresp", "Disconnect", "Auth") diff --git a/sbapp/mqtt/properties.py b/sbapp/mqtt/properties.py deleted file mode 100644 index f307b86..0000000 --- a/sbapp/mqtt/properties.py +++ /dev/null @@ -1,421 +0,0 @@ -# ******************************************************************* -# Copyright (c) 2017, 2019 IBM Corp. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v2.0 -# and Eclipse Distribution License v1.0 which accompany this distribution. -# -# The Eclipse Public License is available at -# http://www.eclipse.org/legal/epl-v20.html -# and the Eclipse Distribution License is available at -# http://www.eclipse.org/org/documents/edl-v10.php. -# -# Contributors: -# Ian Craggs - initial implementation and/or documentation -# ******************************************************************* - -import struct - -from .packettypes import PacketTypes - - -class MQTTException(Exception): - pass - - -class MalformedPacket(MQTTException): - pass - - -def writeInt16(length): - # serialize a 16 bit integer to network format - return bytearray(struct.pack("!H", length)) - - -def readInt16(buf): - # deserialize a 16 bit integer from network format - return struct.unpack("!H", buf[:2])[0] - - -def writeInt32(length): - # serialize a 32 bit integer to network format - return bytearray(struct.pack("!L", length)) - - -def readInt32(buf): - # deserialize a 32 bit integer from network format - return struct.unpack("!L", buf[:4])[0] - - -def writeUTF(data): - # data could be a string, or bytes. If string, encode into bytes with utf-8 - if not isinstance(data, bytes): - data = bytes(data, "utf-8") - return writeInt16(len(data)) + data - - -def readUTF(buffer, maxlen): - if maxlen >= 2: - length = readInt16(buffer) - else: - raise MalformedPacket("Not enough data to read string length") - maxlen -= 2 - if length > maxlen: - raise MalformedPacket("Length delimited string too long") - buf = buffer[2:2+length].decode("utf-8") - # look for chars which are invalid for MQTT - for c in buf: # look for D800-DFFF in the UTF string - ord_c = ord(c) - if ord_c >= 0xD800 and ord_c <= 0xDFFF: - raise MalformedPacket("[MQTT-1.5.4-1] D800-DFFF found in UTF-8 data") - if ord_c == 0x00: # look for null in the UTF string - raise MalformedPacket("[MQTT-1.5.4-2] Null found in UTF-8 data") - if ord_c == 0xFEFF: - raise MalformedPacket("[MQTT-1.5.4-3] U+FEFF in UTF-8 data") - return buf, length+2 - - -def writeBytes(buffer): - return writeInt16(len(buffer)) + buffer - - -def readBytes(buffer): - length = readInt16(buffer) - return buffer[2:2+length], length+2 - - -class VariableByteIntegers: # Variable Byte Integer - """ - MQTT variable byte integer helper class. Used - in several places in MQTT v5.0 properties. - - """ - - @staticmethod - def encode(x): - """ - Convert an integer 0 <= x <= 268435455 into multi-byte format. - Returns the buffer converted from the integer. - """ - if not 0 <= x <= 268435455: - raise ValueError(f"Value {x!r} must be in range 0-268435455") - buffer = b'' - while 1: - digit = x % 128 - x //= 128 - if x > 0: - digit |= 0x80 - buffer += bytes([digit]) - if x == 0: - break - return buffer - - @staticmethod - def decode(buffer): - """ - Get the value of a multi-byte integer from a buffer - Return the value, and the number of bytes used. - - [MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value - """ - multiplier = 1 - value = 0 - bytes = 0 - while 1: - bytes += 1 - digit = buffer[0] - buffer = buffer[1:] - value += (digit & 127) * multiplier - if digit & 128 == 0: - break - multiplier *= 128 - return (value, bytes) - - -class Properties: - """MQTT v5.0 properties class. - - See Properties.names for a list of accepted property names along with their numeric values. - - See Properties.properties for the data type of each property. - - Example of use:: - - publish_properties = Properties(PacketTypes.PUBLISH) - publish_properties.UserProperty = ("a", "2") - publish_properties.UserProperty = ("c", "3") - - First the object is created with packet type as argument, no properties will be present at - this point. Then properties are added as attributes, the name of which is the string property - name without the spaces. - - """ - - def __init__(self, packetType): - self.packetType = packetType - self.types = ["Byte", "Two Byte Integer", "Four Byte Integer", "Variable Byte Integer", - "Binary Data", "UTF-8 Encoded String", "UTF-8 String Pair"] - - self.names = { - "Payload Format Indicator": 1, - "Message Expiry Interval": 2, - "Content Type": 3, - "Response Topic": 8, - "Correlation Data": 9, - "Subscription Identifier": 11, - "Session Expiry Interval": 17, - "Assigned Client Identifier": 18, - "Server Keep Alive": 19, - "Authentication Method": 21, - "Authentication Data": 22, - "Request Problem Information": 23, - "Will Delay Interval": 24, - "Request Response Information": 25, - "Response Information": 26, - "Server Reference": 28, - "Reason String": 31, - "Receive Maximum": 33, - "Topic Alias Maximum": 34, - "Topic Alias": 35, - "Maximum QoS": 36, - "Retain Available": 37, - "User Property": 38, - "Maximum Packet Size": 39, - "Wildcard Subscription Available": 40, - "Subscription Identifier Available": 41, - "Shared Subscription Available": 42 - } - - self.properties = { - # id: type, packets - # payload format indicator - 1: (self.types.index("Byte"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), - 2: (self.types.index("Four Byte Integer"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), - 3: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), - 8: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), - 9: (self.types.index("Binary Data"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), - 11: (self.types.index("Variable Byte Integer"), - [PacketTypes.PUBLISH, PacketTypes.SUBSCRIBE]), - 17: (self.types.index("Four Byte Integer"), - [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.DISCONNECT]), - 18: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), - 19: (self.types.index("Two Byte Integer"), [PacketTypes.CONNACK]), - 21: (self.types.index("UTF-8 Encoded String"), - [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), - 22: (self.types.index("Binary Data"), - [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), - 23: (self.types.index("Byte"), - [PacketTypes.CONNECT]), - 24: (self.types.index("Four Byte Integer"), [PacketTypes.WILLMESSAGE]), - 25: (self.types.index("Byte"), [PacketTypes.CONNECT]), - 26: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), - 28: (self.types.index("UTF-8 Encoded String"), - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]), - 31: (self.types.index("UTF-8 Encoded String"), - [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, - PacketTypes.PUBREL, PacketTypes.PUBCOMP, PacketTypes.SUBACK, - PacketTypes.UNSUBACK, PacketTypes.DISCONNECT, PacketTypes.AUTH]), - 33: (self.types.index("Two Byte Integer"), - [PacketTypes.CONNECT, PacketTypes.CONNACK]), - 34: (self.types.index("Two Byte Integer"), - [PacketTypes.CONNECT, PacketTypes.CONNACK]), - 35: (self.types.index("Two Byte Integer"), [PacketTypes.PUBLISH]), - 36: (self.types.index("Byte"), [PacketTypes.CONNACK]), - 37: (self.types.index("Byte"), [PacketTypes.CONNACK]), - 38: (self.types.index("UTF-8 String Pair"), - [PacketTypes.CONNECT, PacketTypes.CONNACK, - PacketTypes.PUBLISH, PacketTypes.PUBACK, - PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, - PacketTypes.SUBSCRIBE, PacketTypes.SUBACK, - PacketTypes.UNSUBSCRIBE, PacketTypes.UNSUBACK, - PacketTypes.DISCONNECT, PacketTypes.AUTH, PacketTypes.WILLMESSAGE]), - 39: (self.types.index("Four Byte Integer"), - [PacketTypes.CONNECT, PacketTypes.CONNACK]), - 40: (self.types.index("Byte"), [PacketTypes.CONNACK]), - 41: (self.types.index("Byte"), [PacketTypes.CONNACK]), - 42: (self.types.index("Byte"), [PacketTypes.CONNACK]), - } - - def allowsMultiple(self, compressedName): - return self.getIdentFromName(compressedName) in [11, 38] - - def getIdentFromName(self, compressedName): - # return the identifier corresponding to the property name - result = -1 - for name in self.names.keys(): - if compressedName == name.replace(' ', ''): - result = self.names[name] - break - return result - - def __setattr__(self, name, value): - name = name.replace(' ', '') - privateVars = ["packetType", "types", "names", "properties"] - if name in privateVars: - object.__setattr__(self, name, value) - else: - # the name could have spaces in, or not. Remove spaces before assignment - if name not in [aname.replace(' ', '') for aname in self.names.keys()]: - raise MQTTException( - f"Property name must be one of {self.names.keys()}") - # check that this attribute applies to the packet type - if self.packetType not in self.properties[self.getIdentFromName(name)][1]: - raise MQTTException(f"Property {name} does not apply to packet type {PacketTypes.Names[self.packetType]}") - - # Check for forbidden values - if not isinstance(value, list): - if name in ["ReceiveMaximum", "TopicAlias"] \ - and (value < 1 or value > 65535): - - raise MQTTException(f"{name} property value must be in the range 1-65535") - elif name in ["TopicAliasMaximum"] \ - and (value < 0 or value > 65535): - - raise MQTTException(f"{name} property value must be in the range 0-65535") - elif name in ["MaximumPacketSize", "SubscriptionIdentifier"] \ - and (value < 1 or value > 268435455): - - raise MQTTException(f"{name} property value must be in the range 1-268435455") - elif name in ["RequestResponseInformation", "RequestProblemInformation", "PayloadFormatIndicator"] \ - and (value != 0 and value != 1): - - raise MQTTException( - f"{name} property value must be 0 or 1") - - if self.allowsMultiple(name): - if not isinstance(value, list): - value = [value] - if hasattr(self, name): - value = object.__getattribute__(self, name) + value - object.__setattr__(self, name, value) - - def __str__(self): - buffer = "[" - first = True - for name in self.names.keys(): - compressedName = name.replace(' ', '') - if hasattr(self, compressedName): - if not first: - buffer += ", " - buffer += f"{compressedName} : {getattr(self, compressedName)}" - first = False - buffer += "]" - return buffer - - def json(self): - data = {} - for name in self.names.keys(): - compressedName = name.replace(' ', '') - if hasattr(self, compressedName): - val = getattr(self, compressedName) - if compressedName == 'CorrelationData' and isinstance(val, bytes): - data[compressedName] = val.hex() - else: - data[compressedName] = val - return data - - def isEmpty(self): - rc = True - for name in self.names.keys(): - compressedName = name.replace(' ', '') - if hasattr(self, compressedName): - rc = False - break - return rc - - def clear(self): - for name in self.names.keys(): - compressedName = name.replace(' ', '') - if hasattr(self, compressedName): - delattr(self, compressedName) - - def writeProperty(self, identifier, type, value): - buffer = b"" - buffer += VariableByteIntegers.encode(identifier) # identifier - if type == self.types.index("Byte"): # value - buffer += bytes([value]) - elif type == self.types.index("Two Byte Integer"): - buffer += writeInt16(value) - elif type == self.types.index("Four Byte Integer"): - buffer += writeInt32(value) - elif type == self.types.index("Variable Byte Integer"): - buffer += VariableByteIntegers.encode(value) - elif type == self.types.index("Binary Data"): - buffer += writeBytes(value) - elif type == self.types.index("UTF-8 Encoded String"): - buffer += writeUTF(value) - elif type == self.types.index("UTF-8 String Pair"): - buffer += writeUTF(value[0]) + writeUTF(value[1]) - return buffer - - def pack(self): - # serialize properties into buffer for sending over network - buffer = b"" - for name in self.names.keys(): - compressedName = name.replace(' ', '') - if hasattr(self, compressedName): - identifier = self.getIdentFromName(compressedName) - attr_type = self.properties[identifier][0] - if self.allowsMultiple(compressedName): - for prop in getattr(self, compressedName): - buffer += self.writeProperty(identifier, - attr_type, prop) - else: - buffer += self.writeProperty(identifier, attr_type, - getattr(self, compressedName)) - return VariableByteIntegers.encode(len(buffer)) + buffer - - def readProperty(self, buffer, type, propslen): - if type == self.types.index("Byte"): - value = buffer[0] - valuelen = 1 - elif type == self.types.index("Two Byte Integer"): - value = readInt16(buffer) - valuelen = 2 - elif type == self.types.index("Four Byte Integer"): - value = readInt32(buffer) - valuelen = 4 - elif type == self.types.index("Variable Byte Integer"): - value, valuelen = VariableByteIntegers.decode(buffer) - elif type == self.types.index("Binary Data"): - value, valuelen = readBytes(buffer) - elif type == self.types.index("UTF-8 Encoded String"): - value, valuelen = readUTF(buffer, propslen) - elif type == self.types.index("UTF-8 String Pair"): - value, valuelen = readUTF(buffer, propslen) - buffer = buffer[valuelen:] # strip the bytes used by the value - value1, valuelen1 = readUTF(buffer, propslen - valuelen) - value = (value, value1) - valuelen += valuelen1 - return value, valuelen - - def getNameFromIdent(self, identifier): - rc = None - for name in self.names: - if self.names[name] == identifier: - rc = name - return rc - - def unpack(self, buffer): - self.clear() - # deserialize properties into attributes from buffer received from network - propslen, VBIlen = VariableByteIntegers.decode(buffer) - buffer = buffer[VBIlen:] # strip the bytes used by the VBI - propslenleft = propslen - while propslenleft > 0: # properties length is 0 if there are none - identifier, VBIlen2 = VariableByteIntegers.decode( - buffer) # property identifier - buffer = buffer[VBIlen2:] # strip the bytes used by the VBI - propslenleft -= VBIlen2 - attr_type = self.properties[identifier][0] - value, valuelen = self.readProperty( - buffer, attr_type, propslenleft) - buffer = buffer[valuelen:] # strip the bytes used by the value - propslenleft -= valuelen - propname = self.getNameFromIdent(identifier) - compressedName = propname.replace(' ', '') - if not self.allowsMultiple(compressedName) and hasattr(self, compressedName): - raise MQTTException( - f"Property '{property}' must not exist more than once") - setattr(self, propname, value) - return self, propslen + VBIlen diff --git a/sbapp/mqtt/publish.py b/sbapp/mqtt/publish.py deleted file mode 100644 index 333c190..0000000 --- a/sbapp/mqtt/publish.py +++ /dev/null @@ -1,306 +0,0 @@ -# Copyright (c) 2014 Roger Light -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v2.0 -# and Eclipse Distribution License v1.0 which accompany this distribution. -# -# The Eclipse Public License is available at -# http://www.eclipse.org/legal/epl-v20.html -# and the Eclipse Distribution License is available at -# http://www.eclipse.org/org/documents/edl-v10.php. -# -# Contributors: -# Roger Light - initial API and implementation - -""" -This module provides some helper functions to allow straightforward publishing -of messages in a one-shot manner. In other words, they are useful for the -situation where you have a single/multiple messages you want to publish to a -broker, then disconnect and nothing else is required. -""" -from __future__ import annotations - -import collections -from collections.abc import Iterable -from typing import TYPE_CHECKING, Any, List, Tuple, Union - -from paho.mqtt.enums import CallbackAPIVersion, MQTTProtocolVersion -from paho.mqtt.properties import Properties -from paho.mqtt.reasoncodes import ReasonCode - -from .. import mqtt -from . import client as paho - -if TYPE_CHECKING: - try: - from typing import NotRequired, Required, TypedDict # type: ignore - except ImportError: - from typing_extensions import NotRequired, Required, TypedDict - - try: - from typing import Literal - except ImportError: - from typing_extensions import Literal # type: ignore - - - - class AuthParameter(TypedDict, total=False): - username: Required[str] - password: NotRequired[str] - - - class TLSParameter(TypedDict, total=False): - ca_certs: Required[str] - certfile: NotRequired[str] - keyfile: NotRequired[str] - tls_version: NotRequired[int] - ciphers: NotRequired[str] - insecure: NotRequired[bool] - - - class MessageDict(TypedDict, total=False): - topic: Required[str] - payload: NotRequired[paho.PayloadType] - qos: NotRequired[int] - retain: NotRequired[bool] - - MessageTuple = Tuple[str, paho.PayloadType, int, bool] - - MessagesList = List[Union[MessageDict, MessageTuple]] - - -def _do_publish(client: paho.Client): - """Internal function""" - - message = client._userdata.popleft() - - if isinstance(message, dict): - client.publish(**message) - elif isinstance(message, (tuple, list)): - client.publish(*message) - else: - raise TypeError('message must be a dict, tuple, or list') - - -def _on_connect(client: paho.Client, userdata: MessagesList, flags, reason_code, properties): - """Internal v5 callback""" - if reason_code == 0: - if len(userdata) > 0: - _do_publish(client) - else: - raise mqtt.MQTTException(paho.connack_string(reason_code)) - - -def _on_publish( - client: paho.Client, userdata: collections.deque[MessagesList], mid: int, reason_codes: ReasonCode, properties: Properties, -) -> None: - """Internal callback""" - #pylint: disable=unused-argument - - if len(userdata) == 0: - client.disconnect() - else: - _do_publish(client) - - -def multiple( - msgs: MessagesList, - hostname: str = "localhost", - port: int = 1883, - client_id: str = "", - keepalive: int = 60, - will: MessageDict | None = None, - auth: AuthParameter | None = None, - tls: TLSParameter | None = None, - protocol: MQTTProtocolVersion = paho.MQTTv311, - transport: Literal["tcp", "websockets"] = "tcp", - proxy_args: Any | None = None, -) -> None: - """Publish multiple messages to a broker, then disconnect cleanly. - - This function creates an MQTT client, connects to a broker and publishes a - list of messages. Once the messages have been delivered, it disconnects - cleanly from the broker. - - :param msgs: a list of messages to publish. Each message is either a dict or a - tuple. - - If a dict, only the topic must be present. Default values will be - used for any missing arguments. The dict must be of the form: - - msg = {'topic':"", 'payload':"", 'qos':, - 'retain':} - topic must be present and may not be empty. - If payload is "", None or not present then a zero length payload - will be published. - If qos is not present, the default of 0 is used. - If retain is not present, the default of False is used. - - If a tuple, then it must be of the form: - ("", "", qos, retain) - - :param str hostname: the address of the broker to connect to. - Defaults to localhost. - - :param int port: the port to connect to the broker on. Defaults to 1883. - - :param str client_id: the MQTT client id to use. If "" or None, the Paho library will - generate a client id automatically. - - :param int keepalive: the keepalive timeout value for the client. Defaults to 60 - seconds. - - :param will: a dict containing will parameters for the client: will = {'topic': - "", 'payload':", 'qos':, 'retain':}. - Topic is required, all other parameters are optional and will - default to None, 0 and False respectively. - Defaults to None, which indicates no will should be used. - - :param auth: a dict containing authentication parameters for the client: - auth = {'username':"", 'password':""} - Username is required, password is optional and will default to None - if not provided. - Defaults to None, which indicates no authentication is to be used. - - :param tls: a dict containing TLS configuration parameters for the client: - dict = {'ca_certs':"", 'certfile':"", - 'keyfile':"", 'tls_version':"", - 'ciphers':", 'insecure':""} - ca_certs is required, all other parameters are optional and will - default to None if not provided, which results in the client using - the default behaviour - see the paho.mqtt.client documentation. - Alternatively, tls input can be an SSLContext object, which will be - processed using the tls_set_context method. - Defaults to None, which indicates that TLS should not be used. - - :param str transport: set to "tcp" to use the default setting of transport which is - raw TCP. Set to "websockets" to use WebSockets as the transport. - - :param proxy_args: a dictionary that will be given to the client. - """ - - if not isinstance(msgs, Iterable): - raise TypeError('msgs must be an iterable') - if len(msgs) == 0: - raise ValueError('msgs is empty') - - client = paho.Client( - CallbackAPIVersion.VERSION2, - client_id=client_id, - userdata=collections.deque(msgs), - protocol=protocol, - transport=transport, - ) - - client.enable_logger() - client.on_publish = _on_publish - client.on_connect = _on_connect # type: ignore - - if proxy_args is not None: - client.proxy_set(**proxy_args) - - if auth: - username = auth.get('username') - if username: - password = auth.get('password') - client.username_pw_set(username, password) - else: - raise KeyError("The 'username' key was not found, this is " - "required for auth") - - if will is not None: - client.will_set(**will) - - if tls is not None: - if isinstance(tls, dict): - insecure = tls.pop('insecure', False) - # mypy don't get that tls no longer contains the key insecure - client.tls_set(**tls) # type: ignore[misc] - if insecure: - # Must be set *after* the `client.tls_set()` call since it sets - # up the SSL context that `client.tls_insecure_set` alters. - client.tls_insecure_set(insecure) - else: - # Assume input is SSLContext object - client.tls_set_context(tls) - - client.connect(hostname, port, keepalive) - client.loop_forever() - - -def single( - topic: str, - payload: paho.PayloadType = None, - qos: int = 0, - retain: bool = False, - hostname: str = "localhost", - port: int = 1883, - client_id: str = "", - keepalive: int = 60, - will: MessageDict | None = None, - auth: AuthParameter | None = None, - tls: TLSParameter | None = None, - protocol: MQTTProtocolVersion = paho.MQTTv311, - transport: Literal["tcp", "websockets"] = "tcp", - proxy_args: Any | None = None, -) -> None: - """Publish a single message to a broker, then disconnect cleanly. - - This function creates an MQTT client, connects to a broker and publishes a - single message. Once the message has been delivered, it disconnects cleanly - from the broker. - - :param str topic: the only required argument must be the topic string to which the - payload will be published. - - :param payload: the payload to be published. If "" or None, a zero length payload - will be published. - - :param int qos: the qos to use when publishing, default to 0. - - :param bool retain: set the message to be retained (True) or not (False). - - :param str hostname: the address of the broker to connect to. - Defaults to localhost. - - :param int port: the port to connect to the broker on. Defaults to 1883. - - :param str client_id: the MQTT client id to use. If "" or None, the Paho library will - generate a client id automatically. - - :param int keepalive: the keepalive timeout value for the client. Defaults to 60 - seconds. - - :param will: a dict containing will parameters for the client: will = {'topic': - "", 'payload':", 'qos':, 'retain':}. - Topic is required, all other parameters are optional and will - default to None, 0 and False respectively. - Defaults to None, which indicates no will should be used. - - :param auth: a dict containing authentication parameters for the client: - Username is required, password is optional and will default to None - auth = {'username':"", 'password':""} - if not provided. - Defaults to None, which indicates no authentication is to be used. - - :param tls: a dict containing TLS configuration parameters for the client: - dict = {'ca_certs':"", 'certfile':"", - 'keyfile':"", 'tls_version':"", - 'ciphers':", 'insecure':""} - ca_certs is required, all other parameters are optional and will - default to None if not provided, which results in the client using - the default behaviour - see the paho.mqtt.client documentation. - Defaults to None, which indicates that TLS should not be used. - Alternatively, tls input can be an SSLContext object, which will be - processed using the tls_set_context method. - - :param transport: set to "tcp" to use the default setting of transport which is - raw TCP. Set to "websockets" to use WebSockets as the transport. - - :param proxy_args: a dictionary that will be given to the client. - """ - - msg: MessageDict = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain} - - multiple([msg], hostname, port, client_id, keepalive, will, auth, tls, - protocol, transport, proxy_args) diff --git a/sbapp/mqtt/py.typed b/sbapp/mqtt/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/sbapp/mqtt/reasoncodes.py b/sbapp/mqtt/reasoncodes.py deleted file mode 100644 index 243ac96..0000000 --- a/sbapp/mqtt/reasoncodes.py +++ /dev/null @@ -1,223 +0,0 @@ -# ******************************************************************* -# Copyright (c) 2017, 2019 IBM Corp. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v2.0 -# and Eclipse Distribution License v1.0 which accompany this distribution. -# -# The Eclipse Public License is available at -# http://www.eclipse.org/legal/epl-v20.html -# and the Eclipse Distribution License is available at -# http://www.eclipse.org/org/documents/edl-v10.php. -# -# Contributors: -# Ian Craggs - initial implementation and/or documentation -# ******************************************************************* - -import functools -import warnings -from typing import Any - -from .packettypes import PacketTypes - - -@functools.total_ordering -class ReasonCode: - """MQTT version 5.0 reason codes class. - - See ReasonCode.names for a list of possible numeric values along with their - names and the packets to which they apply. - - """ - - def __init__(self, packetType: int, aName: str ="Success", identifier: int =-1): - """ - packetType: the type of the packet, such as PacketTypes.CONNECT that - this reason code will be used with. Some reason codes have different - names for the same identifier when used a different packet type. - - aName: the String name of the reason code to be created. Ignored - if the identifier is set. - - identifier: an integer value of the reason code to be created. - - """ - - self.packetType = packetType - self.names = { - 0: {"Success": [PacketTypes.CONNACK, PacketTypes.PUBACK, - PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, - PacketTypes.UNSUBACK, PacketTypes.AUTH], - "Normal disconnection": [PacketTypes.DISCONNECT], - "Granted QoS 0": [PacketTypes.SUBACK]}, - 1: {"Granted QoS 1": [PacketTypes.SUBACK]}, - 2: {"Granted QoS 2": [PacketTypes.SUBACK]}, - 4: {"Disconnect with will message": [PacketTypes.DISCONNECT]}, - 16: {"No matching subscribers": - [PacketTypes.PUBACK, PacketTypes.PUBREC]}, - 17: {"No subscription found": [PacketTypes.UNSUBACK]}, - 24: {"Continue authentication": [PacketTypes.AUTH]}, - 25: {"Re-authenticate": [PacketTypes.AUTH]}, - 128: {"Unspecified error": [PacketTypes.CONNACK, PacketTypes.PUBACK, - PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, - PacketTypes.DISCONNECT], }, - 129: {"Malformed packet": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 130: {"Protocol error": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 131: {"Implementation specific error": [PacketTypes.CONNACK, - PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, - PacketTypes.UNSUBACK, PacketTypes.DISCONNECT], }, - 132: {"Unsupported protocol version": [PacketTypes.CONNACK]}, - 133: {"Client identifier not valid": [PacketTypes.CONNACK]}, - 134: {"Bad user name or password": [PacketTypes.CONNACK]}, - 135: {"Not authorized": [PacketTypes.CONNACK, PacketTypes.PUBACK, - PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, - PacketTypes.DISCONNECT], }, - 136: {"Server unavailable": [PacketTypes.CONNACK]}, - 137: {"Server busy": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 138: {"Banned": [PacketTypes.CONNACK]}, - 139: {"Server shutting down": [PacketTypes.DISCONNECT]}, - 140: {"Bad authentication method": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 141: {"Keep alive timeout": [PacketTypes.DISCONNECT]}, - 142: {"Session taken over": [PacketTypes.DISCONNECT]}, - 143: {"Topic filter invalid": - [PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT]}, - 144: {"Topic name invalid": - [PacketTypes.CONNACK, PacketTypes.PUBACK, - PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, - 145: {"Packet identifier in use": - [PacketTypes.PUBACK, PacketTypes.PUBREC, - PacketTypes.SUBACK, PacketTypes.UNSUBACK]}, - 146: {"Packet identifier not found": - [PacketTypes.PUBREL, PacketTypes.PUBCOMP]}, - 147: {"Receive maximum exceeded": [PacketTypes.DISCONNECT]}, - 148: {"Topic alias invalid": [PacketTypes.DISCONNECT]}, - 149: {"Packet too large": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 150: {"Message rate too high": [PacketTypes.DISCONNECT]}, - 151: {"Quota exceeded": [PacketTypes.CONNACK, PacketTypes.PUBACK, - PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.DISCONNECT], }, - 152: {"Administrative action": [PacketTypes.DISCONNECT]}, - 153: {"Payload format invalid": - [PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, - 154: {"Retain not supported": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 155: {"QoS not supported": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 156: {"Use another server": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 157: {"Server moved": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 158: {"Shared subscription not supported": - [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, - 159: {"Connection rate exceeded": - [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, - 160: {"Maximum connect time": - [PacketTypes.DISCONNECT]}, - 161: {"Subscription identifiers not supported": - [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, - 162: {"Wildcard subscription not supported": - [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, - } - if identifier == -1: - if packetType == PacketTypes.DISCONNECT and aName == "Success": - aName = "Normal disconnection" - self.set(aName) - else: - self.value = identifier - self.getName() # check it's good - - def __getName__(self, packetType, identifier): - """ - Get the reason code string name for a specific identifier. - The name can vary by packet type for the same identifier, which - is why the packet type is also required. - - Used when displaying the reason code. - """ - if identifier not in self.names: - raise KeyError(identifier) - names = self.names[identifier] - namelist = [name for name in names.keys() if packetType in names[name]] - if len(namelist) != 1: - raise ValueError(f"Expected exactly one name, found {namelist!r}") - return namelist[0] - - def getId(self, name): - """ - Get the numeric id corresponding to a reason code name. - - Used when setting the reason code for a packetType - check that only valid codes for the packet are set. - """ - for code in self.names.keys(): - if name in self.names[code].keys(): - if self.packetType in self.names[code][name]: - return code - raise KeyError(f"Reason code name not found: {name}") - - def set(self, name): - self.value = self.getId(name) - - def unpack(self, buffer): - c = buffer[0] - name = self.__getName__(self.packetType, c) - self.value = self.getId(name) - return 1 - - def getName(self): - """Returns the reason code name corresponding to the numeric value which is set. - """ - return self.__getName__(self.packetType, self.value) - - def __eq__(self, other): - if isinstance(other, int): - return self.value == other - if isinstance(other, str): - return other == str(self) - if isinstance(other, ReasonCode): - return self.value == other.value - return False - - def __lt__(self, other): - if isinstance(other, int): - return self.value < other - if isinstance(other, ReasonCode): - return self.value < other.value - return NotImplemented - - def __repr__(self): - try: - packet_name = PacketTypes.Names[self.packetType] - except IndexError: - packet_name = "Unknown" - - return f"ReasonCode({packet_name}, {self.getName()!r})" - - def __str__(self): - return self.getName() - - def json(self): - return self.getName() - - def pack(self): - return bytearray([self.value]) - - @property - def is_failure(self) -> bool: - return self.value >= 0x80 - - -class _CompatibilityIsInstance(type): - def __instancecheck__(self, other: Any) -> bool: - return isinstance(other, ReasonCode) - - -class ReasonCodes(ReasonCode, metaclass=_CompatibilityIsInstance): - def __init__(self, *args, **kwargs): - warnings.warn("ReasonCodes is deprecated, use ReasonCode (singular) instead", - category=DeprecationWarning, - stacklevel=2, - ) - super().__init__(*args, **kwargs) diff --git a/sbapp/mqtt/subscribe.py b/sbapp/mqtt/subscribe.py deleted file mode 100644 index b6c80f4..0000000 --- a/sbapp/mqtt/subscribe.py +++ /dev/null @@ -1,281 +0,0 @@ -# Copyright (c) 2016 Roger Light -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v2.0 -# and Eclipse Distribution License v1.0 which accompany this distribution. -# -# The Eclipse Public License is available at -# http://www.eclipse.org/legal/epl-v20.html -# and the Eclipse Distribution License is available at -# http://www.eclipse.org/org/documents/edl-v10.php. -# -# Contributors: -# Roger Light - initial API and implementation - -""" -This module provides some helper functions to allow straightforward subscribing -to topics and retrieving messages. The two functions are simple(), which -returns one or messages matching a set of topics, and callback() which allows -you to pass a callback for processing of messages. -""" - -from .. import mqtt -from . import client as paho - - -def _on_connect(client, userdata, flags, reason_code, properties): - """Internal callback""" - if reason_code != 0: - raise mqtt.MQTTException(paho.connack_string(reason_code)) - - if isinstance(userdata['topics'], list): - for topic in userdata['topics']: - client.subscribe(topic, userdata['qos']) - else: - client.subscribe(userdata['topics'], userdata['qos']) - - -def _on_message_callback(client, userdata, message): - """Internal callback""" - userdata['callback'](client, userdata['userdata'], message) - - -def _on_message_simple(client, userdata, message): - """Internal callback""" - - if userdata['msg_count'] == 0: - return - - # Don't process stale retained messages if 'retained' was false - if message.retain and not userdata['retained']: - return - - userdata['msg_count'] = userdata['msg_count'] - 1 - - if userdata['messages'] is None and userdata['msg_count'] == 0: - userdata['messages'] = message - client.disconnect() - return - - userdata['messages'].append(message) - if userdata['msg_count'] == 0: - client.disconnect() - - -def callback(callback, topics, qos=0, userdata=None, hostname="localhost", - port=1883, client_id="", keepalive=60, will=None, auth=None, - tls=None, protocol=paho.MQTTv311, transport="tcp", - clean_session=True, proxy_args=None): - """Subscribe to a list of topics and process them in a callback function. - - This function creates an MQTT client, connects to a broker and subscribes - to a list of topics. Incoming messages are processed by the user provided - callback. This is a blocking function and will never return. - - :param callback: function with the same signature as `on_message` for - processing the messages received. - - :param topics: either a string containing a single topic to subscribe to, or a - list of topics to subscribe to. - - :param int qos: the qos to use when subscribing. This is applied to all topics. - - :param userdata: passed to the callback - - :param str hostname: the address of the broker to connect to. - Defaults to localhost. - - :param int port: the port to connect to the broker on. Defaults to 1883. - - :param str client_id: the MQTT client id to use. If "" or None, the Paho library will - generate a client id automatically. - - :param int keepalive: the keepalive timeout value for the client. Defaults to 60 - seconds. - - :param will: a dict containing will parameters for the client: will = {'topic': - "", 'payload':", 'qos':, 'retain':}. - Topic is required, all other parameters are optional and will - default to None, 0 and False respectively. - - Defaults to None, which indicates no will should be used. - - :param auth: a dict containing authentication parameters for the client: - auth = {'username':"", 'password':""} - Username is required, password is optional and will default to None - if not provided. - Defaults to None, which indicates no authentication is to be used. - - :param tls: a dict containing TLS configuration parameters for the client: - dict = {'ca_certs':"", 'certfile':"", - 'keyfile':"", 'tls_version':"", - 'ciphers':", 'insecure':""} - ca_certs is required, all other parameters are optional and will - default to None if not provided, which results in the client using - the default behaviour - see the paho.mqtt.client documentation. - Alternatively, tls input can be an SSLContext object, which will be - processed using the tls_set_context method. - Defaults to None, which indicates that TLS should not be used. - - :param str transport: set to "tcp" to use the default setting of transport which is - raw TCP. Set to "websockets" to use WebSockets as the transport. - - :param clean_session: a boolean that determines the client type. If True, - the broker will remove all information about this client - when it disconnects. If False, the client is a persistent - client and subscription information and queued messages - will be retained when the client disconnects. - Defaults to True. - - :param proxy_args: a dictionary that will be given to the client. - """ - - if qos < 0 or qos > 2: - raise ValueError('qos must be in the range 0-2') - - callback_userdata = { - 'callback':callback, - 'topics':topics, - 'qos':qos, - 'userdata':userdata} - - client = paho.Client( - paho.CallbackAPIVersion.VERSION2, - client_id=client_id, - userdata=callback_userdata, - protocol=protocol, - transport=transport, - clean_session=clean_session, - ) - client.enable_logger() - - client.on_message = _on_message_callback - client.on_connect = _on_connect - - if proxy_args is not None: - client.proxy_set(**proxy_args) - - if auth: - username = auth.get('username') - if username: - password = auth.get('password') - client.username_pw_set(username, password) - else: - raise KeyError("The 'username' key was not found, this is " - "required for auth") - - if will is not None: - client.will_set(**will) - - if tls is not None: - if isinstance(tls, dict): - insecure = tls.pop('insecure', False) - client.tls_set(**tls) - if insecure: - # Must be set *after* the `client.tls_set()` call since it sets - # up the SSL context that `client.tls_insecure_set` alters. - client.tls_insecure_set(insecure) - else: - # Assume input is SSLContext object - client.tls_set_context(tls) - - client.connect(hostname, port, keepalive) - client.loop_forever() - - -def simple(topics, qos=0, msg_count=1, retained=True, hostname="localhost", - port=1883, client_id="", keepalive=60, will=None, auth=None, - tls=None, protocol=paho.MQTTv311, transport="tcp", - clean_session=True, proxy_args=None): - """Subscribe to a list of topics and return msg_count messages. - - This function creates an MQTT client, connects to a broker and subscribes - to a list of topics. Once "msg_count" messages have been received, it - disconnects cleanly from the broker and returns the messages. - - :param topics: either a string containing a single topic to subscribe to, or a - list of topics to subscribe to. - - :param int qos: the qos to use when subscribing. This is applied to all topics. - - :param int msg_count: the number of messages to retrieve from the broker. - if msg_count == 1 then a single MQTTMessage will be returned. - if msg_count > 1 then a list of MQTTMessages will be returned. - - :param bool retained: If set to True, retained messages will be processed the same as - non-retained messages. If set to False, retained messages will - be ignored. This means that with retained=False and msg_count=1, - the function will return the first message received that does - not have the retained flag set. - - :param str hostname: the address of the broker to connect to. - Defaults to localhost. - - :param int port: the port to connect to the broker on. Defaults to 1883. - - :param str client_id: the MQTT client id to use. If "" or None, the Paho library will - generate a client id automatically. - - :param int keepalive: the keepalive timeout value for the client. Defaults to 60 - seconds. - - :param will: a dict containing will parameters for the client: will = {'topic': - "", 'payload':", 'qos':, 'retain':}. - Topic is required, all other parameters are optional and will - default to None, 0 and False respectively. - Defaults to None, which indicates no will should be used. - - :param auth: a dict containing authentication parameters for the client: - auth = {'username':"", 'password':""} - Username is required, password is optional and will default to None - if not provided. - Defaults to None, which indicates no authentication is to be used. - - :param tls: a dict containing TLS configuration parameters for the client: - dict = {'ca_certs':"", 'certfile':"", - 'keyfile':"", 'tls_version':"", - 'ciphers':", 'insecure':""} - ca_certs is required, all other parameters are optional and will - default to None if not provided, which results in the client using - the default behaviour - see the paho.mqtt.client documentation. - Alternatively, tls input can be an SSLContext object, which will be - processed using the tls_set_context method. - Defaults to None, which indicates that TLS should not be used. - - :param protocol: the MQTT protocol version to use. Defaults to MQTTv311. - - :param transport: set to "tcp" to use the default setting of transport which is - raw TCP. Set to "websockets" to use WebSockets as the transport. - - :param clean_session: a boolean that determines the client type. If True, - the broker will remove all information about this client - when it disconnects. If False, the client is a persistent - client and subscription information and queued messages - will be retained when the client disconnects. - Defaults to True. If protocol is MQTTv50, clean_session - is ignored. - - :param proxy_args: a dictionary that will be given to the client. - """ - - if msg_count < 1: - raise ValueError('msg_count must be > 0') - - # Set ourselves up to return a single message if msg_count == 1, or a list - # if > 1. - if msg_count == 1: - messages = None - else: - messages = [] - - # Ignore clean_session if protocol is MQTTv50, otherwise Client will raise - if protocol == paho.MQTTv5: - clean_session = None - - userdata = {'retained':retained, 'msg_count':msg_count, 'messages':messages} - - callback(_on_message_simple, topics, qos, userdata, hostname, port, - client_id, keepalive, will, auth, tls, protocol, transport, - clean_session, proxy_args) - - return userdata['messages'] diff --git a/sbapp/mqtt/subscribeoptions.py b/sbapp/mqtt/subscribeoptions.py deleted file mode 100644 index 7e0605d..0000000 --- a/sbapp/mqtt/subscribeoptions.py +++ /dev/null @@ -1,113 +0,0 @@ -""" -******************************************************************* - Copyright (c) 2017, 2019 IBM Corp. - - All rights reserved. This program and the accompanying materials - are made available under the terms of the Eclipse Public License v2.0 - and Eclipse Distribution License v1.0 which accompany this distribution. - - The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v20.html - and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - - Contributors: - Ian Craggs - initial implementation and/or documentation -******************************************************************* -""" - - - -class MQTTException(Exception): - pass - - -class SubscribeOptions: - """The MQTT v5.0 subscribe options class. - - The options are: - qos: As in MQTT v3.1.1. - noLocal: True or False. If set to True, the subscriber will not receive its own publications. - retainAsPublished: True or False. If set to True, the retain flag on received publications will be as set - by the publisher. - retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND - Controls when the broker should send retained messages: - - RETAIN_SEND_ON_SUBSCRIBE: on any successful subscribe request - - RETAIN_SEND_IF_NEW_SUB: only if the subscribe request is new - - RETAIN_DO_NOT_SEND: never send retained messages - """ - - # retain handling options - RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB, RETAIN_DO_NOT_SEND = range( - 0, 3) - - def __init__( - self, - qos: int = 0, - noLocal: bool = False, - retainAsPublished: bool = False, - retainHandling: int = RETAIN_SEND_ON_SUBSCRIBE, - ): - """ - qos: 0, 1 or 2. 0 is the default. - noLocal: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. - retainAsPublished: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. - retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND - RETAIN_SEND_ON_SUBSCRIBE is the default and corresponds to MQTT v3.1.1 behavior. - """ - object.__setattr__(self, "names", - ["QoS", "noLocal", "retainAsPublished", "retainHandling"]) - self.QoS = qos # bits 0,1 - self.noLocal = noLocal # bit 2 - self.retainAsPublished = retainAsPublished # bit 3 - self.retainHandling = retainHandling # bits 4 and 5: 0, 1 or 2 - if self.retainHandling not in (0, 1, 2): - raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") - if self.QoS not in (0, 1, 2): - raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") - - def __setattr__(self, name, value): - if name not in self.names: - raise MQTTException( - f"{name} Attribute name must be one of {self.names}") - object.__setattr__(self, name, value) - - def pack(self): - if self.retainHandling not in (0, 1, 2): - raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") - if self.QoS not in (0, 1, 2): - raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") - noLocal = 1 if self.noLocal else 0 - retainAsPublished = 1 if self.retainAsPublished else 0 - data = [(self.retainHandling << 4) | (retainAsPublished << 3) | - (noLocal << 2) | self.QoS] - return bytes(data) - - def unpack(self, buffer): - b0 = buffer[0] - self.retainHandling = ((b0 >> 4) & 0x03) - self.retainAsPublished = True if ((b0 >> 3) & 0x01) == 1 else False - self.noLocal = True if ((b0 >> 2) & 0x01) == 1 else False - self.QoS = (b0 & 0x03) - if self.retainHandling not in (0, 1, 2): - raise AssertionError(f"Retain handling should be 0, 1 or 2, not {self.retainHandling}") - if self.QoS not in (0, 1, 2): - raise AssertionError(f"QoS should be 0, 1 or 2, not {self.QoS}") - return 1 - - def __repr__(self): - return str(self) - - def __str__(self): - return "{QoS="+str(self.QoS)+", noLocal="+str(self.noLocal) +\ - ", retainAsPublished="+str(self.retainAsPublished) +\ - ", retainHandling="+str(self.retainHandling)+"}" - - def json(self): - data = { - "QoS": self.QoS, - "noLocal": self.noLocal, - "retainAsPublished": self.retainAsPublished, - "retainHandling": self.retainHandling, - } - return data diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index ce5547d..fa43164 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -3228,9 +3228,10 @@ class SidebandCore(): if self.config["telemetry_enabled"] == True: self.update_telemeter_config() if self.telemeter != None: - def mqtt_job(): - self.mqtt_handle_telemetry(self.lxmf_destination.hash, self.telemeter.packed()) - threading.Thread(target=mqtt_job, daemon=True).start() + if self.config["telemetry_to_mqtt"]: + def mqtt_job(): + self.mqtt_handle_telemetry(self.lxmf_destination.hash, self.telemeter.packed()) + threading.Thread(target=mqtt_job, daemon=True).start() return self.telemeter.read_all() else: return {} diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index 0d69816..0d4837e 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -2,9 +2,13 @@ import RNS import time import threading from collections import deque -from sbapp.mqtt import client as mqtt from .sense import Telemeter, Commands +if RNS.vendor.platformutils.get_platform() == "android": + import pmqtt.client as mqtt +else: + from sbapp.pmqtt import client as mqtt + class MQTT(): QUEUE_MAXLEN = 65536 SCHEDULER_SLEEP = 1 diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 7716417..1aa5a9b 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2542,7 +2542,6 @@ class RNSTransport(Sensor): rss = ifstats.pop("rss") if self.last_update == 0: - RNS.log("NO CALC DIFF") rxs = ifstats["rxs"] txs = ifstats["txs"] else: @@ -2551,9 +2550,6 @@ class RNSTransport(Sensor): txd = ifstats["txb"] - self._last_traffic_txb rxs = (rxd/td)*8 txs = (txd/td)*8 - RNS.log(f"CALC DIFFS: td={td}, rxd={rxd}, txd={txd}") - RNS.log(f" rxs={rxs}, txs={txs}") - self._last_traffic_rxb = ifstats["rxb"] self._last_traffic_txb = ifstats["txb"] From cbb388fb636d9999610f1b00ddce1444054c270c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 21:51:32 +0100 Subject: [PATCH 58/76] Fixed stat --- sbapp/sideband/sense.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 1aa5a9b..4243a68 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2554,10 +2554,16 @@ class RNSTransport(Sensor): self._last_traffic_rxb = ifstats["rxb"] self._last_traffic_txb = ifstats["txb"] + transport_enabled = False + transport_uptime = 0 + if "transport_uptime" in ifstats: + transport_enabled = True + transport_uptime = ifstats["transport_uptime"] + self.data = { - "transport_enabled": RNS.Reticulum.transport_enabled(), + "transport_enabled": transport_enabled, "transport_identity": RNS.Transport.identity.hash, - "transport_uptime": time.time()-RNS.Transport.start_time if RNS.Reticulum.transport_enabled() else None, + "transport_uptime": transport_uptime, "traffic_rxb": ifstats["rxb"], "traffic_txb": ifstats["txb"], "speed_rx": rxs, @@ -2856,7 +2862,7 @@ class LXMFPropagation(Sensor): "messagestore_bytes": d["messagestore"]["bytes"], "messagestore_free": d["messagestore"]["limit"]-d["messagestore"]["bytes"], "messagestore_limit": d["messagestore"]["limit"], - "messagestore_pct": round(max( (d["messagestore"]["bytes"]/d["messagestore"]["limit"])*100, 100.0), 2), + "messagestore_pct": round(min( (d["messagestore"]["bytes"]/d["messagestore"]["limit"])*100, 100.0), 2), "client_propagation_messages_received": d["clients"]["client_propagation_messages_received"], "client_propagation_messages_served": d["clients"]["client_propagation_messages_served"], "unpeered_propagation_incoming": d["unpeered_propagation_incoming"], From e743493ffd098ff5576fe7815a122db9c8654cf4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 26 Jan 2025 21:56:27 +0100 Subject: [PATCH 59/76] Updated versions --- sbapp/buildozer.spec | 2 +- sbapp/main.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 24721b1..df728e8 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,7 +10,7 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20250120 +android.numeric_version = 20250126 requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,ffpyplayer,codec2,pycodec2,sh,pynacl,typing-extensions,mistune>=3.0.2,beautifulsoup4 diff --git a/sbapp/main.py b/sbapp/main.py index 9e1042f..8efdd4d 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.3.0" +__version__ = "1.3.1" __variant__ = "" import sys From 329bf6f3e61fbaab585388bbae313ed97988c75e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Jan 2025 10:04:38 +0100 Subject: [PATCH 60/76] Cleanup --- sbapp/sideband/mqtt.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index 0d4837e..bed0e6d 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -22,8 +22,6 @@ class MQTT(): self.queue_lock = threading.Lock() self.waiting_msgs = deque(maxlen=MQTT.QUEUE_MAXLEN) self.waiting_telemetry = set() - self.unacked_msgs = set() - self.client.user_data_set(self.unacked_msgs) self.client.on_connect_fail = self.connect_failed self.client.on_disconnect = self.disconnected self.start() @@ -86,7 +84,6 @@ class MQTT(): def post_message(self, topic, data): mqtt_msg = self.client.publish(topic, data, qos=1) - self.unacked_msgs.add(mqtt_msg.mid) self.waiting_telemetry.add(mqtt_msg) def process_queue(self): @@ -108,6 +105,8 @@ class MQTT(): try: for msg in self.waiting_telemetry: msg.wait_for_publish() + self.waiting_telemetry.clear() + except Exception as e: RNS.log(f"An error occurred while publishing MQTT messages: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) @@ -127,5 +126,4 @@ class MQTT(): for topic in topics: topic_path = f"{root_path}/{topic}" data = topics[topic] - self.waiting_msgs.append((topic_path, data)) - # RNS.log(f"{topic_path}: {data}") # TODO: Remove debug + self.waiting_msgs.append((topic_path, data)) \ No newline at end of file From e65b2306cc1d98eef9bc80ec8aa42ea3b919c4b5 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Jan 2025 10:15:25 +0100 Subject: [PATCH 61/76] Include signal icon in all cases. Fixes #70. --- sbapp/ui/helpers.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sbapp/ui/helpers.py b/sbapp/ui/helpers.py index c3b454c..5b43278 100644 --- a/sbapp/ui/helpers.py +++ b/sbapp/ui/helpers.py @@ -123,10 +123,12 @@ def sig_icon_for_q(q): return "σ°£Έ" elif q > 50: return "σ°£Ά" - elif q > 30: + elif q > 20: return "󰣴" - elif q > 10: + elif q > 5: return "σ°£Ύ" + else: + return "σ°£½" persistent_fonts = ["nf", "term"] nf_mapped = "nf" From de125004e6241f7707ecea41f8a2d0b3f307365d Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Jan 2025 10:24:55 +0100 Subject: [PATCH 62/76] Updated issue template --- .github/ISSUE_TEMPLATE/πŸ›-bug-report.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md b/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md index ddb78fc..82a4968 100644 --- a/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md +++ b/.github/ISSUE_TEMPLATE/πŸ›-bug-report.md @@ -12,7 +12,7 @@ Before creating a bug report on this issue tracker, you **must** read the [Contr - The issue tracker is used by developers of this project. **Do not use it to ask general questions, or for support requests**. - Ideas and feature requests can be made on the [Discussions](https://github.com/markqvist/Reticulum/discussions). **Only** feature requests accepted by maintainers and developers are tracked and included on the issue tracker. **Do not post feature requests here**. -- After reading the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md), delete this section from your bug report. +- After reading the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md), **delete this section only** (*"Read the Contribution Guidelines"*) from your bug report, **and fill in all the other sections**. **Describe the Bug** First of all: Is this really a bug? Is it reproducible? From 5153a1178b78ec2ee21bd5b331a17280feb6207b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Jan 2025 11:41:00 +0100 Subject: [PATCH 63/76] Updated sensor stale times --- sbapp/sideband/sense.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 4243a68..05dc81f 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2513,7 +2513,7 @@ class Fuel(Sensor): class RNSTransport(Sensor): SID = Sensor.SID_RNS_TRANSPORT - STALE_TIME = 1 + STALE_TIME = 60 def __init__(self): self._last_traffic_rxb = 0 @@ -2743,7 +2743,7 @@ class RNSTransport(Sensor): class LXMFPropagation(Sensor): SID = Sensor.SID_LXMF_PROPAGATION - STALE_TIME = 15 + STALE_TIME = 300 def __init__(self): self.identity = None From fc5ffab9cec63cb0f0b9eb51b63614266f1b1ba3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Jan 2025 11:41:12 +0100 Subject: [PATCH 64/76] Updated loglevels --- sbapp/sideband/core.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index fa43164..65ab389 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -75,7 +75,7 @@ class PropagationNodeDetector(): "snr": stat_endpoint.reticulum.get_packet_snr(announce_packet_hash), "q": stat_endpoint.reticulum.get_packet_q(announce_packet_hash)} - RNS.log("Detected active propagation node "+RNS.prettyhexrep(destination_hash)+" emission "+str(age)+" seconds ago, "+str(hops)+" hops away") + RNS.log("Detected active propagation node "+RNS.prettyhexrep(destination_hash)+" emission "+str(age)+" seconds ago, "+str(hops)+" hops away", RNS.LOG_EXTREME) self.owner.log_announce(destination_hash, app_data, dest_type=PropagationNodeDetector.aspect_filter, link_stats=link_stats) if self.owner.config["lxmf_propagation_node"] == None: @@ -91,10 +91,10 @@ class PropagationNodeDetector(): pass else: - RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)} with data: {app_data}", RNS.LOG_DEBUG) + RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)} with data: {app_data}", RNS.LOG_EXTREME) else: - RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)} with data: {app_data}", RNS.LOG_DEBUG) + RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)} with data: {app_data}", RNS.LOG_EXTREME) except Exception as e: RNS.log("Error while processing received propagation node announce: "+str(e)) @@ -1003,7 +1003,7 @@ class SidebandCore(): app_data = b"" if type(app_data) != bytes: app_data = msgpack.packb([app_data, stamp_cost]) - RNS.log("Received "+str(dest_type)+" announce for "+RNS.prettyhexrep(dest)+" with data: "+str(app_data), RNS.LOG_DEBUG) + RNS.log("Received "+str(dest_type)+" announce for "+RNS.prettyhexrep(dest), RNS.LOG_DEBUG) self._db_save_announce(dest, app_data, dest_type, link_stats) self.setstate("app.flags.new_announces", True) From 2c25b75042411eb4d3af148e34d1b4eacc09ce19 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Jan 2025 14:40:49 +0100 Subject: [PATCH 65/76] Added aggregate propagation stats --- sbapp/sideband/sense.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 05dc81f..cdcaab7 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -2947,9 +2947,23 @@ class LXMFPropagation(Sensor): f"{topic}/max_peers": v["max_peers"], } + peered_rx_bytes = 0 + peered_tx_bytes = 0 + peered_offered = 0 + peered_outgoing = 0 + peered_incoming = 0 + peered_unhandled = 0 + peered_max_unhandled = 0 for peer_id in v["peers"]: p = v["peers"][peer_id] pid = mqtt_desthash(peer_id) + peer_rx_bytes = p["rx_bytes"]; peered_rx_bytes += peer_rx_bytes + peer_tx_bytes = p["tx_bytes"]; peered_tx_bytes += peer_tx_bytes + peer_messages_offered = p["messages_offered"]; peered_offered += peer_messages_offered + peer_messages_outgoing = p["messages_outgoing"]; peered_outgoing += peer_messages_outgoing + peer_messages_incoming = p["messages_incoming"]; peered_incoming += peer_messages_incoming + peer_messages_unhandled = p["messages_unhandled"]; peered_unhandled += peer_messages_unhandled + peered_max_unhandled = max(peered_max_unhandled, peer_messages_unhandled) rendered[f"{topic}/peers/{pid}/type"] = p["type"] rendered[f"{topic}/peers/{pid}/state"] = p["state"] rendered[f"{topic}/peers/{pid}/alive"] = p["alive"] @@ -2962,12 +2976,20 @@ class LXMFPropagation(Sensor): rendered[f"{topic}/peers/{pid}/str"] = p["str"] rendered[f"{topic}/peers/{pid}/transfer_limit"] = p["transfer_limit"] rendered[f"{topic}/peers/{pid}/network_distance"] = p["network_distance"] - rendered[f"{topic}/peers/{pid}/rx_bytes"] = p["rx_bytes"] - rendered[f"{topic}/peers/{pid}/tx_bytes"] = p["tx_bytes"] - rendered[f"{topic}/peers/{pid}/messages_offered"] = p["messages_offered"] - rendered[f"{topic}/peers/{pid}/messages_outgoing"] = p["messages_outgoing"] - rendered[f"{topic}/peers/{pid}/messages_incoming"] = p["messages_incoming"] - rendered[f"{topic}/peers/{pid}/messages_unhandled"] = p["messages_unhandled"] + rendered[f"{topic}/peers/{pid}/rx_bytes"] = peer_rx_bytes + rendered[f"{topic}/peers/{pid}/tx_bytes"] = peer_tx_bytes + rendered[f"{topic}/peers/{pid}/messages_offered"] = peer_messages_offered + rendered[f"{topic}/peers/{pid}/messages_outgoing"] = peer_messages_outgoing + rendered[f"{topic}/peers/{pid}/messages_incoming"] = peer_messages_incoming + rendered[f"{topic}/peers/{pid}/messages_unhandled"] = peer_messages_unhandled + + rendered[f"{topic}/peered_propagation_rx_bytes"] = peered_rx_bytes + rendered[f"{topic}/peered_propagation_tx_bytes"] = peered_tx_bytes + rendered[f"{topic}/peered_propagation_offered"] = peered_offered + rendered[f"{topic}/peered_propagation_outgoing"] = peered_outgoing + rendered[f"{topic}/peered_propagation_incoming"] = peered_incoming + rendered[f"{topic}/peered_propagation_unhandled"] = peered_unhandled + rendered[f"{topic}/peered_propagation_max_unhandled"] = peered_max_unhandled else: rendered = None From 3b2e1adaf2965b2f21ff5a78f7cd6828d14765eb Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 28 Jan 2025 15:18:00 +0100 Subject: [PATCH 66/76] Added connection map sensor --- sbapp/sideband/sense.py | 131 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 129 insertions(+), 2 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index cdcaab7..34c2e14 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -55,7 +55,8 @@ class Telemeter(): Sensor.SID_POWER_PRODUCTION: PowerProduction, Sensor.SID_PROCESSOR: Processor, Sensor.SID_RAM: RandomAccessMemory, Sensor.SID_NVM: NonVolatileMemory, Sensor.SID_CUSTOM: Custom, Sensor.SID_TANK: Tank, Sensor.SID_FUEL: Fuel, - Sensor.SID_RNS_TRANSPORT: RNSTransport, Sensor.SID_LXMF_PROPAGATION: LXMFPropagation} + Sensor.SID_RNS_TRANSPORT: RNSTransport, Sensor.SID_LXMF_PROPAGATION: LXMFPropagation, + Sensor.SID_CONNECTION_MAP: ConnectionMap} self.available = { "time": Sensor.SID_TIME, @@ -69,7 +70,8 @@ class Telemeter(): "power_consumption": Sensor.SID_POWER_CONSUMPTION, "power_production": Sensor.SID_POWER_PRODUCTION, "processor": Sensor.SID_PROCESSOR, "ram": Sensor.SID_RAM, "nvm": Sensor.SID_NVM, "custom": Sensor.SID_CUSTOM, "tank": Sensor.SID_TANK, "fuel": Sensor.SID_FUEL, - "rns_transport": Sensor.SID_RNS_TRANSPORT, "lxmf_propagation": Sensor.SID_LXMF_PROPAGATION} + "rns_transport": Sensor.SID_RNS_TRANSPORT, "lxmf_propagation": Sensor.SID_LXMF_PROPAGATION, + "connection_map": Sensor.SID_CONNECTION_MAP} self.names = {} for name in self.available: @@ -210,6 +212,7 @@ class Sensor(): SID_FUEL = 0x17 SID_RNS_TRANSPORT = 0x19 SID_LXMF_PROPAGATION = 0x18 + SID_CONNECTION_MAP = 0x1A SID_CUSTOM = 0xff def __init__(self, sid = None, stale_time = None): @@ -3002,6 +3005,130 @@ class LXMFPropagation(Sensor): return None +class ConnectionMap(Sensor): + SID = Sensor.SID_CONNECTION_MAP + STALE_TIME = 60 + DEFAULT_MAP_NAME = 0x00 + + def __init__(self): + self.maps = {} + super().__init__(type(self).SID, type(self).STALE_TIME) + + def setup_sensor(self): + self.update_data() + + def teardown_sensor(self): + self.data = None + + def ensure_map(self, map_name): + if map_name == None: + map_name = self.DEFAULT_MAP_NAME + + if not map_name in self.maps: + self.maps[map_name] = { + "name": map_name, + "points": {}, + } + + return self.maps[map_name] + + def add_point(self, lat, lon, altitude=None, type_label=None, name=None, map_name=None, + signal_rssi=None, signal_snr=None, signal_q=None, hash_on_name_and_type_only=False): + + p = { + "latitude": lat, + "longitude": lon, + "altitude": altitude, + "type_label": type_label, + "name": name} + + if not hash_on_name_and_type_only: + p_hash = RNS.Identity.truncated_hash(umsgpack.packb(p)) + else: + p_hash = RNS.Identity.truncated_hash(umsgpack.packb({"type_label": type_label, "name": name})) + + p["signal"] = {"rssi": signal_rssi, "snr": signal_snr, "q": signal_q} + self.ensure_map(map_name)["points"][p_hash] = p + + def update_data(self): + self.data = { + "maps": self.maps, + } + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = self.data + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + return packed + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + try: + rendered = { + "icon": "map-check-outline", + "name": "Connection Map", + "values": {"maps": self.data["maps"]}, + } + + return rendered + + except Exception as e: + RNS.log(f"Could not render connection map telemetry data. The contained exception was: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + return None + + def render_mqtt(self, relative_to=None): + try: + if self.data != None: + r = self.render(relative_to=relative_to) + v = r["values"] + topic = f"{self.name()}" + rendered = { + f"{topic}/name": r["name"], + f"{topic}/icon": r["icon"], + } + + for map_name in v["maps"]: + m = v["maps"][map_name] + if map_name == self.DEFAULT_MAP_NAME: + map_name = "default" + for ph in m["points"]: + pid = mqtt_hash(ph) + p = m["points"][ph] + tl = p["type_label"] + n = p["name"] + rendered[f"{topic}/maps/{map_name}/points/{tl}/{n}/{pid}/lat"] = p["latitude"] + rendered[f"{topic}/maps/{map_name}/points/{tl}/{n}/{pid}/lon"] = p["longitude"] + rendered[f"{topic}/maps/{map_name}/points/{tl}/{n}/{pid}/alt"] = p["altitude"] + rendered[f"{topic}/maps/{map_name}/points/{tl}/{n}/{pid}/rssi"] = p["signal"]["rssi"] + rendered[f"{topic}/maps/{map_name}/points/{tl}/{n}/{pid}/snr"] = p["signal"]["snr"] + rendered[f"{topic}/maps/{map_name}/points/{tl}/{n}/{pid}/q"] = p["signal"]["q"] + + else: + rendered = None + + return rendered + + except Exception as e: + RNS.log(f"Could not render conection map telemetry data to MQTT format. The contained exception was: {e}", RNS.LOG_ERROR) + + return None + def mqtt_desthash(desthash): if type(desthash) == bytes: return RNS.hexrep(desthash, delimit=False) From b4a063a4e78f15357112d59ec226832c9d0ca5b0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 17 Feb 2025 20:42:00 +0100 Subject: [PATCH 67/76] Added periodic telemetry data cleaning --- docs/utilities/rns_audio_call_calc.py | 129 -------------------------- sbapp/main.py | 2 +- sbapp/sideband/core.py | 28 +++++- 3 files changed, 28 insertions(+), 131 deletions(-) delete mode 100644 docs/utilities/rns_audio_call_calc.py diff --git a/docs/utilities/rns_audio_call_calc.py b/docs/utilities/rns_audio_call_calc.py deleted file mode 100644 index 6bb2ccb..0000000 --- a/docs/utilities/rns_audio_call_calc.py +++ /dev/null @@ -1,129 +0,0 @@ -import os -import math -import RNS -import RNS.vendor.umsgpack as mp - -def simulate(link_speed=9600, audio_slot_ms=70, codec_rate=1200, method="msgpack"): - # Simulated on-air link speed - LINK_SPEED = link_speed - - # Packing method, can be "msgpack" or "protobuf" - PACKING_METHOD = method - - # The target audio slot time - TARGET_MS = audio_slot_ms - - # Packets needed per second for half-duplex audio - PACKETS_PER_SECOND = 1000/TARGET_MS - - # Effective audio encoder bitrate - CODEC_RATE = codec_rate - - # Maximum number of supported audio modes - MAX_ENUM = 127 - - # Per-packet overhead on a established link is 19 - # bytes, 3 for header and context, 16 for link ID - RNS_OVERHEAD = 19 - - # Physical-layer overhead. For RNode, this is 1 - # byte per RNS packet. - PHY_OVERHEAD = 1 - - # Total transport overhead - TRANSPORT_OVERHEAD = PHY_OVERHEAD+RNS_OVERHEAD - - # Calculate parameters - AUDIO_LEN = int(math.ceil(CODEC_RATE/(1000/TARGET_MS)/8)) - PER_BYTE_LATENCY_MS = 1000/(LINK_SPEED/8) - - # Pack the message with msgpack to get real- - # world packed message size - - if PACKING_METHOD == "msgpack": - # Calculate msgpack overhead - PL_LEN = len(mp.packb([MAX_ENUM, os.urandom(AUDIO_LEN)])) - PACKING_OVERHEAD = PL_LEN-AUDIO_LEN - elif PACKING_METHOD == "protobuf": - # For protobuf, assume the 8 bytes of stated overhead - PACKING_OVERHEAD = 8 - PL_LEN = AUDIO_LEN+PACKING_OVERHEAD - else: - print("Unsupported packing method") - exit(1) - - # Calculate required encrypted token blocks - BLOCKSIZE = 16 - REQUIRED_BLOCKS = math.ceil((PL_LEN+1)/BLOCKSIZE) - ENCRYPTED_PAYLOAD_LEN = REQUIRED_BLOCKS*BLOCKSIZE - BLOCK_HEADROOM = (REQUIRED_BLOCKS*BLOCKSIZE) - PL_LEN - 1 - - # The complete on-air packet length - PACKET_LEN = PHY_OVERHEAD+RNS_OVERHEAD+ENCRYPTED_PAYLOAD_LEN - PACKET_LATENCY = round(PACKET_LEN*PER_BYTE_LATENCY_MS, 1) - - # TODO: This should include any additional - # airtime consumption such as preamble and TX-tail. - PACKET_AIRTIME = PACKET_LEN*PER_BYTE_LATENCY_MS - AIRTIME_PCT = (PACKET_AIRTIME/TARGET_MS) * 100 - - # Maximum amount of concurrent full-duplex - # calls that can coexist on the same channel - CONCURRENT_CALLS = math.floor(100/AIRTIME_PCT) - - # Calculate latencies - TRANSPORT_LATENCY = round((PHY_OVERHEAD+RNS_OVERHEAD)*PER_BYTE_LATENCY_MS, 1) - - PAYLOAD_LATENCY = round(ENCRYPTED_PAYLOAD_LEN*PER_BYTE_LATENCY_MS, 1) - RAW_DATA_LATENCY = round(AUDIO_LEN*PER_BYTE_LATENCY_MS, 1) - PACKING_LATENCY = round(PACKING_OVERHEAD*PER_BYTE_LATENCY_MS, 1) - - DATA_LATENCY = round(ENCRYPTED_PAYLOAD_LEN*PER_BYTE_LATENCY_MS, 1) - ENCRYPTION_LATENCY = round((ENCRYPTED_PAYLOAD_LEN-PL_LEN)*PER_BYTE_LATENCY_MS, 1) - if ENCRYPTED_PAYLOAD_LEN-PL_LEN == 1: - E_OPT_STR = "(optimal)" - else: - E_OPT_STR = "(sub-optimal)" - - TOTAL_LATENCY = round(TARGET_MS+PACKET_LATENCY, 1) - - print( "\n===== Simulation Parameters ===\n") - print(f" Packing method : {method}") - print(f" Sampling delay : {TARGET_MS}ms") - print(f" Codec bitrate : {CODEC_RATE} bps") - print(f" Audio data : {AUDIO_LEN} bytes") - print(f" Packing overhead : {PACKING_OVERHEAD} bytes") - print(f" Payload length : {PL_LEN} bytes") - print(f" AES blocks needed : {REQUIRED_BLOCKS}") - print(f" Encrypted payload : {ENCRYPTED_PAYLOAD_LEN} bytes") - print(f" Transport overhead : {TRANSPORT_OVERHEAD} bytes ({RNS_OVERHEAD} from RNS, {PHY_OVERHEAD} from PHY)") - print(f" On-air length : {PACKET_LEN} bytes") - print(f" Packet airtime : {round(PACKET_AIRTIME,2)}ms") - - print( "\n===== Results for "+RNS.prettyspeed(LINK_SPEED)+" Link Speed ===\n") - print(f" Final latency : {TOTAL_LATENCY}ms") - print(f" Recording latency : contributes {TARGET_MS}ms") - print(f" Packet transport : contributes {PACKET_LATENCY}ms") - print(f" Payload : contributes {PAYLOAD_LATENCY}ms") - print(f" Audio data : contributes {RAW_DATA_LATENCY}ms") - print(f" Packing format : contributes {PACKING_LATENCY}ms") - print(f" Encryption : contributes {ENCRYPTION_LATENCY}ms {E_OPT_STR}") - print(f" RNS+PHY overhead : contributes {TRANSPORT_LATENCY}ms") - print(f"") - print(f" Half-duplex airtime : {round(AIRTIME_PCT, 2)}% of link capacity") - print(f" Concurrent calls : {int(CONCURRENT_CALLS)}\n") - print(f" Full-duplex airtime : {round(AIRTIME_PCT*2, 2)}% of link capacity") - print(f" Concurrent calls : {int(CONCURRENT_CALLS/2)}") - - if BLOCK_HEADROOM != 0: - print("") - print(f" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") - print(f" Unaligned AES block! Each packet could fit") - print(f" {BLOCK_HEADROOM} bytes of additional audio data") - print(f" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") - -print( "\n= With mspack =================") -simulate(method="msgpack") - -#print("\n\n= With protobuf ===============") -#simulate(method="protobuf") diff --git a/sbapp/main.py b/sbapp/main.py index 8efdd4d..7bc46d4 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2809,7 +2809,7 @@ class SidebandApp(MDApp): str_comps = " - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)" - str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]MD2bbcode[/b] (GPL3 License)" + str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]FFmpeg[/b] (GPL3 License)\n - [b]MD2bbcode[/b] (GPL3 License)" str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Paho MQTT[/b] (EPL2 License)\n - [b]Python[/b] (PSF License)" str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright Β© 2025 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY" info = "This is "+self.root.ids.app_version_info.text+", on RNS v"+RNS.__version__+" and LXMF v"+LXMF.__version__+".\n\nHumbly build using the following open components:\n\n"+str_comps diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 65ab389..36b8162 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -113,8 +113,10 @@ class SidebandCore(): SERVICE_JOB_INTERVAL = 1 PERIODIC_JOBS_INTERVAL = 60 PERIODIC_SYNC_RETRY = 360 + TELEMETRY_KEEP = 60*60*24*7 TELEMETRY_INTERVAL = 60 SERVICE_TELEMETRY_INTERVAL = 300 + TELEMETRY_CLEAN_INTERVAL = 3600 IF_CHANGE_ANNOUNCE_MIN_INTERVAL = 3.5 # In seconds AUTO_ANNOUNCE_RANDOM_MIN = 90 # In minutes @@ -174,6 +176,8 @@ class SidebandCore(): self.pending_telemetry_send_try = 0 self.pending_telemetry_send_maxtries = 2 self.telemetry_send_blocked_until = 0 + self.telemetry_clean_interval = self.TELEMETRY_CLEAN_INTERVAL + self.last_telemetry_clean = 0 self.pending_telemetry_request = False self.telemetry_request_max_history = 7*24*60*60 self.live_tracked_objects = {} @@ -2717,7 +2721,7 @@ class SidebandCore(): db.commit() def _db_clean_messages(self): - RNS.log("Purging stale messages... "+str(self.db_path)) + RNS.log("Purging stale messages... ", RNS.LOG_DEBUG) with self.db_lock: db = self.__db_connect() dbc = db.cursor() @@ -2726,6 +2730,20 @@ class SidebandCore(): dbc.execute(query, {"outbound_state": LXMF.LXMessage.OUTBOUND, "sending_state": LXMF.LXMessage.SENDING}) db.commit() + def _db_clean_telemetry(self): + RNS.log("Cleaning telemetry... ", RNS.LOG_DEBUG) + clean_time = time.time()-self.TELEMETRY_KEEP + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = f"delete from telemetry where (ts < {clean_time});" + dbc.execute(query, {"outbound_state": LXMF.LXMessage.OUTBOUND, "sending_state": LXMF.LXMessage.SENDING}) + db.commit() + + self.last_telemetry_clean = time.time() + + def _db_message_set_state(self, lxm_hash, state, is_retry=False, ratchet_id=None, originator_stamp=None): msg_extras = None if ratchet_id != None: @@ -3525,6 +3543,9 @@ class SidebandCore(): self.setpersistent("lxmf.syncretrying", False) if self.config["telemetry_enabled"]: + if time.time()-self.last_telemetry_clean > self.telemetry_clean_interval: + self._db_clean_telemetry() + if self.config["telemetry_send_to_collector"]: if self.config["telemetry_collector"] != None and self.config["telemetry_collector"] != self.lxmf_destination.hash: try: @@ -4783,6 +4804,7 @@ class SidebandCore(): def start(self): self._db_clean_messages() + self._db_clean_telemetry() self.__start_jobs_immediate() thread = threading.Thread(target=self.__start_jobs_deferred) @@ -5008,6 +5030,10 @@ class SidebandCore(): RNS.log("Error while handling commands: "+str(e), RNS.LOG_ERROR) def create_telemetry_collector_response(self, to_addr, timebase, is_authorized_telemetry_request=False): + if self.getstate(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.update_sending") == True: + RNS.log("Not sending new telemetry collector response, since an earlier transfer is already in progress", RNS.LOG_DEBUG) + return "in_progress" + added_sources = {} sources = self.list_telemetry(after=timebase) only_latest = self.config["telemetry_requests_only_send_latest"] From 54000a72c77fabe5da17c8a3b2213b334213751c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 17 Feb 2025 21:55:50 +0100 Subject: [PATCH 68/76] Improved markdown rendering --- sbapp/main.py | 2 +- sbapp/md2bbcode/main.py | 11 +++-------- sbapp/md2bbcode/renderers/bbcode.py | 26 +++++++++++++++++++------- 3 files changed, 23 insertions(+), 16 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 7bc46d4..ee5239a 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1527,7 +1527,7 @@ class SidebandApp(MDApp): def md_to_bbcode(self, text): if not hasattr(self, "mdconv"): - from md2bbcode.main import process_readme as mdconv + from .md2bbcode.main import process_readme as mdconv self.mdconv = mdconv converted = self.mdconv(text) while converted.endswith("\n"): diff --git a/sbapp/md2bbcode/main.py b/sbapp/md2bbcode/main.py index 4cb1d1c..2897b25 100644 --- a/sbapp/md2bbcode/main.py +++ b/sbapp/md2bbcode/main.py @@ -17,9 +17,9 @@ from mistune.plugins.abbr import abbr from mistune.plugins.spoiler import spoiler # local -from md2bbcode.plugins.merge_lists import merge_ordered_lists -from md2bbcode.renderers.bbcode import BBCodeRenderer -from md2bbcode.html2bbcode import process_html +from .plugins.merge_lists import merge_ordered_lists +from .renderers.bbcode import BBCodeRenderer +from .html2bbcode import process_html def convert_markdown_to_bbcode(markdown_text, domain): # Create a Markdown parser instance using the custom BBCode renderer @@ -32,11 +32,6 @@ def process_readme(markdown_text, domain=None, debug=False): # Convert Markdown to BBCode bbcode_text = convert_markdown_to_bbcode(markdown_text, domain) - # If debug mode, save intermediate BBCode - if debug: - with open('readme.1stpass', 'w', encoding='utf-8') as file: - file.write(bbcode_text) - # Convert BBCode formatted as HTML to final BBCode final_bbcode = process_html(bbcode_text, debug, 'readme.finalpass') diff --git a/sbapp/md2bbcode/renderers/bbcode.py b/sbapp/md2bbcode/renderers/bbcode.py index 32e8b49..f8cf266 100644 --- a/sbapp/md2bbcode/renderers/bbcode.py +++ b/sbapp/md2bbcode/renderers/bbcode.py @@ -26,6 +26,7 @@ class BBCodeRenderer(BaseRenderer): return func(**attrs) else: return func() + if attrs: return func(text, **attrs) else: @@ -69,7 +70,7 @@ class BBCodeRenderer(BaseRenderer): return '\n' def softbreak(self) -> str: - return '' + return '\n' def inline_html(self, html: str) -> str: if self._escape: @@ -126,13 +127,24 @@ class BBCodeRenderer(BaseRenderer): return '[color=red][icode]' + text + '[/icode][/color]\n' def list(self, text: str, ordered: bool, **attrs) -> str: - # For ordered lists, always use [list=1] to get automatic sequential numbering - # For unordered lists, use [list] - tag = 'list=1' if ordered else 'list' - return '[{}]'.format(tag) + text + '[/list]\n' + depth = 0; sln = ""; tli = "" + if "depth" in attrs: depth = attrs["depth"] + if depth != 0: sln = "\n" + if depth == 0: tli = "\n" + def remove_empty_lines(text): + lines = text.split('\n') + non_empty_lines = [line for line in lines if line.strip() != ''] + nli = ""; dlm = "\n"+" "*depth + if depth != 0: nli = dlm + return nli+dlm.join(non_empty_lines) + + text = remove_empty_lines(text) + + return sln+text+"\n"+tli + # return '[{}]'.format(tag) + text + '[/list]\n' def list_item(self, text: str) -> str: - return '[*]' + text + '\n' + return 'β€’ ' + text + '\n' def strikethrough(self, text: str) -> str: return '[s]' + text + '[/s]' @@ -209,7 +221,7 @@ class BBCodeRenderer(BaseRenderer): def task_list_item(self, text: str, checked: bool = False) -> str: # Using emojis to represent the checkbox - checkbox_emoji = 'πŸ—Ή' if checked else '☐' + checkbox_emoji = 'σ°±’' if checked else 'σ°„±' return checkbox_emoji + ' ' + text + '\n' def def_list(self, text: str) -> str: From 587773ace4fcff6ac55b7098c1508108e76476ee Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 17 Feb 2025 22:45:00 +0100 Subject: [PATCH 69/76] Updated dependencies --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 6a5f879..e6a40bf 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.1", + "rns>=0.9.2", "lxmf>=0.6.0", "kivy>=2.3.0", "pillow>=10.2.0", From 1bf11aca6f4ad06cef1b358f3fab97f98c121b9b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 13:51:37 +0100 Subject: [PATCH 70/76] Always use local markdown library --- sbapp/main.py | 6 ++++-- sbapp/md2bbcode/main.py | 13 +++++++++---- sbapp/md2bbcode/md2ast.py | 2 +- sbapp/ui/messages.py | 1 + 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index ee5239a..26266f8 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -197,7 +197,7 @@ if args.daemon: NewConv = DaemonElement; Telemetry = DaemonElement; ObjectDetails = DaemonElement; Announces = DaemonElement; Messages = DaemonElement; ts_format = DaemonElement; messages_screen_kv = DaemonElement; plyer = DaemonElement; multilingual_markup = DaemonElement; ContentNavigationDrawer = DaemonElement; DrawerList = DaemonElement; IconListItem = DaemonElement; escape_markup = DaemonElement; - SoundLoader = DaemonElement; BoxLayout = DaemonElement; + SoundLoader = DaemonElement; BoxLayout = DaemonElement; mdconv = DaemonElement; else: apply_ui_scale() @@ -255,6 +255,8 @@ else: import pyogg from pydub import AudioSegment + from md2bbcode.main import process_readme as mdconv + from kivymd.utils.set_bars_colors import set_bars_colors android_api_version = autoclass('android.os.Build$VERSION').SDK_INT @@ -271,6 +273,7 @@ else: from .ui.messages import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem from .ui.helpers import multilingual_markup, mdc + from .md2bbcode.main import process_readme as mdconv import sbapp.pyogg as pyogg from sbapp.pydub import AudioSegment @@ -1527,7 +1530,6 @@ class SidebandApp(MDApp): def md_to_bbcode(self, text): if not hasattr(self, "mdconv"): - from .md2bbcode.main import process_readme as mdconv self.mdconv = mdconv converted = self.mdconv(text) while converted.endswith("\n"): diff --git a/sbapp/md2bbcode/main.py b/sbapp/md2bbcode/main.py index 2897b25..c001366 100644 --- a/sbapp/md2bbcode/main.py +++ b/sbapp/md2bbcode/main.py @@ -5,6 +5,7 @@ #standard library import argparse import sys +import RNS # mistune import mistune @@ -16,10 +17,14 @@ from mistune.plugins.def_list import def_list from mistune.plugins.abbr import abbr from mistune.plugins.spoiler import spoiler -# local -from .plugins.merge_lists import merge_ordered_lists -from .renderers.bbcode import BBCodeRenderer -from .html2bbcode import process_html +if RNS.vendor.platformutils.is_android(): + from .plugins.merge_lists import merge_ordered_lists + from .renderers.bbcode import BBCodeRenderer + from .html2bbcode import process_html +else: + from sbapp.md2bbcode.plugins.merge_lists import merge_ordered_lists + from sbapp.md2bbcode.renderers.bbcode import BBCodeRenderer + from sbapp.md2bbcode.html2bbcode import process_html def convert_markdown_to_bbcode(markdown_text, domain): # Create a Markdown parser instance using the custom BBCode renderer diff --git a/sbapp/md2bbcode/md2ast.py b/sbapp/md2bbcode/md2ast.py index 65b7c3d..9ffe648 100644 --- a/sbapp/md2bbcode/md2ast.py +++ b/sbapp/md2bbcode/md2ast.py @@ -11,7 +11,7 @@ from mistune.plugins.abbr import abbr from mistune.plugins.spoiler import spoiler #local -from md2bbcode.plugins.merge_lists import merge_ordered_lists +from sbapp.md2bbcode.plugins.merge_lists import merge_ordered_lists def convert_markdown_to_ast(input_filepath, output_filepath): # Initialize Markdown parser with no renderer to produce an AST diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 87557b0..6eb696f 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -510,6 +510,7 @@ class Messages(): except Exception as e: RNS.log(f"Message content could not be decoded: {e}", RNS.LOG_DEBUG) + RNS.trace_exception(e) message_input = b"" if message_input.strip() == b"": From 6b2cf01c697b239b18295298cae16f860ade62c0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 13:59:41 +0100 Subject: [PATCH 71/76] Updated version --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 26266f8..e34cb2b 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.3.1" +__version__ = "1.4.0" __variant__ = "" import sys From 09db4a93287dd59bc9097e64b4fba9c2149f8766 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 16:13:57 +0100 Subject: [PATCH 72/76] Removed library --- sbapp/md2bbcode/__init__.py | 0 sbapp/md2bbcode/html2bbcode.py | 132 -------------- sbapp/md2bbcode/main.py | 67 ------- sbapp/md2bbcode/md2ast.py | 47 ----- sbapp/md2bbcode/plugins/merge_lists.py | 83 --------- sbapp/md2bbcode/renderers/__init__.py | 0 sbapp/md2bbcode/renderers/bbcode.py | 240 ------------------------- 7 files changed, 569 deletions(-) delete mode 100644 sbapp/md2bbcode/__init__.py delete mode 100644 sbapp/md2bbcode/html2bbcode.py delete mode 100644 sbapp/md2bbcode/main.py delete mode 100644 sbapp/md2bbcode/md2ast.py delete mode 100644 sbapp/md2bbcode/plugins/merge_lists.py delete mode 100644 sbapp/md2bbcode/renderers/__init__.py delete mode 100644 sbapp/md2bbcode/renderers/bbcode.py diff --git a/sbapp/md2bbcode/__init__.py b/sbapp/md2bbcode/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/sbapp/md2bbcode/html2bbcode.py b/sbapp/md2bbcode/html2bbcode.py deleted file mode 100644 index 98fd830..0000000 --- a/sbapp/md2bbcode/html2bbcode.py +++ /dev/null @@ -1,132 +0,0 @@ -# converts some HTML tags to BBCode -# pass --debug to save the output to readme.finalpass -# may be better off replacing this with html to markdown (and then to bbcode). Lepture recommeds a JS html to markdown converter: sundown -from bs4 import BeautifulSoup, NavigableString -import argparse - -def handle_font_tag(tag, replacements): - """Handles the conversion of tag with attributes like color and size.""" - attributes = [] - if 'color' in tag.attrs: - attributes.append(f"COLOR={tag['color']}") - if 'size' in tag.attrs: - attributes.append(f"SIZE={tag['size']}") - if 'face' in tag.attrs: - attributes.append(f"FONT={tag['face']}") - - inner_content = ''.join(recursive_html_to_bbcode(child, replacements) for child in tag.children) - if attributes: - # Nest all attributes. Example: [COLOR=red][SIZE=5]content[/SIZE][/COLOR] - for attr in reversed(attributes): - inner_content = f"[{attr}]{inner_content}[/{attr.split('=')[0]}]" - return inner_content - -def handle_style_tag(tag, replacements): - """Handles the conversion of tags with style attributes like color, size, and font.""" - attributes = [] - style = tag.attrs.get('style', '') - - # Extracting CSS properties - css_properties = {item.split(':')[0].strip(): item.split(':')[1].strip() for item in style.split(';') if ':' in item} - - # Mapping CSS properties to BBCode - if 'color' in css_properties: - attributes.append(f"COLOR={css_properties['color']}") - if 'font-size' in css_properties: - attributes.append(f"SIZE={css_properties['font-size']}") - if 'font-family' in css_properties: - attributes.append(f"FONT={css_properties['font-family']}") - if 'text-decoration' in css_properties and 'line-through' in css_properties['text-decoration']: - attributes.append("S") # Assume strike-through - if 'text-decoration' in css_properties and 'underline' in css_properties['text-decoration']: - attributes.append("U") - if 'font-weight' in css_properties: - if css_properties['font-weight'].lower() == 'bold' or (css_properties['font-weight'].isdigit() and int(css_properties['font-weight']) >= 700): - attributes.append("B") # Assume bold - - inner_content = ''.join(recursive_html_to_bbcode(child, replacements) for child in tag.children) - if attributes: - # Nest all attributes - for attr in reversed(attributes): - if '=' in attr: # For attributes with values - inner_content = f"[{attr}]{inner_content}[/{attr.split('=')[0]}]" - else: # For simple BBCode tags like [B], [I], [U], [S] - inner_content = f"[{attr}]{inner_content}[/{attr}]" - return inner_content - -def recursive_html_to_bbcode(element): - """Recursively convert HTML elements to BBCode.""" - bbcode = '' - - if isinstance(element, NavigableString): - bbcode += str(element) - elif element.name == 'details': - # Handle
tag - summary = element.find('summary') - spoiler_title = '' - if summary: - # Get the summary content and remove the summary element - spoiler_title = '=' + ''.join([recursive_html_to_bbcode(child) for child in summary.contents]) - summary.decompose() - - # Process remaining content - content = ''.join([recursive_html_to_bbcode(child) for child in element.contents]) - bbcode += f'[SPOILER{spoiler_title}]{content}[/SPOILER]' - elif element.name == 'summary': - # Skip summary tag as it's handled in details - return '' - else: - # Handle other tags or pass through - content = ''.join([recursive_html_to_bbcode(child) for child in element.contents]) - bbcode += content - - return bbcode - -def html_to_bbcode(html): - replacements = { - 'b': 'B', - 'strong': 'B', - 'i': 'I', - 'em': 'I', - 'u': 'U', - 's': 'S', - 'sub': 'SUB', - 'sup': 'SUP', - 'p': '', # Handled by default - 'ul': 'LIST', - 'ol': 'LIST=1', - 'li': '*', # Special handling in recursive function - 'font': '', # To be handled for attributes - 'blockquote': 'QUOTE', - 'pre': 'CODE', - 'code': 'ICODE', - 'a': 'URL', # Special handling for attributes - 'img': 'IMG' # Special handling for attributes - } - - soup = BeautifulSoup(html, 'html.parser') - return recursive_html_to_bbcode(soup) - -def process_html(input_html, debug=False, output_file=None): - converted_bbcode = html_to_bbcode(input_html) - - if debug: - with open(output_file, 'w', encoding='utf-8') as file: - file.write(converted_bbcode) - else: - return converted_bbcode - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Convert HTML to BBCode with optional debugging output.") - parser.add_argument('input_file', type=str, help='Input HTML file path') - parser.add_argument('--debug', action='store_true', help='Save output to readme.finalpass for debugging') - - args = parser.parse_args() - input_file = args.input_file - output_file = 'readme.finalpass' if args.debug else None - - with open(input_file, 'r', encoding='utf-8') as file: - html_content = file.read() - - # Call the processing function - process_html(html_content, debug=args.debug, output_file=output_file) \ No newline at end of file diff --git a/sbapp/md2bbcode/main.py b/sbapp/md2bbcode/main.py deleted file mode 100644 index c001366..0000000 --- a/sbapp/md2bbcode/main.py +++ /dev/null @@ -1,67 +0,0 @@ -# uses a custom mistune renderer to convert Markdown to BBCode. The custom renderer is defined in the bbcode.py file. -# pass --debug to save the output to readme.1stpass (main.py) and readme.finalpass (html2bbcode) -# for further debugging, you can convert the markdown file to AST using md2ast.py. Remember to load the plugin(s) you want to test. - -#standard library -import argparse -import sys -import RNS - -# mistune -import mistune -from mistune.plugins.formatting import strikethrough, mark, superscript, subscript, insert -from mistune.plugins.table import table, table_in_list -from mistune.plugins.footnotes import footnotes -from mistune.plugins.task_lists import task_lists -from mistune.plugins.def_list import def_list -from mistune.plugins.abbr import abbr -from mistune.plugins.spoiler import spoiler - -if RNS.vendor.platformutils.is_android(): - from .plugins.merge_lists import merge_ordered_lists - from .renderers.bbcode import BBCodeRenderer - from .html2bbcode import process_html -else: - from sbapp.md2bbcode.plugins.merge_lists import merge_ordered_lists - from sbapp.md2bbcode.renderers.bbcode import BBCodeRenderer - from sbapp.md2bbcode.html2bbcode import process_html - -def convert_markdown_to_bbcode(markdown_text, domain): - # Create a Markdown parser instance using the custom BBCode renderer - markdown_parser = mistune.create_markdown(renderer=BBCodeRenderer(domain=domain), plugins=[strikethrough, mark, superscript, subscript, insert, table, footnotes, task_lists, def_list, abbr, spoiler, table_in_list, merge_ordered_lists]) - - # Convert Markdown text to BBCode - return markdown_parser(markdown_text) - -def process_readme(markdown_text, domain=None, debug=False): - # Convert Markdown to BBCode - bbcode_text = convert_markdown_to_bbcode(markdown_text, domain) - - # Convert BBCode formatted as HTML to final BBCode - final_bbcode = process_html(bbcode_text, debug, 'readme.finalpass') - - return final_bbcode - -def main(): - parser = argparse.ArgumentParser(description='Convert Markdown file to BBCode with HTML processing.') - parser.add_argument('input', help='Input Markdown file path') - parser.add_argument('--domain', help='Domain to prepend to relative URLs') - parser.add_argument('--debug', action='store_true', help='Output intermediate results to files for debugging') - args = parser.parse_args() - - if args.input == '-': - # Read Markdown content from stdin - markdown_text = sys.stdin.read() - else: - with open(args.input, 'r', encoding='utf-8') as md_file: - markdown_text = md_file.read() - - # Process the readme and get the final BBCode - final_bbcode = process_readme(markdown_text, args.domain, args.debug) - - # Optionally, print final BBCode to console - if not args.debug: - print(final_bbcode) - -if __name__ == '__main__': - main() diff --git a/sbapp/md2bbcode/md2ast.py b/sbapp/md2bbcode/md2ast.py deleted file mode 100644 index 9ffe648..0000000 --- a/sbapp/md2bbcode/md2ast.py +++ /dev/null @@ -1,47 +0,0 @@ -# this is for debugging the custom mistune renderer bbcode.py -import argparse -import mistune -import json # Import the json module for serialization -from mistune.plugins.formatting import strikethrough, mark, superscript, subscript, insert -from mistune.plugins.table import table, table_in_list -from mistune.plugins.footnotes import footnotes -from mistune.plugins.task_lists import task_lists -from mistune.plugins.def_list import def_list -from mistune.plugins.abbr import abbr -from mistune.plugins.spoiler import spoiler - -#local -from sbapp.md2bbcode.plugins.merge_lists import merge_ordered_lists - -def convert_markdown_to_ast(input_filepath, output_filepath): - # Initialize Markdown parser with no renderer to produce an AST - markdown_parser = mistune.create_markdown(renderer=None, plugins=[strikethrough, mark, superscript, subscript, insert, table, footnotes, task_lists, def_list, abbr, spoiler, table_in_list, merge_ordered_lists]) - - # Read the input Markdown file - with open(input_filepath, 'r', encoding='utf-8') as md_file: - markdown_text = md_file.read() - - # Convert Markdown text to AST - ast_text = markdown_parser(markdown_text) - - # Serialize the AST to a JSON string - ast_json = json.dumps(ast_text, indent=4) - - # Write the output AST to a new file in JSON format - with open(output_filepath, 'w', encoding='utf-8') as ast_file: - ast_file.write(ast_json) - -def main(): - # Create argument parser - parser = argparse.ArgumentParser(description='Convert Markdown file to AST file (JSON format).') - # Add arguments - parser.add_argument('input', help='Input Markdown file path') - parser.add_argument('output', help='Output AST file path (JSON format)') - # Parse arguments - args = parser.parse_args() - - # Convert the Markdown to AST using the provided paths - convert_markdown_to_ast(args.input, args.output) - -if __name__ == '__main__': - main() diff --git a/sbapp/md2bbcode/plugins/merge_lists.py b/sbapp/md2bbcode/plugins/merge_lists.py deleted file mode 100644 index 5f499e1..0000000 --- a/sbapp/md2bbcode/plugins/merge_lists.py +++ /dev/null @@ -1,83 +0,0 @@ -from typing import Dict, Any, List - -def merge_ordered_lists(md): - """ - A plugin to merge consecutive "top-level" ordered lists into one, - and also attach any intervening code blocks or blank lines to the - last list item so that the final BBCode appears as a single list - with multiple steps. - - This relies on a few assumptions: - 1) The only tokens between two ordered lists that should be merged - are code blocks or blank lines (not normal paragraphs). - 2) We want any code block(s) right after a list item to appear in - that same bullet item. - """ - - def rewrite_tokens(md, state): - tokens = state.tokens - merged = [] - i = 0 - - while i < len(tokens): - token = tokens[i] - - # Check if this token is a top-level ordered list - if ( - token["type"] == "list" - and token.get("attrs", {}).get("ordered", False) - and token.get("attrs", {}).get("depth", 0) == 0 - ): - # Start new merged list - current_depth = token["attrs"]["depth"] - list_items = list(token["children"]) # bullet items in the first list - i += 1 - - # Continue until we run into something that's not: - # another top-level ordered list, - # or code blocks / blank lines (which we'll attach to the last bullet). - while i < len(tokens): - nxt = tokens[i] - - # If there's another ordered list at the same depth, merge its bullet items - if ( - nxt["type"] == "list" - and nxt.get("attrs", {}).get("ordered", False) - and nxt.get("attrs", {}).get("depth", 0) == current_depth - ): - list_items.extend(nxt["children"]) - i += 1 - - # If there's a code block or blank line, attach it to the *last* bullet item. - elif nxt["type"] in ["block_code", "blank_line"]: - if list_items: # attach to last bullet item, if any - list_items[-1]["children"].append(nxt) - i += 1 - - else: - # Not a same-depth list or code blockβ€”stop merging - break - - # Create single merged list token - merged.append( - { - "type": "list", - "children": list_items, - "attrs": { - "ordered": True, - "depth": current_depth, - }, - } - ) - - else: - # If not a top-level ordered list, just keep it as-is - merged.append(token) - i += 1 - - # Replace the old tokens with the merged version - state.tokens = merged - - # Attach to before_render_hooks so we can manipulate tokens before rendering - md.before_render_hooks.append(rewrite_tokens) - return md \ No newline at end of file diff --git a/sbapp/md2bbcode/renderers/__init__.py b/sbapp/md2bbcode/renderers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/sbapp/md2bbcode/renderers/bbcode.py b/sbapp/md2bbcode/renderers/bbcode.py deleted file mode 100644 index f8cf266..0000000 --- a/sbapp/md2bbcode/renderers/bbcode.py +++ /dev/null @@ -1,240 +0,0 @@ -from mistune.core import BaseRenderer -from mistune.util import escape as escape_text, striptags, safe_entity -from urllib.parse import urljoin, urlparse - - -class BBCodeRenderer(BaseRenderer): - """A renderer for converting Markdown to BBCode.""" - _escape: bool - NAME = 'bbcode' - - def __init__(self, escape=False, domain=None): - super(BBCodeRenderer, self).__init__() - self._escape = escape - self.domain = domain - - def render_token(self, token, state): - func = self._get_method(token['type']) - attrs = token.get('attrs') - - if 'raw' in token: - text = token['raw'] - elif 'children' in token: - text = self.render_tokens(token['children'], state) - else: - if attrs: - return func(**attrs) - else: - return func() - - if attrs: - return func(text, **attrs) - else: - return func(text) - - def safe_url(self, url: str) -> str: - # Simple URL sanitization - if url.startswith(('javascript:', 'vbscript:', 'data:')): - return '#harmful-link' - # Check if the URL is absolute by looking for a netloc part in the URL - if not urlparse(url).netloc: - url = urljoin(self.domain, url) - return url - - def text(self, text: str) -> str: - if self._escape: - return escape_text(text) - return text - - def emphasis(self, text: str) -> str: - return '[i]' + text + '[/i]' - - def strong(self, text: str) -> str: - return '[b]' + text + '[/b]' - - def link(self, text: str, url: str, title=None) -> str: - return '[url=' + self.safe_url(url) + ']' + text + '[/url]' - - def image(self, text: str, url: str, title=None) -> str: - alt_text = f' alt="{text}"' if text else '' - img_tag = f'[img{alt_text}]' + self.safe_url(url) + '[/img]' - # Check if alt text starts with 'pixel' and treat it as pixel art - if text and text.lower().startswith('pixel'): - return f'[pixelate]{img_tag}[/pixelate]' - return img_tag - - def codespan(self, text: str) -> str: - return '[icode]' + text + '[/icode]' - - def linebreak(self) -> str: - return '\n' - - def softbreak(self) -> str: - return '\n' - - def inline_html(self, html: str) -> str: - if self._escape: - return escape_text(html) - return html - - def paragraph(self, text: str) -> str: - return text + '\n\n' - - def heading(self, text: str, level: int, **attrs) -> str: - if 1 <= level <= 3: - return f"[HEADING={level}]{text}[/HEADING]\n" - else: - # Handle cases where level is outside 1-3 - return f"[HEADING=3]{text}[/HEADING]\n" - - def blank_line(self) -> str: - return '' - - def thematic_break(self) -> str: - return '[hr][/hr]\n' - - def block_text(self, text: str) -> str: - return text - - def block_code(self, code: str, **attrs) -> str: - # Renders blocks of code using the language specified in Markdown - special_cases = { - 'plaintext': None # Default [CODE] - } - - if 'info' in attrs: - lang_info = safe_entity(attrs['info'].strip()) - lang = lang_info.split(None, 1)[0].lower() - # Check if the language needs special handling - bbcode_lang = special_cases.get(lang, lang) # Use the special case if it exists, otherwise use lang as is - if bbcode_lang: - return f"[CODE={bbcode_lang}]{escape_text(code)}[/CODE]\n" - else: - return f"[CODE]{escape_text(code)}[/CODE]\n" - else: - # No language specified, render with a generic [CODE] tag - return f"[CODE]{escape_text(code)}[/CODE]\n" - - def block_quote(self, text: str) -> str: - return '[QUOTE]\n' + text + '[/QUOTE]\n' - - def block_html(self, html: str) -> str: - if self._escape: - return '

' + escape_text(html.strip()) + '

\n' - return html + '\n' - - def block_error(self, text: str) -> str: - return '[color=red][icode]' + text + '[/icode][/color]\n' - - def list(self, text: str, ordered: bool, **attrs) -> str: - depth = 0; sln = ""; tli = "" - if "depth" in attrs: depth = attrs["depth"] - if depth != 0: sln = "\n" - if depth == 0: tli = "\n" - def remove_empty_lines(text): - lines = text.split('\n') - non_empty_lines = [line for line in lines if line.strip() != ''] - nli = ""; dlm = "\n"+" "*depth - if depth != 0: nli = dlm - return nli+dlm.join(non_empty_lines) - - text = remove_empty_lines(text) - - return sln+text+"\n"+tli - # return '[{}]'.format(tag) + text + '[/list]\n' - - def list_item(self, text: str) -> str: - return 'β€’ ' + text + '\n' - - def strikethrough(self, text: str) -> str: - return '[s]' + text + '[/s]' - - def mark(self, text: str) -> str: - # Simulate the mark effect with a background color in BBCode - return '[mark]' + text + '[/mark]' - - def insert(self, text: str) -> str: - # Use underline to represent insertion - return '[u]' + text + '[/u]' - - def superscript(self, text: str) -> str: - return '[sup]' + text + '[/sup]' - - def subscript(self, text: str) -> str: - return '[sub]' + text + '[/sub]' - - def inline_spoiler(self, text: str) -> str: - return '[ISPOILER]' + text + '[/ISPOILER]' - - def block_spoiler(self, text: str) -> str: - return '[SPOILER]\n' + text + '\n[/SPOILER]' - - def footnote_ref(self, key: str, index: int): - # Use superscript for the footnote reference - return f'[sup][u][JUMPTO=fn-{index}]{index}[/JUMPTO][/u][/sup]' - - def footnotes(self, text: str): - # Optionally wrap all footnotes in a specific section if needed - return '[b]Footnotes:[/b]\n' + text - - def footnote_item(self, text: str, key: str, index: int): - # Define the footnote with an anchor at the end of the document - return f'[ANAME=fn-{index}]{index}[/ANAME]. {text}' - - def table(self, children, **attrs): - # Starting with a full-width table by default if not specified - # width = attrs.get('width', '100%') # comment out until XF 2.3 - # return f'[TABLE width="{width}"]\n' + children + '[/TABLE]\n' # comment out until XF 2.3 - return '[TABLE]\n' + children + '[/TABLE]\n' - - def table_head(self, children, **attrs): - return '[TR]\n' + children + '[/TR]\n' - - def table_body(self, children, **attrs): - return children - - def table_row(self, children, **attrs): - return '[TR]\n' + children + '[/TR]\n' - - def table_cell(self, text, align=None, head=False, **attrs): - # BBCode does not support direct cell alignment, - # use [LEFT], [CENTER], or [RIGHT] tags - - # Use th for header cells and td for normal cells - tag = 'TH' if head else 'TD' - - # Initialize alignment tags - alignment_start = '' - alignment_end = '' - - if align == 'center': - alignment_start = '[CENTER]' - alignment_end = '[/CENTER]' - elif align == 'right': - alignment_start = '[RIGHT]' - alignment_end = '[/RIGHT]' - elif align == 'left': - alignment_start = '[LEFT]' - alignment_end = '[/LEFT]' - - return f'[{tag}]{alignment_start}{text}{alignment_end}[/{tag}]\n' - - def task_list_item(self, text: str, checked: bool = False) -> str: - # Using emojis to represent the checkbox - checkbox_emoji = 'σ°±’' if checked else 'σ°„±' - return checkbox_emoji + ' ' + text + '\n' - - def def_list(self, text: str) -> str: - # No specific BBCode tag for
, so we just use the plain text grouping - return '\n' + text + '\n' - - def def_list_head(self, text: str) -> str: - return '[b]' + text + '[/b]' + ' ' + ':' + '\n' - - def def_list_item(self, text: str) -> str: - return '[INDENT]' + text + '[/INDENT]\n' - - def abbr(self, text: str, title: str) -> str: - if title: - return f'[abbr={title}]{text}[/abbr]' - return text \ No newline at end of file From 03cc00483bc4b071cde94767dc02bfbcb649b750 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 16:15:21 +0100 Subject: [PATCH 73/76] Improved markdown rendering --- sbapp/md/__init__.py | 1 + sbapp/md/md.py | 110 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 sbapp/md/__init__.py create mode 100644 sbapp/md/md.py diff --git a/sbapp/md/__init__.py b/sbapp/md/__init__.py new file mode 100644 index 0000000..42253a8 --- /dev/null +++ b/sbapp/md/__init__.py @@ -0,0 +1 @@ +from .md import mdconv \ No newline at end of file diff --git a/sbapp/md/md.py b/sbapp/md/md.py new file mode 100644 index 0000000..f2c3f6b --- /dev/null +++ b/sbapp/md/md.py @@ -0,0 +1,110 @@ +import mistune +from mistune.core import BaseRenderer +from mistune.plugins.formatting import strikethrough, mark, superscript, subscript, insert +from mistune.plugins.table import table, table_in_list +from mistune.plugins.footnotes import footnotes +from mistune.plugins.task_lists import task_lists +from mistune.plugins.spoiler import spoiler +from mistune.util import escape as escape_text, safe_entity + +def mdconv(markdown_text, domain=None, debug=False): + parser = mistune.create_markdown(renderer=BBRenderer(), plugins=[strikethrough, mark, superscript, subscript, insert, footnotes, task_lists, spoiler]) + return parser(markdown_text) + +class BBRenderer(BaseRenderer): + NAME = "bbcode" + + def __init__(self, escape=False): + super(BBRenderer, self).__init__() + self._escape = escape + + def render_token(self, token, state): + func = self._get_method(token["type"]) + attrs = token.get("attrs") + + if "raw" in token: text = token["raw"] + elif "children" in token: text = self.render_tokens(token["children"], state) + else: + if attrs: return func(**attrs) + else: return func() + + if attrs: return func(text, **attrs) + else: return func(text) + + # Simple renderers + def emphasis(self, text): return f"[i]{text}[/i]" + def strong(self, text): return f"[b]{text}[/b]" + def codespan(self, text): return f"[icode]{text}[/icode]" + def linebreak(self): return "\n" + def softbreak(self): return "\n" + def list_item(self, text): return f"β€’ {text}\n" + def task_list_item(self, text, checked=False): e = "σ°±’" if checked else "σ°„±"; return f"{e} {text}\n" + def strikethrough(self, text): return f"[s]{text}[/s]" + def insert(self, text): return f"[u]{text}[/u]" + def inline_spoiler(self, text): return f"[ISPOILER]{text}[/ISPOILER]" + def block_spoiler(self, text): return f"[SPOILER]\n{text}\n[/SPOILER]" + def block_error(self, text): return f"[color=red][icode]{text}[/icode][/color]\n" + def block_html(self, html): return "" + def link(self, text, url, title=None): return f"[u]{text}[/u] ({url})" + def footnote_ref(self, key, index): return f"[sup][u]{index}[/u][/sup]" + def footnotes(self, text): return f"[b]Footnotes[/b]\n{text}" + def footnote_item(self, text, key, index): return f"[ANAME=footnote-{index}]{index}[/ANAME]. {text}" + def superscript(self, text: str) -> str: return f"[sup]{text}[/sup]" + def subscript(self, text): return f"[sub]{text}[/sub]" + def block_quote(self, text: str) -> str: return f"| [i]{text}[/i]" + def paragraph(self, text): return f"{text}\n\n" + def blank_line(self): return "" + def block_text(self, text): return text + + # Renderers needing some logic + def text(self, text): + if self._escape: return escape_text(text) + else: return text + + def inline_html(self, html: str) -> str: + if self._escape: return escape_text(html) + else: return html + + def heading(self, text, level, **attrs): + if 1 <= level <= 3: return f"[HEADING={level}]{text}[/HEADING]\n" + else: return f"[HEADING=3]{text}[/HEADING]\n" + + def block_code(self, code: str, **attrs) -> str: + special_cases = {"plaintext": None, "text": None, "txt": None} + if "info" in attrs: + lang_info = safe_entity(attrs["info"].strip()) + lang = lang_info.split(None, 1)[0].lower() + bbcode_lang = special_cases.get(lang, lang) + if bbcode_lang: return f"[CODE={bbcode_lang}]{escape_text(code)}[/CODE]\n" + else: return f"[CODE]{escape_text(code)}[/CODE]\n" + + else: return f"[CODE]{escape_text(code)}[/CODE]\n" + + def list(self, text, ordered, **attrs): + depth = 0; sln = ""; tli = "" + if "depth" in attrs: depth = attrs["depth"] + if depth != 0: sln = "\n" + if depth == 0: tli = "\n" + def remove_empty_lines(text): + lines = text.split("\n") + non_empty_lines = [line for line in lines if line.strip() != ""] + nli = ""; dlm = "\n"+" "*depth + if depth != 0: nli = dlm + return nli+dlm.join(non_empty_lines) + + text = remove_empty_lines(text) + return sln+text+"\n"+tli + + # TODO: Implement various table types and other special formatting + def table(self, children, **attrs): return children + def table_head(self, children, **attrs): return children + def table_body(self, children, **attrs): return children + def table_row(self, children, **attrs): return children + def table_cell(self, text, align=None, head=False, **attrs): return f"{text}\n" + def def_list(self, text): return f"{text}\n" + def def_list_head(self, text): return f"{text}\n" + def def_list_item(self, text): return f"{text}\n" + def abbr(self, text, title): return text + def mark(self, text): return text + def image(self, text, url, title=None): return "" + def thematic_break(self): return "-------------\n" \ No newline at end of file From 9494ab80950f06dd45cb13ff86f98be07db84f0c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 16:16:11 +0100 Subject: [PATCH 74/76] Improved markdown rendering --- sbapp/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e34cb2b..58eed93 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -255,8 +255,6 @@ else: import pyogg from pydub import AudioSegment - from md2bbcode.main import process_readme as mdconv - from kivymd.utils.set_bars_colors import set_bars_colors android_api_version = autoclass('android.os.Build$VERSION').SDK_INT @@ -273,7 +271,6 @@ else: from .ui.messages import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem from .ui.helpers import multilingual_markup, mdc - from .md2bbcode.main import process_readme as mdconv import sbapp.pyogg as pyogg from sbapp.pydub import AudioSegment @@ -1530,7 +1527,10 @@ class SidebandApp(MDApp): def md_to_bbcode(self, text): if not hasattr(self, "mdconv"): + if RNS.vendor.platformutils.is_android(): from md import mdconv + else: from .md import mdconv self.mdconv = mdconv + converted = self.mdconv(text) while converted.endswith("\n"): converted = converted[:-1] From 3f9204e1e1b04e3cf37185ccd1630482e0f75366 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 16:17:34 +0100 Subject: [PATCH 75/76] Cleanup --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 58eed93..ffb2cf4 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2811,7 +2811,7 @@ class SidebandApp(MDApp): str_comps = " - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)" - str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]FFmpeg[/b] (GPL3 License)\n - [b]MD2bbcode[/b] (GPL3 License)" + str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]FFmpeg[/b] (GPL3 License)" str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Paho MQTT[/b] (EPL2 License)\n - [b]Python[/b] (PSF License)" str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright Β© 2025 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY" info = "This is "+self.root.ids.app_version_info.text+", on RNS v"+RNS.__version__+" and LXMF v"+LXMF.__version__+".\n\nHumbly build using the following open components:\n\n"+str_comps From 4b5128f177312ef72f9eec57728500180b09d3be Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Feb 2025 16:18:22 +0100 Subject: [PATCH 76/76] Cleanup --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf0a057..557b655 100644 --- a/README.md +++ b/README.md @@ -311,11 +311,11 @@ You can help support the continued development of open, free and private communi - Adding a Linux desktop integration - Adding prebuilt Windows binaries to the releases - Adding prebuilt macOS binaries to the releases +- A debug log viewer - Adding a Nomad Net page browser - LXMF sneakernet functionality - Network visualisation and test tools - Better message sorting mechanism -- A debug log viewer # License Unless otherwise noted, this work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License][cc-by-nc-sa].