From 13071fd9d863bf82cf08ca14fe833777b2ef6a96 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 20 Jan 2025 17:28:29 +0100 Subject: [PATCH 001/271] 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 002/271] 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 003/271] 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 004/271] 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 005/271] 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 006/271] 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 007/271] 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 008/271] 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 009/271] 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 010/271] 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 011/271] 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 012/271] 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 013/271] 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 014/271] 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 015/271] 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 016/271] 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 017/271] 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 018/271] 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 019/271] 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 020/271] 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 021/271] 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 022/271] 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 023/271] 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 024/271] 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 025/271] 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 026/271] 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 027/271] 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 028/271] 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 029/271] 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 030/271] 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 031/271] 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 032/271] 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 033/271] 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 034/271] 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 035/271] 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 036/271] 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 037/271] 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 038/271] 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 039/271] 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 040/271] 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 041/271] 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 042/271] 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 043/271] 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 044/271] 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 045/271] 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]. From 3d6d039a489f5b65f816bd4517a9e2e4ea6a293a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 20 Feb 2025 23:03:38 +0100 Subject: [PATCH 046/271] Updated intent filter to allow sharing any file type for attachments --- sbapp/buildozer.spec | 2 +- sbapp/patches/intent-filter.xml | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index df728e8..b6b8594 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 = 20250126 +android.numeric_version = 20250220 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/patches/intent-filter.xml b/sbapp/patches/intent-filter.xml index 6ec9ab0..37c4df6 100644 --- a/sbapp/patches/intent-filter.xml +++ b/sbapp/patches/intent-filter.xml @@ -28,6 +28,10 @@ + + + + Date: Sat, 22 Feb 2025 21:26:44 +0100 Subject: [PATCH 047/271] Added audioop-lts on python >= 3.13 --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index e6a40bf..aa03687 100644 --- a/setup.py +++ b/setup.py @@ -129,6 +129,7 @@ setuptools.setup( "pyaudio;sys.platform=='linux'", "pyobjus;sys.platform=='darwin'", "pyogg;sys.platform=='Windows' and sys.platform!='win32'", + "audioop-lts>=0.2.1;python_version>='3.13'" ], python_requires='>=3.7', ) From 63030a6f48c8249a4555d0541f49cee7b44a0360 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 23 Feb 2025 22:42:43 +0100 Subject: [PATCH 048/271] Added link stats to object details --- sbapp/sideband/core.py | 70 +++++++++++++++++++++++++++++++++++++++ sbapp/ui/objectdetails.py | 22 +++++++----- 2 files changed, 84 insertions(+), 8 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 36b8162..ee6a173 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1838,6 +1838,72 @@ class SidebandCore(): RNS.log(ed, RNS.LOG_DEBUG) return None + def _get_destination_mtu(self, destination_hash): + try: + mr = self.message_router + oh = destination_hash + ol = None + if oh in mr.direct_links: + ol = mr.direct_links[oh] + elif oh in mr.backchannel_links: + ol = mr.backchannel_links[oh] + + if ol != None: + return ol.get_mtu() + + return None + + except Exception as e: + RNS.trace_exception(e) + return None + + def get_destination_mtu(self, destination_hash): + if not RNS.vendor.platformutils.is_android(): + return self._get_destination_mtu(destination_hash) + else: + if self.is_service: + return self._get_destination_mtu(destination_hash) + else: + try: + return self.service_rpc_request({"get_destination_mtu": destination_hash}) + except Exception as e: + ed = "Error while getting destination link MTU over RPC: "+str(e) + RNS.log(ed, RNS.LOG_DEBUG) + return None + + def _get_destination_edr(self, destination_hash): + try: + mr = self.message_router + oh = destination_hash + ol = None + if oh in mr.direct_links: + ol = mr.direct_links[oh] + elif oh in mr.backchannel_links: + ol = mr.backchannel_links[oh] + + if ol != None: + return ol.get_expected_rate() + + return None + + except Exception as e: + RNS.trace_exception(e) + return None + + def get_destination_edr(self, destination_hash): + if not RNS.vendor.platformutils.is_android(): + return self._get_destination_edr(destination_hash) + else: + if self.is_service: + return self._get_destination_edr(destination_hash) + else: + try: + return self.service_rpc_request({"get_destination_edr": destination_hash}) + except Exception as e: + ed = "Error while getting destination link EIFR over RPC: "+str(e) + RNS.log(ed, RNS.LOG_DEBUG) + return None + def __start_rpc_listener(self): try: RNS.log("Starting RPC listener", RNS.LOG_DEBUG) @@ -1882,6 +1948,10 @@ class SidebandCore(): connection.send(self._get_plugins_info()) elif "get_destination_establishment_rate" in call: connection.send(self._get_destination_establishment_rate(call["get_destination_establishment_rate"])) + elif "get_destination_mtu" in call: + connection.send(self._get_destination_mtu(call["get_destination_mtu"])) + elif "get_destination_edr" in call: + connection.send(self._get_destination_edr(call["get_destination_edr"])) elif "send_message" in call: args = call["send_message"] send_result = self.send_message( diff --git a/sbapp/ui/objectdetails.py b/sbapp/ui/objectdetails.py index a5ab969..0de4f3d 100644 --- a/sbapp/ui/objectdetails.py +++ b/sbapp/ui/objectdetails.py @@ -822,17 +822,23 @@ class RVDetails(MDRecycleView): if nhi and nhi != "None": self.entries.append({"icon": "routes", "text": f"Current path on [b]{nhi}[/b]", "on_release": pass_job}) - try: - ler = self.delegate.app.sideband.get_destination_establishment_rate(self.delegate.object_hash) - if ler: - lers = RNS.prettyspeed(ler, "b") - self.entries.append({"icon": "lock-check-outline", "text": f"Direct link established, LER is [b]{lers}[/b]", "on_release": pass_job}) - except Exception as e: - RNS.trace_exception(e) - if nh != RNS.Transport.PATHFINDER_M: hs = "hop" if nh == 1 else "hops" self.entries.append({"icon": "atom-variant", "text": f"Network distance is [b]{nh} {hs}[/b]", "on_release": pass_job}) + + try: + ler = self.delegate.app.sideband.get_destination_establishment_rate(self.delegate.object_hash) + mtu = self.delegate.app.sideband.get_destination_mtu(self.delegate.object_hash) or RNS.Reticulum.MTU + edr = self.delegate.app.sideband.get_destination_edr(self.delegate.object_hash) + if ler: + lers = RNS.prettyspeed(ler, "b") + mtus = RNS.prettysize(mtu) + edrs = f"{RNS.prettyspeed(edr)}" if edr != None else "" + self.entries.append({"icon": "lock-check-outline", "text": f"Link established, LER is [b]{lers}[/b], MTU is [b]{mtus}[/b]", "on_release": pass_job}) + if edr: self.entries.append({"icon": "approximately-equal", "text": f"Expected data rate is [b]{edrs}[/b]", "on_release": pass_job}) + except Exception as e: + RNS.trace_exception(e) + except Exception as e: RNS.trace_exception(e) From 88f427b97c3e275385f29e4a26fd74e89f5713a3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Feb 2025 12:39:12 +0100 Subject: [PATCH 049/271] Catch OS notification limit exceptions --- sbapp/sideband/core.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index ee6a173..4e59c16 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -993,13 +993,16 @@ class SidebandCore(): notifications_permitted = True if notifications_permitted: - if RNS.vendor.platformutils.get_platform() == "android": - if self.is_service: - self.owner_service.android_notification(title, content, group=group, context_id=context_id) + try: + if RNS.vendor.platformutils.get_platform() == "android": + if self.is_service: + self.owner_service.android_notification(title, content, group=group, context_id=context_id) + else: + plyer.notification.notify(title, content, notification_icon=self.notification_icon, context_override=None) else: - plyer.notification.notify(title, content, notification_icon=self.notification_icon, context_override=None) - else: - plyer.notification.notify(title, content, app_icon=self.icon_32) + plyer.notification.notify(title, content, app_icon=self.icon_32) + except Exception as e: + RNS.log("An error occurred while posting a notification to the operating system: {e}", RNS.LOG_ERROR) def log_announce(self, dest, app_data, dest_type, stamp_cost=None, link_stats=None): try: From fbd5896856e4051b11f83199e8c7cdee6d264c74 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 11:15:33 +0100 Subject: [PATCH 050/271] Fixed telemetry plugin init error --- sbapp/sideband/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 4e59c16..0a4e780 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -3287,7 +3287,7 @@ class SidebandCore(): else: self.telemeter.disable(sensor) - for telemetry_plugin in self.active_telemetry_plugins: + for telemetry_plugin in self.active_telemetry_plugins.copy(): try: plugin = self.active_telemetry_plugins[telemetry_plugin] plugin.update_telemetry(self.telemeter) From 3faa7e220313333348d168044df3304fba6d3d3c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 14:28:03 +0100 Subject: [PATCH 051/271] Added BME280 telemetry plugin --- docs/example_plugins/bme280_telemetry.py | 67 ++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/example_plugins/bme280_telemetry.py diff --git a/docs/example_plugins/bme280_telemetry.py b/docs/example_plugins/bme280_telemetry.py new file mode 100644 index 0000000..af29c70 --- /dev/null +++ b/docs/example_plugins/bme280_telemetry.py @@ -0,0 +1,67 @@ +# This plugin provides temperature, humidity +# and pressure data via a BME280 sensor +# connected over I2C. The plugin requires +# the "smbus2" and "RPi.bme280" modules to +# be available on your system. These can be +# installed with: +# +# pip install smbus2 RPi.bme280 + +import os +import RNS +from importlib.util import find_spec + +class BME280Plugin(SidebandTelemetryPlugin): + plugin_name = "telemetry_bme280" + + I2C_ADDRESS = 0x76 + I2C_BUS = 1 + + # If your BME280 has an offset from the true + # temperature, you can compensate for this + # by modifying this parameter. + TEMPERATURE_CORRECTION = 0.0 + + def start(self): + RNS.log("BME280 telemetry plugin starting...") + + if find_spec("smbus2"): import smbus2 + else: raise OSError(f"No smbus2 module available, cannot start BME280 telemetry plugin") + + if find_spec("bme280"): import bme280 + else: raise OSError(f"No bme280 module available, cannot start BME280 telemetry plugin") + + self.sensor_connected = False + + try: + self.bme280 = bme280 + self.address = self.I2C_ADDRESS + self.bus = smbus2.SMBus(self.I2C_BUS) + self.calibration = self.bme280.load_calibration_params(self.bus, self.address) + self.sensor_connected = True + self.tc = self.TEMPERATURE_CORRECTION + + except Exception as e: + RNS.log(f"Could not connect to I2C device while starting BME280 telemetry plugin", RNS.LOG_ERROR) + RNS.log(f"The contained exception was: {e}", RNS.LOG_ERROR) + + super().start() + + def stop(self): + self.bus.close() + super().stop() + + def update_telemetry(self, telemeter): + if telemeter != None: + if self.sensor_connected: + try: + sample = self.bme280.sample(self.bus, self.address, self.calibration); ts = telemeter.sensors + telemeter.synthesize("temperature"); ts["temperature"].data = {"c": round(sample.temperature+self.tc,1)} + telemeter.synthesize("humidity"); ts["humidity"].data = {"percent_relative": round(sample.humidity,1)} + telemeter.synthesize("pressure"); ts["pressure"].data = {"mbar": round(sample.pressure,1)} + + except Exception as e: + RNS.log("An error occurred while updating BME280 sensor data", RNS.LOG_ERROR) + RNS.log(f"The contained exception was: {e}", RNS.LOG_ERROR) + +plugin_class = BME280Plugin \ No newline at end of file From 902e1c54511bfc9cd42b49182fd0e6aaa57aedb4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 14:28:33 +0100 Subject: [PATCH 052/271] Added ringtones --- sbapp/assets/audio/notifications/ringer.opus | Bin 0 -> 32047 bytes sbapp/assets/audio/notifications/soft1.opus | Bin 0 -> 102838 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 sbapp/assets/audio/notifications/ringer.opus create mode 100644 sbapp/assets/audio/notifications/soft1.opus diff --git a/sbapp/assets/audio/notifications/ringer.opus b/sbapp/assets/audio/notifications/ringer.opus new file mode 100644 index 0000000000000000000000000000000000000000..36d00947ab23d0954daf00787082e351ada7c40a GIT binary patch literal 32047 zcmagFV~{3K(Dpks_t>_%W81cE+qS)<9a}rtv2EM7Z5wC)&-=tVpH95pU%ET8Bcra) ztgiZ1mb|&SG7t#R{~ma^%E13!a^8id0Heq|xH?Oi8kztDa{%|~{*Q_Lf9C)1@t^sB z_A>`H_`rDonX4F@JH!1vv9UC=|G6b(q+_LH`p^FVycm%E-!%}>e=q*$lz1L{1NWQe z|NmSE__m({Vm#?qrf^7Xg<-;A&X3J*hZp$XZ%KUt4hv)zf`u~(hk`;$jt3#(-VKA^ zPy@W}T+=i4pES@*3=xbjr??nU;bM~?HnO5T{mZhau4Vhlor9(hYaUz3IOAjR5Hbz^ zJXY_$GEc%dXLKM`FYaFsS0Pu(n6d5L|_;sR0_aqiK}@(8$mQoEgHX(cJ;k&(YrG z377Mea%`>Hz%`m-ljRE6~gRQq&ugPYO6$1=@uP*8%V>@9vOsLpXC zObl5?rzqp@5d0c4ymaw@6)4(a$k{a&{nvH4*49e59<8d1>!cdnn9A^&@QS^>ja>$5HOpu%0 zi+TA2x~!w0$PH`(_r19k)`Qx8j|^ZI@Q}Pp>j1vZ*mcvw7Qz|s-+HABgMOU`;@a{8 zYU?cg<3&WI7Pxi8EnRR!(m2Z+n@<0(^I7b*mVZkf4{U9+mj+^E@@2KL>uC)`bIE=4 zz&@7JBy#JgS+fn#{l0l>Kp&UDQ4XHswWR-lLrBF}?^2$I1@w~YHm9!jD zHP)etX_2&{&8?%6LbgltC#n*P4trF4=>t9etJdqnYh(SH##`RUr~>mx8FGJb4OWBh ze1nCqc|`^$kC#?DSLzVST7QZ|oyRi;R?}(;e3UZ+i|RSReYl@sI2eFjqp_pM%*jdT zcR_XJjuS(G)O2yoF3!y(LK!LZGiu3|)JH0E23Uig*@`iiK!f?*|Yif4sWm+F$l_13luYw8xTV$RN; zO=S;2Y>9XPj6a(&HV~rZd@b?PXAC_AT*Jn!3O1+Zk+ zk-)pC>i5}AGL>m%yTWkA<-MrQPpve$9jA=V3ayeBRqcdVOWx^BW;pdXzYs-sFe^&m zQ<~8jUatrdKQlyfht$@^)JC(m2fTHMO@0YgNun zs}yytV{4jMG;Wn(cs)7?4ZJXz1q%dYR$2{rzO3QjlACm!3HhR0ezwxu-bTVjp{wgZiqgdf=w+3h#N`DQ(XM-` z6U7bs)jf@=U3hush%L_WeW9a*0e=ZxP<{K^B7O1irDgdbr=Fwxie^496xqF(JI><+ zB@5PYLqA0E(UCw=EB2J6EZ5g|NnpJ^mTAVxtPX}lEr60~2B$B1+}_;$7X4TrQ9o^5 zeTSe%&)A@T!h1qmgF;7-1mE*dK%`UjKZl0yZMMqvWfLyHq%do3#JEmw$j|nf$(Eb7 zgHx`7>g%>(Mk0%_^!)g`Li5(`s z7nEQnDYIwBehDiMpNNL&XD4Ffj^yjhe5w11iiw-g$?v-dkbDKC*&y3!206((Oe8x; z9W6teKx5vnt^7j9{8$c-V9Ah?DsfPNbP4V{>GsH6UhG-?!4R$4lOIyZ)5)* znEbWjUkxJrlSEpY1^+ri8!~BdgMxnbJ7FHh(e5+LT)y=TV0~a>I~qpeMl}tn47K4S zzdqhrKpKy*e%Fd`eA{Uquwqb)BJ@7A?wRUEerJDUwqP6pkz(w*sh_A#4AMYN!5>vR zGmxn6e_D*}Z#&@8l-R7frI*zMU4OzOx7FYMjnP#8DEc@&(qR(5+yVsqPf1oWGp19@ zhI@_dH-$rRMJvfBpCK;MF5D_^R(!)Or|4Uljn_ZMmA<%+myMZz&rTxrFtYyE=VB}l zRnvTkyZ)_X>`RsYQwoqniU@Lx?l9gqcKh4<#Eg%``n0<4%eqX+dX5{a`4FQGlFl>v z17{Y)uY#}3<~yYpX3r*npWo8GPPiib9snd~==8|8T#qhEM|CW&=X@kEXX=Rur+@b? zhjb)Mm05SKuN{t^$pXIzwX78Ga-WPGVMpu$^%|UN=10OskJC3i!+g@#mNDH;?^?I9 zn(6BR6&^-xrUT8^>4pg)OP-N$A*dITm4pr3(MI&w%c)x))>c5`_Nrx3U%vUpedYr( zKYF8qLj7}W03MgRF(`unQZnTSkrD5_w5#~=aOp{fUlM+3EAcbfRSc0oxnTnd=5z8T z&qth=_KBN6uo8$y#GRg-wL!H(N~6eMh~+)5J8e2dtR*~vq9SPm7^B1pi1f-PcQtD8 z82{uIoiPt*XB8Wxi5-yH@PBnc!RFARqMf!oHxyUQi1RDQr zq*wxeZ)BM}SvAJGsMhC^;HGrm%S_Ku2Mb_kolIGHMfHIj{%sdYe&j(ceS;urGQ zoG||mQW>+_`P=3WOvhT-`{4wK645Zt!AplcVq-AatNquW-)G9^z*u)8p$C#wq4{U@ z`!hBciPD}B%2#N%l%%%pZu)94g_L7?y&GVH24^baUxld>?38e8Fg>T=4qB|XM;@V6 zMv!epNs#n>G%>Sb`+Kp+l??n{bG&ovcnO#q`uB}R>x%6l+DsG$MV&!aIO7zmhS?!$ zG^VcMmJ74u7`RXT>kKskm;r647@~q_9n5;d^YPi_ssGbA<0|JZ>;p@{AR+yQTPq%f zoBPx_F{0*i`%)hntMsEhKbGfQaL{gFA@+3DSQ3JTtPy zz$x9w?fyn+H^mBX!g6Btm@?%ISU~py?P+TciXAkONKYIvsYXB#N@ssLF5|D=es=x& z3>jR+7OP?gMa@XcPreypC4up^$mg96DdTYB@T~HfTh^r;a;GYp1XjOhVa?8Fwh_V_9~KB$zJz>lW|X) zG^X=ck`%IPW1WiX%rvNV01+XQID1r7QmS+h5K77YmCg=n-aUZ=4{GSDhtl#C_#B)r zk0oX9i&IjLKPH6hR_if^|2o?9MbK?aF^r?_{OuK{6XU(_n{d)_aO@Iwy7YqtcU`oViB4RF>rFHp9`fk)Y?H=FqIE4&7Ww9Y`U9Yv+Q%ZGG20sl7GWXYc@v@ z#+~|YdaS!a{slQ;r>AnZJD>aEm1ZLgZwjy){C)-@zh<`f{`ljY0at??-ZD_h*wa)h zEUqAhu^Ci*BP;*bF4uq1u|PP}v7s|T?iv*bjzR1xP1xDam;SEUlH$zL@&gy$}BIT=OcDX?RSyW+Wt`idgq?`8a&beJ?cB~yc)hKv28;Nu* z{hw5P&t2gNxN*4BU&UxW4Z?8_IJN^QhHq^@$ zUGH@gGBjRTs0M-$R)wN@6h(D!;lQ*?L1UXfCG`Er)}B%`jIz?T6%H;R;J|0k*nBW{o$GN{Ku zav^yd%mS%k-V5MS|LM@$C(*+xI~7#FFH^D90w<>&-|qx#WkTT~RdIH>dCiUHz-KaE z0x`tUuUP-W_L>Mm<}GD_upz0zNZHNbX&qJW+W*LnEV3tDUD=R{UK690F2=bBfjX(q zvS9J?3+_c5a=m#Omrzo;&l~`CP!t(D2oB+;Hx!&W$irW`L@YeP45}nzpnCo_Qn3EM z5j>0OVSKDf^0IvLB{Swz8WO%!j~4T4R~9Rt7qi$NkC%vk*4#h6g?$bsCL&O)GYs@? z;FMoZkLjzqOF7nYBAykoAsXNx1gWAbZY9B3&c^^w`vDL?x#funyf8|#zKog{ot;A< zfaz*#XJkr9GHjm0+0}Iu#w`i&F{_cEPvtE7Uy{N7KfL3AfCS(NNXP~$?EhbYgmC{# z#eiiXa*&BU(wgWiVwpeLGQhViNfGpX6MInjJgBrRcNvgp4CiYwQKrKeXWSpK zFGcz3TezgZnep>6(N^HJ+Y{Aol@ylJtPc-!Hg}Ko!5_zkxUZU^EZ|Ces%qyfx;JUK zY4DVa=HCb!eZIj@A&>tM`29F)w)rY7<|E-2tlihdj4RAobLOosC0 zdmS=-TF~`)4?G5&=thc;U~f?g2^t|CwdNU)YNxLm>tn|>#(K?oZGo}*lqj+n{VqkI zH;Tg(;*!cXCK^R!VEi^Vi^wcTDjX$!3P)lP9WwFH7qz06Zkth^^Bh~tJvB_fia^*g z^IP(9zK9L_AVES(4^}}rP_54+(1MxkCy|9kE zpkgntl;C?zTNGde_S39A3J67w%T`x5<)Z{LPZ0}@j-n>0d%NVibb`Ir;{aYau2y3M zX+&Wl1-t}-oz(~);3c${5qv`mdI~QFV&dRPTx{XqCnvh2dogOU9uzZ=ym^T+axV>p ztC5O~O6A~l*;&T$v8Q!D0G_gP|9Z&VOR^omq9JEYxL98EVrDSxs;IRC5ZK+4?e2(( zT?67sD^N8zs2?9s6<46u6jDhkA~$k*qw2%Km;&kHMgKQ`sTIofRCv*D$99?4WzJyF zwvIic=?sMLIso_6A@#Fw0~MZXb$CrQr1;k#1wSljZ4B1(ueU!jFc{Ueg8Kc6Rj?aD zr7-vP?{HbIJ?xDdCj(fE{@=T%!$hb^nO?B+K(+zA$YD@0t40*+`yKgVS>Wx+cr)Vs zs9v($NqejNc)w(D`QhJo+GQa?L=LIR$;8QqW?5tv)NsAw&UUPVgYG2CBdbXK@6L%! z57`sOXP1(-X6;M7Kyg3))|{1gxjP*B8S}7YtZBgN)d&fiv=N8iA04C=*X*wMW;v-g zH?-GqWHi1V6E^a2UgmfC z_nec-bz=3O#h8Qq@S4A=@OA?nNrWVTTL z0N~#*o3|17@?)DFRjRHM35~w_btx62<`b1Dl(!zqz3#{JryZvBuEh zdZ00mLc#r^QvM7v30y+F7apA%U*$QWwyqXYi0u1QtFT=-fJT4maltwUFTIP&C#f6J zzKn;cXlaI)^1O+9F}nbo9Xjpm$3ZM&c&1Uwt=mf28Im7%vld8?rr||lb`8U5I*y@y zRpI5W{Q4lInSEj$ifLI48iHLLnMVlCE?72>Wb0l@=mpV!Ys`ApbD80n?$;X6^}7;A zijnhdUyK6wJ7hDP0r*g^ZnE+)*co=RFxcMz1-ZUc#iRq$TH!4dA~IR~()!VPwQ30I zjV?Bq-F>JHay&T0Mw@H1j5OPT8tHYT0@p>fU8EE4Uou}XT=Ss5COJXkv%n{)D;3Ix zXR3_--wc-~sphxCL zjtCtVhcG^5JaN7qPyfV^`e9_nl$!k3@0UMxCIu-PEe|^-(h%d|G#g!UfXq#^(MsLYk+m345c2qAx%`s&9XOqr7&6y&l` z%a-=<(C87~)J*tE`s%^s&g*`QR>5yIUEv3ln6|?t5^Mgozke0K8&RYC? zh>gtl1R*LN4s(Pg4(nh}G8`22swhO`<~PBbZ5QnqLEgV71S!(lildMp08Cp7WITUXe13Mgp5^v=Pl{YI)JUd zkSQ2qP_onOLhwFdKZ48BeJ;Ju#?4CW<|W%SWK4vAa`~uN&x&o^Yp-zO*iWP@Us75n|d>ZerAryT&ER? zg?jQHS$aN~1?!#$6D|prQ{yu8Hix}<%jvVxCEO+nEGKgz|4~Xv&ly|8Sbz8eCoq&= z$jQJ;ZHj7aqK(P!A}C{XF_7s?Vmx9f)*%Atct=A)y^(w!u&hqT+GP!cOnvRwff{zX zDNlPodFKZ!kNUMq{A=p`pX2e{7|CP-*fVu+Eu21M=fHat^9Kg(=sIO{@?bfB&Ds$1 z9RvQqPVy;w7z@0eA(mE*9i)yHX(`LlHI(JGvzOObVJSQk`0`I*VUF3I#L^6IrN4Ub zWZoQdLSR8=Lr`sF=-xoCBqpA!%+?Nkw6}9`bA@kV^eG`36xj(!L4iGl&NC01gVnz! zLn_^57hy^Ek5Ia)u*(p?#D#;!Wo8^Z-HBX8&Mo_*oF6BqsHgxFEKaIe!yU(xG}d$> zCv0!~(|o6sX?!vyFy9r+7`?Npb6S<<>W*o5*Os`Lu4Xt=bZb!tM++&Ad1XI9F%yuNxEYsQFo+D5`0Aw}7eG zQH_8E>p1Uo9+gh~oLVr^NEM|@m%d~0ZJf6yD-wuXAnjVXVA**O`|`KCxZqQyz(S=3 zI)`7Myg#y0ju+9$f-Ny!FKYZU2RB1w4?I0qbJ&|RBlKe`vv_f057&s?n;%2bT*F zq%ea1GiXL6=GWi0BJoSQx3?G^Xtre-|5h8qB6wb=B=Z(sgfC~ zk*a{5$YrYepT25CV~0>|4|vB3KI*waSkkJigvI~il#T8##~Ns0IEdU9wSEfrxc>~t z2cj1$#0BKye? z(^Yte%(KO&`L@~>*Pja+c24bMwJdp3s-baLB$2zt*PZPUYsM6K#l!@Jdo${UYjFM04|4v z-IZ82EU7#BTw$KCeWN@3yK!5i7Qjn8?{wb3%!`+~$8;@w-Mr9#=<~QuhAaegvy#8K zPmEhnW}Imi81rdt1Rx~h!h@5#=vS zP!^uE3z~GgxxbaBkWUE@!PxOKh973N>XpIzv_Tg=ouoUh5A&mAxE^>o(RB%gzifI=RS5q>oG7S4OCQZ=amt&mvx|9}MO50FT67ZCWr013Y5%<_rUD3zM) zCjc}aegNiw$gdlmLPxnhE_ps3=0<48ZNM4C2>aFf^Fng5AJgB*K zK7(jYXuK9*2fOIpix59Rm-E;?!jq2tULP~#zzG^|Y3K{dqY?NbkPUg1*Y7S?epA8M zo>NIW3qfpe+rF>>^8~2P=Q`=>+|Yp|{fo&&7)Dv}&s9(*(>q307Y2u{?*$ZJJJ2uF zlRNr*4XZ59-y!VqEvtIbnhE5=OdWQ8S!U*F@7jK&8>)UKxrFK zLkD}0#U$xXW3_cd1R)PX;{tD9ueZ>mQBp*E`bh}_yQ%idGIkNZsCR_Dx=cPVZtHw% zbtN5SLYynYNSr_BiT>3~s}|9pjHpv$QHi!|n2xak#5QM8Oq=&FJRvW?Un`8x;K`16 z=qAE5Gru*F&x16UiGIgroTva$)a;G6ZUm03u_gDxB0{^JMOcN;fQZ&crB9Y3%kPU+ zMe@6fzKhI+m*(4;I@ZDT!BV4cbZju}WOL?Ik-FoG1!i#2Jhw|g)Bmz`hiAJ?9gts% zH~U6oWzkz6rJ^c?)Sw42cDlpr0|Pp#&nDV zuHy`ag4c#|9MPBIt(aPU{hA?cfaRP~kjHCL_yZjickG4BuSbkfIEzUmTL=-pE^4PBq>(G>0L5I%Ff`b=o2U?nW^RfaOl$$`q?H=fhO8or3Hh1QQ z(i%yoKZ^zQnN&5L83fv{%VgOHNV5P&BKCab@_vj3Eh5W2CcbV_&N{3*?0z_vnRhkO z1#Xc8t}Gi&W@7WUDE!y7D7LediSLUmkS16bT~N!0U=JS=3Tyvqt!z)WrU7X(f>=qN5L**6ART3Q9a+o{Irn`sZ&L-X@&GGVPMKh=vZ z9wj(V`A}Tdma5@lI+I6$o-J5XF%Gn&bh{ne))!R$7!o`gfYRxXqKf>HD*pX3*HsG^ z4MDQBpNf7NV+^?2pW#JETvfI0R`q;e+lUOlnE~wAbCnI6gwE}fsZz8^D6b+9|_!3U}1{?p^8 zgJgNqHK!n$vM8E(tRwdPwaak*s;>A`eymFoauyQ&_2jZMUoMc&W6S}12xKyrru;Zn z&Dl62(Oq^sZ$3P4*iJ7vedNWh)YOtB`6Ja}2cFDT!Cy&u8!&nR{OpQBP@2{2*SfR) zp~jArLz5m~X_qb`R`?BsnIe@9&@e%wsojl1#7Lo%8S4U zd*9TXz5>4M_B9n$ZvA%g>x#k{yyOOsYh9K#D>>eYWQbRArq6KpOR_?@5)=oVd%9== zG!>m|Io0Vqk6eb=TfYv~1<;f)Ahp-{nt7!q6d&Iy5psF(I|8|;c)4f+h;(|9eIx}K zF{)Emvlh~o<}rHMk4?8C{@Pv?V>U{1R1(fYY?h(h?*zF~!A&vJI$tL`)z79LAyfPv zealko&=jLq%K!2}NV70HgZF%Gp4*eiAyIo{W!{*=hDD~>{{dp6XBS;XP=BG8UINI} zYmHWM6PN7#N`>-AD&aa)+0MPpPx@_(fik+p%I05+|FQ@HbO>l{=-3ko46vnmxx#;% zs$C?Pu7#*O5n`6mvWiV#Nm7r2UkwP=jjGFn{e3gM{=TnK+CAY)H!?-Lt5wEAB~g5E zD$i2B(xUR3-OxM^MFf{$pjnX-6!H{)>%{Y#Zb15SW+86QDW}6ux{UDSfIjtxIX$K) zQyNw@HdejTD|FCJN&`!CQvum8m(`~XL^-KKo7}s8h6>nA7WZ0X)ND zj^SIz4GkxkXh+CErqML{a3y^HQDN+Ga9?E#MIWD6wHmLXt2YLlH+xzwl5?Y-Va0?} z{8id)k|-}8PKd9eH1NBi5M=x5&D!Dgk-_aIQ|38=F=MBi@gXYnafb1IVjL3c68#U_ zVt1PMyK=?e%tt3fFe)wDZs@Ce5#~^ ziCQ#7B1>fjBn6)qVI`ULR*oL+u+sfpg=;IkrEXe?`awtfj%+0GGK%@mH*)GE=;OF~ z9Vd>y?q46yBU~U;nxBCP6T^_bFJbD!nr(u5Y#(vb3h;aY|z6N zs(FN&P}XE@n)+>kqkg4XM?#?R+>$T1?=5@?$N4|!&d}fy34kvqSz9v|MHtw`A;{gW zF)Sj9R@7U$yU|b}U($+aTE=gv!^WRf&V<)3u^;uI1B+JKuLios7)qr5;P)y2ITqjYKaP*_}&;ie0O7Lt2V1eix3m5 zM`9Zorp?N@Y8G`P+qDKAbe@V$(-x#iPWZ?9~z@~Ang5AvSvqLe=adxq&)9hs=_O=$rm_S{5f2TIh4!Gn2$J)G%0GeNMR(D zfD16?kj2%|Z?G?<+z`F2pLCP49IwI{}NY&eF@^>$aEB)5ch_J&)<=#`Zx z#0ZM>jJZ=gJLhlOW6=8uTP%*nx71&}Y~$Dnqh7EGG1cOV;`WIXg6}yUSv@p$Z#cMW zZ>MS@dR6RpRNPcZKh*4Q^Dr%yw)1M&Dpe8?fbNckg5JuxBBLi+PG_gi=5PzBc|b#} zG?#z46-YX#!s(%Jq859PU1!2B_f)GCzsXs#%9^mIk@&kG*o{XI7+y~SYzXZ2Gan~{ zY;$#(o=V%GkU%Iu;=!^w3ZJ~3VGZC>5ImY`v9O#grzZ0-YVbV6;@N*5z>$qrVwd?N zl>o(XY5j%3^>%D**Vky5j82*OCohS-^ z4xzLI-!^cZ`Ut_tmb$~;08HLu2|b_XAKzvH)+L|i98D=Y#RC3z;P&px_R07k7rz%O zZumro6z3+c1`^_;b`MxFvIw-oaq(hF8vHIsp0@YH!Ie+stVkb&i5 zH)B3ryWMF`+|6_cJdcPl9}$PVnwG!m_f|$g8#s(kOmB+z(^s9U(!7|wW;YAf8{|3Z zs1{&)ocLIFmnae(db29BfT?z`c2a;rR+Me$w8~W=9=Z4ia1wDZ7*fCBT~+s$=dk6) zt>l^jzK?KksWqpMQ}+O*{Vlp-K43G1Nt+?6@wt?u@e4p8ayBo}kHkSHf4)P%rp!Ck zyCVMVy@74p0|Q|q667rmwZ#@R>v_0}W_>^M!xL<%E+>xtH31&tLrSJRg!VZLAv2g^ z98?rSgUBtudB-()kK+=R^wz{V*9{H*$NE+$`JW5pyiDA#Lb~D5BWoR4McR$!C8fVC z&>_1|gu1oY{!4-7`%u5sKr0CM$WlxNb7}R<2qTDQi+|Cdj$^w|&&EG$e?Rp&3+44{ zszjZTwHI&qSEU|smU6rP0g{R$6O#OqN}s5xC%aaERd4v?fP?#sK3|;WP`@LyPh~J7 zTb7U5##Ku34=W_{+Iite+;6?0Kk8hb9vn6A*B!}j9p6sDUYqREw}zTZ|4Tm zpX_~3sJ99dYh9zwGy7$$e_Z3gT28bkxoXeY`%{408}3dQ=l(V;C~($`lCYDWEsO}q z*!s{*VSJkw6Xke@!9QAP2TeOzJy7q*T0`++9OY_j(~@8rL!?sXHr&5QxrVKniQm49keB7yN~|xFjZg-m zPCbofxXZucOEU6Nr%kS8&Vcw%aE?Bev9$Om~|8uP#>nVL`3oLe|F zkhzNry_p&3%KYC73Ag{VJLJDD8(=>`Vm>)!^Zx=Q7JzA+y>I>Ho*1o;=<(*G?olB6 z7RnWj8_Rt-@ZtSXph1ziVZ+%va6d&xaLTl$FD{Mk zpx4c2hI#w(BfWw@jCBaZQxHBZpKCS28oiZk6);cQS#AHWEcDN9nN^(jQM>?did)C2 z6qqF0Zm$}!XvQgSsEQ;vaMn3cUqetidWl5+qjc@hImoS6v zRn)^WXD&nSB`=0?qo`Bb{+G9EK05>GU*|K+Obm){&G`6isyR_G=7wn&)U{94Jl2m9 z+?n3D$r(LOxCy~ktn9i1SheUys!4C^j)2VH8ZO9^ET>|?@JXbweMG98&Wy)%c7TIB zsMF75*~&=QWnUrF_yy>=qv0P!HsSV*2X)pbm`%KcckHuqWkT$_VB!3qste-OByO2N zi*zGYk=4~F6UT3Gl8#v>Q2dW#2p=_x!-g6)U?Z#H01@cy@xWfY=dBnw46`+^K7Xvk zA@D$lbQQbN1ptgSN#RtHlCE>*_I@eWi8`KzlE0fjnuy1r8Z+Wr#aA(?#eQPk;d5^Jj>;5o zn85e=UnN8z;&NZh6hj{G#gq8p6A$jOCbY{dVz56v zNd2)$LAq|(5%eVl4I+pV=ffd$NGqiPa4y8Z*mzaBmDkbZ2<_f3HD-@L$?f77pq>Fq zw?}fxc1;8+47xHWVH7rztZ8d!bo2u6sg5X~-?kx?Jx8T@Z>OreinUxi_co2x#y8c1 zD^@wJZ26TwekN7zXjjHB7XQTEYBWsabY>a8#rRw7(0b=iEtyq%_;CJ{${96ZBBHt& z{g3m);?gN`yjYBu*HjS;zu6YP6G3t~qOgDNq!kJixXGpsq2^x({vL z<1hz84z2AMkk#inipFF>rHo{R6({{#64VD9HD4J#rd3$lT-7wPLG^7q0+5Bl128e{ z66t|^&E#ny<0RU-Q4AlZnxYf#ip;^*Q%%sD2S&?VjdaCY(dq(if)A|>b z*hxXDH{l+w6iXU$F9@FY z_qomXx2IIIde&@jlGmw!TWbG;2_Ve(;J4x#tlrKM!NmtWw;i-@WI*)}7HEV0gVH*K z{5T%AM9A1v4-)_wzyj)of$!UoAi|)a_&(E4&DIgTJM@S9@M~?$*UZ8B zl{iQN@2wK2CNe%%9Z6feigeFY2$4~~hMH`2xWj!RSuDctrMg`~gS|ugM|Puh&d_4ovYayN}g} z*!Zr7F||BmNnf|RWFabv96JWPaL0JZYvc!vCK~MVhTQ&3R=1}V24p#?!Rmjj7B_8U zj3cqXx1TUOT{GxZaRJIQRVVi|8^WaIZ8idQxX`DNa=9|!Y)o52_#~R3B`z_A z(pStb&$Ud4!Ul$z#i2sKCD;1CUqe)ArbFNf+mMxwdJcLMSOSS})~;y7H>SE8P0A*9 zN;6Ws4X<0*sjlc8Rt+Vg6I;vwo_WXi5zZ%qPGo*f%z4;=g*!NKWuEyH^`EOB zq97Dq>3za>753vyMj3rD)7NP6mWkLffx9_#Q0iW(1TwBJ^!BHW{J1dXnI^AbYqb2|GrRwY{f`zGvCTC#&2yJq$Fg zwH}!MA+_FdpIgiQGf~T6+#A$BVA0=t9qS=(U55Zz6A$P=ss6`F<0gb{YG%D$b~&K( zkp~f?s@_AM;w}|RMP2ta#e%(f0P$%RU@@utju1&Y0yTjd;rxYqSO_GtJtDU+JOQ0@x z(oB>Z9A@|%U{<%bcBY#{Xqu+@VlO01s62`N{c5UMDoLc?5;8R3zU0y9McjDt#{~`Z zH#*--mr&e4UrLc@Rny~~wuyj@FJ`#W1^D%{F&1yjnv;GNx+xz7z}*$=Xmb5B9wg^7`Wmu6OSGQQ84d>q02OZCU_KoYI?bUOPQLE(LILJ_Gep5%cg<$lzEJ=C`t?i97$of?(NG5 z1oGV$io-)>LbOQKt+c}=pW;%iXoje&_dW9V@$%gfq0b>RpsR@;bPp+F)qJ?!I`u1g z!L67ggv6g%kv#qYv4Hay8gn@jIblUDf%_!zv@!U#)$I|TGSTn1KsOD;thlwV1vG}s zK15|BRUab`yGi{M0K5D(D02gz%*yEMK9gffb@%%d{Ssn)OzKk^)Z;#5d)p)ukBwc6 z^vd0l?q^)}KTcpM%*{$EQhTe=pGg|8=y-4JE}4j<2m?|F2In~bJO`Jz)5zOVXk1Iv zuF%NAOY}6XzTK0N$cysI%VK%3`AmifLXBoj!Eea3hF_mWA+gy^mY15#C`Sz1G#LKZ zjv+j=I^H!l1qaOzHnL(esuo4@%>%19WMj`n4>&DY?^E}75{T7f1YH#S&qPNl7IMfP6h6a=larx~MbQG@2CF_)?aupYDL1-Jt#Kvpkf25jfjeoxDe0g#4 zhM(PIj|E~520FHhxoDl))j{EKt6+JWNLGidff!j`Ig#87b?N}h6=rNnkyniN$zxCs z_Rc4(1AW-3Ijd_^x)huk!s8z~8+)5fuAh5g;|Uw%-s&-1&75k_bT+&DH**G3#Bm&i z54Vhrtr)S6&~&FF3sXvCVao40^hWUhYb+GM*Sh0NcAk*?u_c!Qy6GvH&f7)YJi7&I z6aiWtxn~_GRH0GV?y}>R-5i}^_wq-VYbHlWB!y3}ae3EZz zqLffOG8bx7eHMp-G}d~GkkcDpZW0>4u8Etuwd(c;#o*@p~^R7{j^BiShgAJlL>w|D+X)oLbbu7N8~L>d}+zpHm4fD#Vv0BASn z=H>*w&XtvR+sNlKy5n6rBZ)y%>c4$<@>ZtMbvAD27JpAN8=%IZC3;#r!90Ymv9Cd_ z$~`mSN8=mhDOvU4Dn_!KUOZSwlE9N|HS>pCt`bz^5yyDVr{sEp5Fcxs)rfjAaXHFB z3Ev(jw3Tgg9VJ{{pxP13R;b{T#Pd6o*k zG)6==%5^w)q8aa0M4FKrqzIyK7bkuhm&sg5lkeiu@*0wLG>O{sJ+|)Dk8=kc zjyV3hA77Y=)IkSR(UUTt>$2hInY!DaQ*qJZpJ&=31X330<#OZh=z8QsF?r6)W~}yX z%p8EdIp~!R>HJB+!QyX|o$)I#hSp3Xd<1mCc2nY54eRKSzc9oe-n5lu^&>^mu0aeaH`vNzN`~!B^JV4Rp0!QYX=F{QGn>21S7CZ8kE=Om=M-%+H zPp4tN@dpSP z*|%Eplmha4oYwzOVdoTFS-`CA*yhBZ*vZ89#Gcr;?TKyMb~3STbH}!w$-n1(U)8Dq z>Rj#1uHCEN#tU%9dAj*O50c^VGn z9*4F9wrg$xA$TKeXH4Ng1Rn6!9M}^2X*m0NK`Y_RJgUT{mZRHa$D&*+&ez|-!YcA% zUqm)Zb!PcBSMXldBq&@Le&bB*#IQbl4TxA)XG15O&(@I$(28n=0HUu?-K%`kQ3O!NxG$*1rvG9HM>)6&FOHck)O^YUaR)wD8@C!|26(6Uc;Pv zTM7;W5|X7#&gU-<)i6T)Vegw+(lpkqUM{5$q@rRyH?;ih#AN{G<<>Nz%%n(S&H#&& z8O)18VK|@d^lYH7qeVm>ZU8jlDpfYFKZLo{fod@iWEJ)fM>|K(?0h4TrZf7=geM;& zsFJn88pigyVvHdl1n);&>y&4eRHfn!Fu$bcFM*dcQEF}e3tKgZ)G+Hu-Vf4%#yPDh z-X7O)#EK)aVQ1WrZG>Q_hz(b8Qbs6>c8#+E{>ej8A-#h8@KS7>hovX{^0qT6pN(H1 zl;Fd7(f$fyxZ&8dsfZCQ(qpJ&BZ6r7d@~L z-b}T}kn|DUR!OEPJW{>AlrRQ6DPT<(3BrwU4GXB-Q3~HkL?{#!LmcH?X9MfLhmam} zTdKE=%XjQUnx_$i1RFm1LafzS%ir4C;q=i8h5 z=c#w9Zx4IF9FjQiCh0><^P9^w`^X@ovr42!$#(axqva6H#_D5hg%MR9Db7M|gr{I{ zYsn5+p>4pfM5vCVQM#H1F64ul;CH|Kw3)7Tf+mfJIkq41C{ejNZwLIijbKBKFvm#3 zYqn#4Y|F1cto;;#M_RO}h2MM({AVJvjGhzmvl$E6`yXu_`HM4{2p!@6J{RALMnEFZ zSc&4Ps4jQ+tV*p5J*n>#jSp5gfF0z9!{fMascq1y8V>5Nl>b7}8dl|L8c2sTi@QZd zhl@iM%i=cEt#j>h{zC(-T!BV%AJj$+W!SGv)0DMZ05?K{gF+B8=4Kb1u3q??niM>=;JmHk&GG4f_lKRmT1cy8Ri3JM_ zY+bFjLYgE^N}R*^BjJqhYO`k5^xT7?PyE${83s#@=3reB=ihq>gUKfFZWGF2lv#Jz zJvkty?)XpRi5HKKcZ`TI_)|d%XvY?^%%{C!qlYs9<_ZCyjB3H3X_4fx-lo?+_NN7z z*}&BoMN(YWhLNi&QI9w~?Y@l9_dCMh7v5L3Bd(9##6G^1KW}*&3E1IuYL?E3rMCXD zoBuqIlFYe20ZR}BY_EW;O;=f?ypi*e>UmE;3xM|;vRrC2$R0uuW(yoTvkSK^M` zB89qF(6*6IfOVQyKu_uZn@z3{+8{<=uV`*hWC&rif?8yQ17>ht5|L%|Wjt#W^r?sA z=%f?a3WEnZYMSSoJ>pesthwq)F;VEb&ocg6BGydz`M=7533f|lLZ)N5fvo%x&KJ9gcCxrJE8nf+?nqP<*ILX6;DO8iK^$OBnJ>f#X zvMtL7+HSJ*>$+q2C?q-9adfqWZWp1>dbtrCRZ(s*17p=FMfr5g0Vp@7^g@l^4Y!Do z{9r0nF*GeJ+e2;*u%SrUXW5H)4}!B=E9S!cEmJAf#7B69m)0FI<_{aR z5iK7R29)uMx2JN&;GzU<)JWXSTl_r?DK&*0hw|Z(hX}m@kKGj4hxuY7gW(z&t34NZ z->L{kOH{--Q*o#FF-edS%fkvhp&@h$0N}aMPmNbR4rNALr^f)xQw%dKHIgMKf8t z!`4iC$qyxI^XY#A^Xw{hsI~*sJtD!yi~-VM_^a;ITa zXgN7K^2bA9zpW{z^ZhxFI619@+KeExABt}9o7(SWi0r|pS9Kj9>-3{5y;t*~qu z1ZOU1BTqe;U6$^&iB|c=s(AS&$z$Y0?!mUj&Wl`k7C?67!%Ci6gAFyN@!(%t)b4e! zUrdgE8&PLnCLRy)ARVXftyGVxs+6awTROs6+6rVeYxQfT$9m?Y`zh8*-+whNowgU` zy@rJ`iDclwmc?aC81A*^EDycGShO6gnG&A@EMqW!$|>$1dQ+eXESib=G+4>giR$K7 zf>C6r0K+=KMWvYD(3SI&?S;1gHA4GC6JnTyfIjN{{U}rJ!Pw`66Eh;WDvtCDGd)mC z55_ZA!fpiC2Ss@|xue zTKwoYjX~n00Tl@!+jsMIr*)7Bk=aaGDfh!S@2T{a%~>^Go;5Qf7*bBnA^+VnVL&O& z8j%|7T~;D9!R;vxw`-M^g1{wo9>iqFQToS^)4L~u*Q05}@EUs1zTUvpCv5KeI z1jg(7dMgAF|ZcwH9}O?x?J5Ae^e^RR`D-Z5&nwYPylVa zW)f`P*JOXV#i*$yU+tQ`R@+in4Pz)@7`c_BeH8-EqG@IAd37$pf326_(M`}i(Cp~w z|D{Untqk0S-T(dpzSLiM>ic=SA_?=uakJntzdMsMQ$stEx(q@SV zMn2W?z;OMXpkecI5__3j`|>K$J{W3;1cue!ZEpUl4gk}3e!|(CVM_A_y(HI5edG?3 zK&DIxq$S4Y?7;ki_I8>R=^q=o?UBb}-S-6mO((U!0svfSsm|~VnZ>Bm=P8YZZe~#KJ-R7k%R2W5C`#t1<)ZU5F~G$vQQ6nJ ztd>zM$;Nmk5kCK!7bp645Dy!cqo0qhCflVUjvKQV$L8-)kCj#XhvMK@)iQE|*C#kF ziMAxtQ5;W}jd?1hE8tUZH%0pP&NK7-1@?l|xjeEK16;*JNx$?J(eat51AY+(!yQ7^q>_UsH z$50t4q1Jch%Hn@#HtPbmjt#xG@D>VJs*LhT4~J|L)r+w|+&pWGasx;&GFt2w15+Os zt4tz1OqisGUPqa!zJw4r~ceiU{q&XCr^ zum#pt+0H)QgraS%7Tq{20ZnAsgCigDd}YUkL{igUj22ZdP}%`n$mq^K5qQSmtVCCoc8AHaaeH z3hTBMF}WIzbxr}o?R`wW1))RCp9LdjJULOz3j7|T;=1;Q3U8I`ldBG} zJSaB~_mI{AaNic`{<#yGET={8q?_P_#R6ji&xR{Acw>FX%}9_^JyKkv{jD;=%2R0UpDK@dAGA_v>E)&{053k zbj|*pSzP2|KNlbpZzSJ$6d6UfZ%CeeI<{H~EK-}SOWZOjMsxw*-|XKV*7)!B3gar4 zng(6(|AbjkCyDLz?_T`n&pIOyV`UT9=g_;l=l(*Ykof4rU=Y%oI0Y`a&%sIg9yQ8R zRm#+Rh)9_{#>)`gXoKroO=>5Q|7<{LFJm2OMHL0dif@<=eY@FWrb0p@M$ny^_k|*o zFvNgZ=i?JN{iUX8O#N<8?zQmP{|tG^>VRGX%|1{!KEQ#qIj;{PxFFDm9peRa9RoL} z^1Wc}1W;9-81V1}MPk(Uo|n|!f zepk`UjO6a*3MwYE=vSV#6R4A)j0Q%EGixq-ishr_mcsB>_`8p-sK?$JhCVebql*G= zl*GQ&c=9*ae5Uf5XiJRRFjlr%3MW~yF%3Nhw^KdKJil{tSaLN*t&+OXtD|2%syast zNqX$o3Xb%fXRpW6w6ul^O~;2{pSmreZa| ziEfov=%b0^)l${$vosg*iUmyVu1QM|plmFL*1i<~-d_|5^nqZX5-Z{F3^B3dxye7{-b=UK!BS83aYZYjVu@V9axKIlKEwabLgGp^iSZURix z=gUtp(;q>C=R1Ehqn4zLoiuAhS?U4+PJKA&271CPC|f4>RJm@moO%ISBiPVm5r*o| zAJmqa%mksmQ!5YXF&w7c+1`|N&!zFrUysLiM8*&ZqXIc}^>ZOml`sbyv3=bh4Bgf% z8%Me2(^=<1_Pe_^wk<70U#4)E$-aVJW zG4r`fthqQSO|jS2tK&Y*1v{L?LPMLTSn0~a4GxrWXH++6+E5-jhZ$St*Kdaz;@r;4 z>p`r_o;KI<|20wW){m;~b*7XwklgtZSSP5(f2*Chq^#lUvB6M=Ckl9dZg^4R?|250 zbE)~gr0+st(H&`oQs=3mQ(uIJH7q7QY{_{qHVo^VSw{UWMF7A~z)f%|fnItoY&7IJehs#0L<1LZv#{v^xp{Ge7J7tHF|~L<38AyTmrE^&Q0U9ct@CgrF3-8%Y9-R=31ju z!Q=D7wDGI2FL0U8ko+?<1Uo=i#Rpx|d=I5UH?6A(kehV-j(o1n%CSABEyJ1bPlfSq zYK>~{6L_x}H0!dfgZQeU-R=+nnhgGmz%_^w?k>kA-1(7pOYjc!m>L6ck%@7h|K>F% zZeY5rnFw?!&&fnD8KSGg$H#&5oF?<)q%^@7V!wWg;)gVuH}w7SdW1pVDr-5 zWR{wcpdG-1T6}X8R7u9a^Z3X(Z}{{XM_Y*jR<1IREhvbAm|BjLBA>?8WBIq!CA~u7 zU^|EfP(ccBcxFj3gx7zz2uCBa4OJknk|H}hWUIS2aprTNSU&2EI^|>F{?=YDS}a17 zlBO>k_1!kj_7};xmgAs_e~+eP={)-9DqstIBsq(Iomr0*tiZkBO)9a6oNUC^ZCFK-Ri~}mR&ZLDb&v-UB$h+W>I$fh z?(h!@%YuuUR(35($Rb)R(_uiv0Dgu7kqR6^A><-d$vq@1YWFbGYjPm*eV~FJHWKr& zX8p7%<%?b_^zz_UJ2q9)rD*q$ZZ}XYi}X@-19X?2Fro7=FH68H7ve+!j2%S!0*-6F zWeQn(Cc}a!$%C+{Moh!h%cwhh@+aEKI)TrOrP_mNr*!q+_=o>Th3$j$D66+PCn)cP z4jxpSZa(n^`Rmxks>VkS>w?y!F^ruLUQW-XwRh4cZDA!6esxSII7&t?l} zJh$g!-ZgPz*4_vR=Yv3(fq=BW3+y>FC-2c;BBEuuVy&sv3g|Zi4$G=8Z=`#_nNBl!=JrCioNZk>UR>|*ZIAu{TXT>gJu_CK)V z%p#J!p`0=HeLJI5$`bTw7P<1(o$-Pqy2XIiuDLKXeew!<7TNwUKs*@s+%<}yFMs>64$dY?s;uRz;fDEn+$hfglEom1DNT7690(U>0fc**8ushyNbIGOMY(=IzjpgVs0N_>lo~ZOg&!2l&awcZw zI(Tbx#U`V{-5s^`EWk`f{>4r9sj!Ju{>axuZEK;hJ5+aI`E_!OM6djbSntaR1nL*( z1gd(|Uyyv3e$hkCDijBqg)Ig?W2hx-X!GTlLOKJ&aY3)Tn?xCirE5;RSu0?n;3Lt#!#TuE@FN>{&Tz|;#c@* zB>Fk}{;OFhRF1@)K0gT>Ga`q5ZL#qo{Y06toy8|H&Om_C5XAMG2TbN#dunN#5ncYo zP+jKmYl2&0tlrn>@Oa@*(Vv1mpvI?OT%5sA#_2!A;Ya!&b7Q0)OdzEM{2FZv>o-bS z7r+Pbj$etk=r}i#hPe-snft`BSt~GV70339J#2PrOTAsFRW#336Vayra{BBbn^d9g zGNrVHXAlng{tn?Urz!=mbAvaG6XFrmsoP)7t(>zL33mVdiM2+k$%OH_@jl?4SX3KD zR`vP0faZlk312W8v&xvBYR&q7eH8deJfq4#1+mVnM}uPlk37BE@ExHmHlGC(e439rt`q*#b;_fav~iR(B9an%TRs;VyyMY~iqgwlL@B zl1t=oTt#^K+{2lrujr~!AZQ*~F9-<6Cw%U)M!hVVQD{v7LHQ_$J@2KD-@`QHnPrYF z^5oZ_M}~O0hH>$&WiZ6gEw77kN8xbD<`bc5%4&0>^&f@G8$tB5Gh0)}*3FR-uL?}{ zI*D>%db)A3-6hOif2dexGtyV`Ku$b)ucZGBh?WFt`SLZ0fLqaaz7NWelShFgfC~!& z-hAYMt^z&}orXX%_wUsyU`hs&9x*|cABwLb6Gd1$u+|5?JyB1}2_pupb7D)?pa!S;l6+NL2eDd?y;&oF#*@rBf#wU9mEM$QD&^a0^T;NL{{R3yh=sg~ zw_oHQhgI#h*aXR+LJ)ae@n73E`j+2P1t0TOka-46atJ@-`;rFGMK*M@6rF66!P-W z0Y|nXz*iWcYWToYj1sWH$K-Y(NBr7d8R6l^^P6q0Q#fRjiyGal!1yuG-Yv_NK%+12 zc+Q~A3)|O{z3p&npV=&b&k@g_ysMtM_wUbcNthXyu_U&Mn&iBX}AW?Bn9%IBncvGo-G zn@>U%oVFc4(FX=)Q2`#F>+#qSNBJwkKLO6&uNrvjV?&<{VEcV)mGo4(^-d1FQi-f& zAN}-65GaQD0PoV#=}7p&*fmj^PCBw4f>k6M^b`srTqD#5fj6AAT{jd_L@HuxIjVc5 zOP4&v;92-{$XE=gVKlwHG#s%f2H;hE~9>(OD`n zPd@l1)}Qg{wu

tX2}vfq>#3uAj8A$z~&xu>KvKd#2no;}s#6KP0GpPzIj8g?>EM zfcN5A?&f5B9`-A0g0Qfmk(F2G@^i=rA?^4qM{f4oh!oPZsI(QY?0uz_j(h`+j#G^! z)uAk8T3t4E+Xw4#^b;oAK31y&xp1q!qQp`Et#be6{$d?=UgtRDfv>UbGAfK$O>ABC zl#}g^@ZH`IndeszdJH4CR4&i-)~9w}NNOCWM+BrTkpr*aLLH@KtVE(|o-M>LPz|B$ z%-aN(3xAjT(dn7K{yBtaZ>)c~dC`>6-F}Qz0%V`+1>LsV+ zYgFoBkyG^VV)6Vt&(%fzmpFjvDt$)J;$d?)?D``79Hxy790UlO zP$~6lWVZ;JhG(~S4=J2X zY~j?7VzDjlak8gS9(9eg^78uJvVKetR9AqU`|lNZ05j5EB9~JnQzztIjoGK-vg2;n zH7as~E4!=Y8roD0SQ0K87vvs;rqxZ()ym5B6x>3bKCwp3eNyG$>!(@F0CUW70d+B=Z9fEI0%p)K+9D)ITmdBMo)en z17sd-c5snZ>XDp6F)Cpo(YQA>QQ7{}s^Zr+{{7|fod*|**3Rpk&N^_d_1B2K(cVmy zRv@5UqcgL%DPxZhP%*^9RLzTL5!p1ZOKL~Y!OpwCRc|@Tr7cVe&#N66Wq>3fh*f3_ z5k>rxkVYirUua5Mo{6M_#WwiiR^8&-=Ei7}1s8cjgIOx60<8ja^fr`zIwVCs$?=mc zpqy)QT-D9j5Wf)GWGb)uX4W}%sCa-o4Mp#8Y2hc+-I#q%c~E&R|FVHIw3?nS@i2Sg}9uwwOBaj|vqT3Y1;YfN`~ zFeEO#!5B((I1b*Jdnd1>o(-O*4fIO37rl>oi5n(DHi^!q5Ge)4k|Q!KFFpX%c5U_h zIML;ToOTsa7cCKIgcPD7o(-a+NT(Yc-)uMQnEo&TV2#j}>}Wf4=^^;?Q}Lt`e6rd* ze{SirZ=4V<+>g|uE4zf)!7Txi;hO3TW9^nhvVFQ|&120lEVWzsVz|V6O;t=o=bCcp zt0vps&4DZnO1C$$<2n{?kv{Ud;>CMa|6k$+7BV`+cpt*`?jNDmYfQmkogC;C6Nf2I z(_0#E$JV1Y`fSiIRtw(VN?K(}Um&H4T|UTknRL~BmICqJ% zrJ^(qIg)F#hNRT?VX^gafOC2!E`T>LD)C@Pr_#iNq#(%}+_orKMPjYvC> zFE>o>6$i4L3EsP(<((KbIBT#n=`+)+To<&7WYG7Xp0FzuUwg%T*o9mzh(|f+oOI_+ z81&8A1UF%7Oj1|UYNl3|v>pNcQmaqxm1OAwJ40-%mOfxZgCCm`9Y!}MoIl54$!C`H zw}H92)mVOSd>H5Fb@?AB-aZ1ue5H*G=gBGR`9^0!3p2GC1*TUzcSw@IN~YWfzmK2# zC>mqibDd0o?(_Rq%lEe#B1dC#5Gv~HI)6=c7^g=!GjyxB5YP=M93lsp9yS}*{1c!z zmTLNa@HzwGc|<1ZTiWRP(1)yEts1A|{A=PMR!IM==|vHh>WJ3xHXA*ELhhZkZ(&^> zfgmVG&lH-0Rn#U&?u`vmH7Qw0hqe?es_kS4KL>Zs>z6)xhCH;eK$s1W1bFYmvF$z#NAekZSztt+kid@TA6 zjnIkCExNd5zo|%QYvzQ)^2QOJ9G@)gfv!qnI!N&vrr7RnT2c*Y0u9_%5+lM-MlXao zq^i`S@6<_jOGBT|iwyW}R|s&Io@iTA8_xX_$2yB~BPq8*F;$tyvS|>ZDMmHYT*8$71ttZAj&1O(Lq_yR0PDN7r5$VzWTsHICmc8zkOA^u z(83tMZpiud1LeF?9=m`xerk(+&w#xcJ`)7@fPnRfpyC%Pi&fNKyWs&WQ{QAXWAAW9 zeIi;2+Gn};3`swg)mo#+P&uHhCWOo_xrcs@l_Azs+Nu0nnG=qK$g1JYyHNBsktf1K z5zmE+{@nVtA&51@DVE~UkszmU!Pw8Kl#5W{hN|UT_w#MP^X$W5iwh}!+EAAQM}l+m z$~jipz@0?-KpJb7CqORSWiqa?AlGv)L57$df?OS1B{_vcxP- z>-$b8nuiD)|dZDGpAxsd>Jgh0cf~o0s4r>sMZB6-*Z}N-zia0mimkC+n>x z%FDNKRoewyJC`>4%!s<4$v59;h(3^JFQr%=`=pjv6l_eNQv zf)Au15HrS>c2G%3wa|elMEi@T>95Vv=5yyu5=vvat;8z%j*`U5mzdSp+(Gys6Jh5L zGiBUGyIM^1wm8>2yMPSBrk@$Ab1TqQJC?mLMA(;ZB6Yip@oN*{@VYG`JH^gT+EjVz zXeQA|3{DPBI=z|%Ra>?x{bOCJ4Xi|b7e_-W6V+fyL)zd7HvdyB*h0Zr!Ly;N=v`bq zo;XpvB%3=7hIqe;6=EF*DfI-Sz6@+uKyx^m_a#gcqnQ>i9>ZCM z?;qD9`On}wqnuIyeh*`;$^Nm9YpXg?yjXU9!K|=z3}rgYyeFPkNk0X4phqKqr?T7_ zO2?A^q}+?bsbN5W1b1c?O6+HsV52o|zO>Iq7Sk~QqaCss0l zk7&gyXx(NgDn^5{kn)sy8!;?06?Ohe zXiYagr&to}h^>HA(;1pl4R89fR*vCB81Q}4?i9klSL!_8Z8acxzygW_y1>2{cQaPsxtrugz;d8(6@z^>{9K}_*;g7mu+zYT)wowzDWY~~czi`h0gSq8e_c&RbD4JeG%LCE(AF)%Gn zVbe$N;iMs5Q$SZ`dl3J=);hM=)k*K8TtS|`#uccmfs}HvqD}fWWY3~erZi}`ojJs> z5`CC+L9{;xN>Q8k2=WfNqs`LPz)9UCiJX+T_8a6AF*7CjE}kGznk8S_Bf^U;Elr-_ zM8h=u`&66tKzOlv~n2SYpo3)qH0z@D9A)0oBVO;xLisJx=#FZMBZ zOB?sswgm>YyhZX z{&g5N`Z$Dk`h+~ISd<;<%s4ml2%5%&U@wT|QD2|LpK+Givm_1r)cW}Z0O-u~h3`^9 zg!1sv_Q$1+Jx6MYNUh}D%w$I%#T=1Rz3n#t6hqWtfZTwl;uos4jaGlk4kRq%w#CL- z25-Y&zCQZ3B`)BZ-uq&|zwCxJ*_0Q9x1GMmIG(xB69@Y=<;wtQXzb@emvzfys1Oy& zdMc9TPSlnoUzv_ire?>eGHVI$INsFw3Sd%&?&$ejj}B*Mj6hp(#s^{;X-oE?wGX%t z0RP(UcoF7%rC8%fc!(~7q8=011gF7y@@-ZoV6eQ#`T8fo#sOL~POQsq6}-5$l|FKq z_4O|HSxyoRffq>9Y7dOsrKXdkmRP0I`B|UJIx^CSk6T(Sj8H$Y%Ma~{i*47Z!IGlh zC9#^)_lrhc!U#LRlz4A$_9=|RPmu|fZSg|_AUtjKhFTChJ->>hnGFR`kfxnM;+d(| z>wYZ-;qhJ7@Hz0%Wx3Zs_s#g~wN2HYKjp98FZOZw;v-l-o$k2PaY~!;fr3dmMd=v- zjXHl(e+$VVq7JH;(s_-zH_zA-(M&`i(-1%HqxK+Q0H7X;9+Iy|`^B~*@owGi9N0Qf z>=%DNCB*{)L7RWse`wAO+B`uqgJE{fkK{(~II19y1BSS5>U#S{;DpkA>vyitIc=TY zwKNVN6c{dS#U0`<7dDuESB3LWfV$#BH}*UMCB9ZyLM2*!d95+b^MGV&Fs>!em1Mgn zOW$Shsbx>jI9Pi@h=EU=Op^3oqBti51^sFz_P&Jd+|OZn&U-pW)j)i8aTXR&5MJ#$ zB-bHNcH-JNx*ul0-!O9inb=giu@l+e33WC#DNFLa!;u6%u}HJtj|6o@U{30(`c1O` zP>p#8IOv%SV49~7O)q@5Bv_vYgUF}xMcC|LV0C1 z_x#KY!tg_6PPQ%df^LoZA~!&|qvrdvYsjVpXdep>H`+NM;is%7vTkyxfV}`Gt*t+K ziJEgWUVQ~+FxPiT zG(yWSTkl2sq(1)s+Bqt^vK3Lc=Ck{aB1}8`w-ldD-%dp@9SBI9IIo@mwW?7wA9#?E z6WUWrvmH%`+t+3BbGqH%3_>(@a$j%Vh5;7Oym5VF>1Gop4rblx;}MTpY_#}qcu2ZJ ztAg<5%dC0+KDQCQ%7|4Be}ApZo4#*I-zY)m?`aq0nT4pVD@M}X6k^iY?$FY)u+Gus z%WqQYnbygU1XA5LG?ruL*4zUzPyPsH7C`~bl*+t28_sl^1J$QaRIjIQY;J1Qe1NwP zNM=5_Qx17Ogp4?<&D`1vV(X@&#W=B$h_JlAR5HK4{YHW8N^UQQX!dxBg;bGHG=ypfV^H%H;8dXf0Y-5e1leW z4xe28qmpms^$#g_ah^s#zb^BkycFdJW?uLNIQ?v6Z$;ThYb|?`G$RBA=prU=q!cLU zMoNK1Y+P>K*@a%S<=r3AfKG7J!`-A!z3YTN+2AhNimbQDDr5Sg^ewnj$ILt<93mxT@@eAhcAu<{B|u*s|(Oo zz?b9^F6Ek{U{Lphf+)lEXxuV}hThFXLht?M+us!JnR2J6JLeLuW?8_ApU_D|sSL1L z438}_P>T-=#!eOjw|ZLWRPX7B=Os) z19mEwH)M!FP_cNtW}8@tXF7K2APHi-#}Rx70XKJu?-lCcGdq`l z^K#4y-wySWb383U)A5Awrd&$ce57T;J<&OCZmON3^lXxHV^a^&6CkH}xHhx9c z&9?<9N6GlDvJS-wcndDaqXYs0hGhBTARV@j)s%DE{4<8w5PnMWtSeO%nj;qHxFC@( ziDpM*-SrZx3 z`AclH*}2l34}^jnI@<&2h8ogXzf`JMZw{n$vR%=(%kShF5}h1cYUjwSnv(UTDp>RCxpegc6l zr8ap2Je!QJo+X!=JdE9|3l;U^F*Siz@xStE?(?U0TG!KbS*BXp1^v zdgr-LUSi^-aS}(cW-sUSkOm{{9pvacIjU0@`l0vh` zXHn^+i<3%C@9Y~p;1{e$Vj89iAs_c$gJkUNkuKE84Idc-b^FhCPgzF=0xE?7#QtRD zn1V6O(NxAyfT(p}9$1-s%48&B|Jy=G%?F3YL*&RC*^y;-(&S~tdfiQ`=mP;J1HTsF zf|OpNw)vykc$O8A*Hq)t&iTts?xiGip#@4r=Qer1z{2rV{d!WMV-tO<$3LrAJ|9k( zAg?JE*1Rxm9jk$jRy6>jI0pU;5D;pAYsR>xffO9eaCh8kdLR5>ev4Vv4GSHk0nH|d znv&@iDgR0^&mf_X97IVeLeF8WrY(hFx?xq-@g5#d{u6F0@8kEysp|^E_Zl;pS zQrEGld3NFael4g$S!yl2?hFObb+Wk}CZ#5_OQ!7Z<6`F!xg(}#K2qaVMz|Fw%g z!JFshi5^H3syJW%(AV2(-4O;yE?dwedq#^Wk)3iTby-yjOqhrXtg9G`9~W!DWpmyV zqDVYv^IE8a56$tCuRp84Y_PL%BIn`>fYJ367Q(sD+ zn&Fu2yu8C>Ex_s1o!abfr+P3WaAer3@Z8ohEa8?52}g9vVceoNpjEVdSI_UE`F;<) zAah!Exlbnk^N;Beigc8M3_r!dHgsNdnWT=edFI#M=GYf}y=Yg=KNG)POS9*AKX{$O zI8J*Y$KGD`I3sbMjeUF?QtX4?kGwhLYLFMI;iKA$C$V76Re3xwh&n#3JM9CFbVQV6=KJ`Y2N^1Fn(D2f>(r%iWnB`6_*Qelw8I zlZ!~4uGJ;QSfE(X{1mZ+>T(wJ8$cEQbZ#k(>20i7kc4V4cIb2?w{iuIS@j7=kDbEF zOaWlOQ>#q>AZum#eF}eNQLPuTk%{A}JM0MG`{U3xH?{ubTN&(mBp6{jo+E;lWc6;=Ek;ddt>|gcHj5^ec!25=k!d~^i17d zQ&at$d#=8^N72$!6#xqOpHidrQ|n(f#sG;I1WnP&-BsG$*bD@e8zivfKOu_$!vDYW zFC66WSxu(&BnZL3a5ZB~SA@S;?5s^3|DF=FFmf=m{)_)_!$7Bh^}h}NHvD%}iwuq; zOz6J_2%P)hcQD}Bf42YYG2nf5cMfMHujFdTO*qX&106R%pAMc9-H80T4Cx>lXZo_% zp51;ja-p9~Tl8jr(fLbgz|KCD5b|TO@|VCwbfz#qM=t*#D0okwNOd46QA|Aa^$fB@ z)Zw@jSlQ^Pes3inD`}bY$2<=9$qxj)y#OT><_}{Y@STK$G3K;_7ZnJLuY&Eyq~a$h z>zBH!J&|N#&lhcZP(uS6mUKdFBg;RTq6JoPLp1jd93ww&qn&+4!)We%bV$n$Qc;oI zGkk*`Vz0`I1aXeKm}1Hc6vkH4B~nl1m2mnmTvbn&LPS%J6l1~*=%Do|y0#r-pjSDtbS8lP8AQ=?ae zG0A5FQ|@DdOf(R%M1gcc}^5ZhgsFXoT1-n%fzKYFZJ$YF+fij zP#M~?AgU`@T#^E5ZpH$Twva`!>6hVw*JzN}jil^)X86PURDF>Gen}x9Db^H%Y>W#4 zUhaT$WAys~uq0~hUemE$>1<N|JOB_Z0D@xoo}brY=ST$08Ucu=3|}Y_cwO_0Ntzcd?!=nwWQF+;kdWfD4V@9| z;$iy+cigv};`;lYk!yjUMIm97u@~y*XrOqu`J#-oEN#y7c~0d!3yAS=M-cr#S+D}; zf37|EIy?jcIFFgTR`K$JpixzHOGv!@BV%owJOaK0MzQqMH-by(WO+HOK0Dw7;W4iZgn=_K-j1?J^`d+(N%W2Ok{u zUv>|&Z6KdD;$-2|;e|*lS?xgJuunt0iG zKN;LrlOfBkaW1EK`U}Ai)s!;B2aa|ki*7g0Wf63aEbr1RqTmfCod?C%_BJzPb{)dd z517+|`8r`Yq`Eg(ikwC6i{y9rJ4IWYqHtBy9VeFShO&g=nN%HELn{mH92o>N$V<|`AcBdi6*u%&^GW1dK zu9(`OUN)aM?|*}XnP+;~V1bb>$t*ud>}5H;eoB6Zht)9yfS>K^7F*&nXdPWuG(fN$ zM$($2hw+7^ac6T`V2~5<(rIY)$@=>KP5`7ttOi@PneZT7MZy!FU_5m}0t zy$~6{rOG>5Y2LCw0R6sGs2ef;h~&Eg)(WCL0s7mawCe3y9K966-i3~NU84K4{jalQ z|L78m@NX5eDCSep@BThH&x`Quln|EXy4L|E;e$XukW>z#Jc3+X6~T$E%)`|kREW4M z7s>jc`FvWqn`eS2M-mfo^Ki{MIeRRbj0(ao#wD@Fbrl6!twdiSVIBO3-u?DPB$~cX z>!cZOdWbu&0Z%gJ(e)9bIcPA2k1c+(BH6_FIowAAR^$q&{J_d^EgO z5wif2onSUu_Iwq(OspQ>kvER@wi&sFr~Vu-6<3fP1$plL^)@3twy~n(#gzK)>foI4 z9xFZdoKnM>>EZk7US%UCDzlb|-b^|9NBAXi1C7ZFr2Xs5)$IMT%Iwlu7y1F07lM5W z-@02r%(Y<@y;jOC7c`*+D#}m~G?07^rPEdRV0}{S)`?lCvgKy-&i3)?KUWx2qJ7`+ zI%vUn+gZDdt+TV%=Ro74UjSe*bax%_DM1h$3I-VG2-BX)KB|q6bj~3;IO)Nz(@bRjhuQ`MVdzX!g1XbCAOqc`^MFncR*!By~QiuW@tA^Vg`n zuCazuQMqvMK0y|7c;fLQpGOGx51jU>I6mcMPY5B;?0~+!W$dBmVP-HE6-7P`lfN#<~@+tEv;y=$M9ttfTyOt_; z@8h~SPP0FzBYZ1?FPl%#BYj^;w7+}no4@I4+I(~-;-KC7P!<*SZ3%Mdc#}q(J+++$ zA*|tESAJ_25D;dPS6?&!OE*59eQ4{)*0+A}iF=b9D9*q}(F`mT?Li6}Q1(Acu2Bg? zSb~@I^wZ@j6Nt{w$+v|R@U+8hVvsQqZ7$vwZhAFh$ zra5=v6S`hPFBM&QSQ7D!IZJ5S_VD&Bf+`ds|Ga^sUt28$~{o-#)W4GM9%{k zo3$#@y_~Mk9_$29b3^a`feg(y-NG~|G(OvpT0pQ19r|$3mZo<;ex_c7(%9cW1#7v> zgmf9EOGq-6A=KTKX?X!EOEciN%zH-~6*uV)?Q3+u>#5tMDM#_9)%O@b{rL)cCDSWn zq-M4dIVNkQg8yuY%uQm4ncz0x!VCh@4P?3fDTh+Fh7ZU;_e#Gx8!9#LjU#p;MTjDCKYq@sJZX%ql&%UHW@54*HO4c(YT!QGQFL#R9^0no3YfiS4* zd27uTt_g7<3>>$)n@~ePQR+*)81xiOlT|&t=M#)GgW`p#L#%rggvdu<M`)2ToaOoz@2*EgZ_{Q#WO#jj&c+lo&yvDj@v@1>ZN0kPb?HG z;ZcscOjFkfMrSl0sjaRM?qiv}ZV#vPg-pD<*ST^5G;0=bQx9xE(0o^!`~bD6B|R?6 zUHB#J8Ko{!N<)2}D)CjG5o!3;y}i~VGyM{yjI z&5HAg@=|Fi$Df8voJu-B*&RlWq^j6m`l3GYgl=+@md1C*V;s5Oq3=m55Wa5;RYZqh zoI!CjXoF)Z`Cz2CG|10%Jw%v7pNt?FWB1pxOc8`w!UFGxC0^i=w9uPh&?NQe+TNd^ z9M?MTAxe&giz`Ug!MM7UY^CKn{^G3V%UItRJoTsSAXJag?S#g2A_=T_gaORpOKiZ1 zMH-I4sa<-8&mi}Z!{`tDW%_xpd{yIl&Zr(T?z2HF$Ipl;Kv~3$a_XA=E z{fmW&i$KGeoNMf*C0=<94B~Bi7Zm+11}|q&J;1T%^WND`X!A(ToLxZ+L~)wA@|8Hn zi;2#+cOOT{&0auZYsg0cmvTGSCV2mykip;9luSEKAV=t?t0CkFVc`ZOPU>7qwXh7gC}?vgd-7*gIO3J7M)GH~;f z0U+m&$sU8LTf9npVd;v2Q9KG5-4+U^4*z;W;%;#vgsz^M^%7 za^-hqHEsrE3_04_(-{9c|DSfc*nA!ZHED`7jWfa0~Mx-$ovB&X@057S!a z1Vl}Bn`nOC+~)C7BTG{;q5>>qf{7~4V(Nrj@Dqh^;$&0(I~E-Jv>|#z8&Pi2$_?MS z3j5N$F(qX3ENudqu8EwYmjeNuwKo+OV4s>g!;k_Tf3;QRvuaJ~ZGzg3%o7R*hOmV1 zRkHWeCD|$iT-($7vN#8K{dV!UE|gdpCU3he+HH<{71Lo86bI^>`K(86P@k4@uUIW7 zmh>^D0%J`XM6ANSZ#(o8o{(1l)CcFnJSq-EL2@I8AGtN}vv2l?O|B#aBCybW7T(Bg zA}FNH_wO}(#MiwiC6$-dWMb`=lLJ_}MZl?HX&yVlJMB_P7WbAX#Fz9|A?GaIrR)oO z9i*Szfg69Se=6d%HwHw!901?kUFx zHlUpHFna@%s-c1M2B&*yb$b_Y>>9m;swwMAdGK0gr+YZ{yDV&vlQgAL+ILq9GyB`# z`Lfg8it*f4$}TH*TX}ePPp_W02sb_7?>ZUy8@6c%`53KWPv@5u{f!L%AtGZ&Lh~En ze=CtLEFB$uw4;ytn*F%LAc%!=ryu`3)oKDVf-Cv^-`gtx-osFiftDOOcoit$aQ;PA zdk;C!o`C+!|Kx2`!i<-fHkN#T+2Pl6zfOFO?kuFkzv9w9DIA#$6SR@NFj-CX^$ZOj z4H~K*@R@FF>$AmiLnPDOXlrx2md868vOZf~&zkV^0fvcrYF%h4oHctO0N3&v zluqoL?d7!}68{3ez#Fp!x$nw1s`~a!Vx;!v0F7)O1aGg3gfd(-GmE%p~q-wdx}dc49j5Q>~)({h9yC^7EJm*~W^%eJ}}k4w-h9Nr0K*vu1(Bwv%NVr3&d zL*-bJv(N1M<)^B4)5PEO>^^Z!5USnC$UXoJm_{od{Q>rpti^Idv4V*%vEIfm z-nel}ee>>AIB@0kYG+UeLye^BeoZVd&n}HWH+diH?guU&T@(ykSCXwb34VXeCK#wP z1Y_ByV9RqG0NrFVL`567)fY^Mh6dB zhvyh!X@*d?qN{GLE>inqk(un204mXrsQXH1<(%RcZs<6*E)w@ zA#un}R6(V4jUKnxMy5SDZ(<}l{g9{M4D~O?SM?6>tOq2c9T*`x^uLoudfVI5g1I<( zsZ3>XzJ7O=4g)5cB5jV}C@PWtmPI}Is?2D_@fwX6=>gio!IKr5xFK4Y6`q0kyN6UT zb~{?{8XYh{al?sC#p!k=j#_}0G7)OgICus#QzYMiUEse0kse{S0Tnu5By$P@5NxKc^zA&;+PB`Q(^&1NxoEBZ4=pwRSdaZznC$Vvk0=QVfd$BXm*X%k#ZtW(Jp6*kMvgh-Ii;<2cfHBU#<>L z+xdESv;i5aW=oI^LiD^-RAgXZ!C;!fTm8M7r{1jhKC6AhhwD&7hKjvM#A4Wt-QQE? zjxrAup?a``pBz|JY^2pQtb&q4zLb&?6_P%}v=}dNWK!9WQMjQhMox2uEUa#{xa|=% zyt^14zh4&H1M9xNLRtbr8idhNCt>rW0oMwCe{m*Ww}T)61)W2L2g`sPp%}0h5vZtD zfg!l!#a@?K6tWXBW(_}_75PTy^n{6>A}>1#hxLb~!gcSUbKpIXP|`<(M)O#m1jgSU z1pnG6&H{GAQBDYN^s>hh>zb!QN#XfNW!5KF#yvgUo!wgL4&Wj{r7qR4tv0}{#IOvb z=h9?cVsH1$J7OeTVmwJz9{^UIk zim?bVSfok(Mx{m-;hO>a>doRi=waPK_X7ueE4S~FGBD2m`Ael)v#Lb2v2P^QJylO@ zdCG`+*}qN>^X_=^&5NdEIlbmH=qj!@*O?H&TSzNFF(i6JDNHZs(#N`E+dN5&xqFI3 zCFEPdS*X<8cb*!KrTha{yXJ}1IlFG7u<+Hvxyjb>^>ytQb+Wrgng40RgTY%!q(YU& zp}{fH+t*=fwEUIA)epqQI|taa_hV;cTA~7Yi3HJc^<-ztL&Eg8e+eH-Rd$4a;jEy| zTb_`9>5|=AlQ+$-0(Kfw&9Y-I2wE|`c7rBV&LJf(tlVLW98`tczJJ^MiExMaA@|ls z5fQfu;xA0s`p}Q=HGG)Lx@AX0y+!lmNlb*fOZ)2AgpO@73$7YTOB@QCaBeiG3t&h&w=76|Ik33NCUhrq6I5z<$D_kAFk1^J z9>GwSm=7H;LfdIS3Y#6ie;r>)2f1A_{2`n61;IVnbb$*waDutybIohx`82gbXs6XF z84rwg9awv52vIRv^vz`XTCMt@(5~3|Mn5$qVwx`=8yO=|@XI~@6CbUhW?i7jzJjnj@X+qCsofAAYK2 zX7}#+MTzY`B?wfo_qpx(<#SBM0l%9ULs?(>E?qvT5;oqDGX+h4exQWf)F9Ifn{RnQ z<@n)q?P<3lL4cQwU>GtsLi39>kD|6h?;_Rd;l1)MLjde#yi1J|Q?b4sa^r6sJ!Wla z7~Uvr{t5w+AVn5HL$-a?i|k*;<{VQ-_4-_B>4lJ-%A8^Z=x5eKfVGR#8?@JMQdcKPQ&ArcSRTCa3KQCk^UNNN5;uiyvYhQW z7#oZVV>Po(GR6*~mD<;;XAcNNgu2nM7C`TjW-<2(PPIqCQ%;}Ly$JVM6uyRrx2;Xo z^1Pk4oa|{@(YG(BG5#w-YFNgDykaUcLcc_eMCUs2`Ay3aI2M?YnZ9~k6ZnI)kG|c= z3tg8poUl+xj0PjEVsOo)VhYB_DsbGh39;|eYU%i^u_p4Y=o-r+1GnyR!EG}*^PzUj!oGGS1Gh>U0+ zLiD4cP(LU$(J292#~luiV^-mVgFF>U-ad34HhL5g8C4y|^- z=IepnQQC+zSD_oCUhe9c@Fn#=QADvU9NdEkl7L;`aeS-QpC`MkOx^&ciiYpKY&0k^ z3xw+LO{~0QOlw>8(OsBz;!6F}k_ILb&!^(_T7#bJ1XD27#%)5~*+H*YI~x@m!h$~g zlxh;wC+JmE9Cs4EN`-HSi)tkldp0Sg@O zvzcZ;tUEuCYHxo66>I8vjl9l}#9p;Q12?fQ0K>jSU(b7gb|BMpub%AC0^@+-4&3F8 zFzzq}=Fx-jQfZU-)!6NW%+B3DFA!T!4Hx2()18yC8KaZ&6f@ZW#raN>LE+Qc#CL{2Dj+O+6XB?&oCJ2xoh|5N_-5> zC<;B{Tw}$=8_pR@DYGe$nzHZ0c@xjoQU8j5Wbny+a^hu%>P;y<=QXpIv&qs5X^!WV zQ(h0%Dc)GRn>QccE59mMy?gVqbbFfg7WNo7>n%bO$*No_hGJ?pIHWaEwbs6&eDD%e zi)|VyEht14kkiTh2Kx*~%dR^)ez~iQ$N!sy#tuLKYrqqN8igBSEPnakN4DkCkN6Dn z2H?atEu6?KRM7(jkOM-SJC^PLrK|GrwDW?5H7?eXD$ ztjY4qq0Jx&FzKH>12<5msBLKY{X^$@Wtfvu_h0zAmqZ1 zDRCNzOfBHg60MY{hOC04n+bPO!_8>z0?ZZ+iVlDXI4L0^45xV>2$W-~7Ud|5`RDq8 zj{6CwuS)quq+_=g#Ku&hXob%$7M?mbI&K@B~Y}&Ixo14?G1zCv7A@vDLm-dPRr;HWbhq~!7 zKl>qY@7De$Dkv?xovbR|TnVSQH@AD{ZL1iL6ZxRM;MwmlGDehTnfKdg2@OY*8RUf~ zev;AK5j^`(`|n;k0}O!6AR>7CzShQq!}cJ$cnW#1c%rQEtyLIK`w~j*w=GA=`NuVF zs+nFUwpPD6L7?LYh!x!{)}JMtG7xAQTdjZD`A#yREALBd@vxP>f@b4H5sHB@45iAX znyi)(*i2hgWY+je%-o>?n|!60CAt(%j1EsHfj4PA97<3U>(cMdp`T^pdL2v|Upv z1~<$%xcU7;9AZKiWy3jEIj7N~xKW2O?v8zFr{igauCD7^8zpS4TGF~2e^c3FN-ZeH+(e1mH`P=V;RwHALw&&QD z&aK#1YohC)*vRN6(K_k&T~z%1nlsRknzE3`WEg^W&dXT6 z#Vq!S&Ec8h6f%Wa$Zm!RzUQ_rwlKzzMN|eN>v)#0COp(}<{5=L1TxkxU6Y_1-Y*Nn z2}=?^`qm5&QYwhW)^(?-SXv2RKqz49$M0i5VV;?UzcB&AMv$ z+RZ$#FN2QH1SzX8g0`T)u7SoiFajW=u^1e(b)L#RtaE85{~w&&10qpQM_#{4f0uW? zAAE?q(7*flf@xA6tT?DmB?i`Yw3#}l!`EkmkY%UHb zau6RIQQ4OG>T=-TR=O3H6Kd&58GC>cPiaqzsZ)f+adF3EJNs#ZgkZwM(AfGw_|>ed zDl^yVJn%CNQ9*G{`$(vmAhs9X20pSHX(RjDFaxUr`saxX;wnI1xU9G7GoKH9#C+qO z)Idzu9$~wsvfOf&Ks4P!5fX4fZB;v$VvRMrksrzVQzd(+{H!$YQGa#uQoYVdM_GFt>*Imt-%UWI_EM?Gs8+l!9 zz4X8xn2ogCZ;o#YzB{}`8$V)|`ij8}GG!w))bv_;sE^OL(hikt``BL#8n>c&mc8;c(-n+l)9cJ=(UEP`q{SU`K7{#>y{e9 zY{JV7WE01|ql)Kw!_FPQA@clLS61|YDL?_~lM3ec+&sZ?{*qn)*ekvXS>l;kFNtK5 zrJ5VOsLKqyb|r#Uwe4PGs!7Lis{4)2ZD^H^v6?*mw_or^^A8S)Pat?amIIF#6G2fB z-NAuf6{e)^I_%5=v@j?mr*FcXa0tWzNW;p)H(7Ebn|HIU<2Y(LQEol!2U0hDK2LJI z{wy!^29EJEZ97jdrBnm$*4qwt`V31C`=4j5zl1kVQWVe2Olc(fr~b0Pv6mRv5VvTy z7?_SVizBN|;`}zp;@Xx-L=p4^!StaoQlyT}fu3|AMgVLN-63So?uhSe@PZ2L;}?dt6zjlG3DUt^_ih^J%4_fH)Knl$Ii{TrcGoMhpOE z7501%AxW#u`cY)#nDb;bG8*LJF@V&?pVaC?`>pe8uMiX;t7qgbTYX*Ci@H1ts-uV9 zq2#gTD~9oAlsRc3Pm3}n6UD|ffW_rBrLvXvA~92i0twc+FS&BGld(VmHo82LtLt_QMCV zW9j4e)6DJppKUj6JPKJpLLRpyP2F30xZ0v79RcePa??Bj8ulxu2Y!*3RoLK)+ zi>1u)X=8>CW}m8yqax>38SEkK&Mba*dF3a{<3w7f6Z!|%1DW48zM$Ve)(Qf3>F!vM zgAs9*<4ghB^LFc&dZjg8MP>x~bn~@2DZ_tpP9pDTl(qxkdJY8xhDK-Rsmak+f8-DR z0B{kbA7ZD+g5r--%9~G&nuV`u9(FTLrfaG>H0ZL(Zt(wZi&DOw7)72je)0R9RN9*> zrFZVWgq07AC@{2fC8k2>iTXN9n9tCv@U9nXlY-NQB@m-h>?0QwySs+P-H)R&QESARfvZ zZE&7471B(T2vtr+)6=2?P-n`v+?88Zi`P_`?=}7asTS~o^nsdC5xjgVSbfzr-CRub zHr5><)K435|`lpS+H(#v_Py^vmVhz@oXNs%Hx?`U^1ot(OhjUoX$Ne zh|qcfP7XULA=#y?I}OMOgK7*!0k8W&-ZkA1Kk9npy_F+9(aWLliH*TtDvT7G3FYe@ z5l$vofHmBbCXJ3c=3Q)E-9$V;*jAW1J2j6q5s-CmeY;bra<`z! zYs6T_u*~9GY~C^=%=N8ez|{|P4AxfJPlCkDu2k@6=HH{QCfW+Bf&ETW@A0R?JR zpFZ%RPKsCzcS?-g=<`^pmg9TeX{~WGJ@4MjH#-txmna%7Hsn^#VJ80mG=qAE=KjzL zee8=*8GeEN;Hb|Tp_2+^$ESBCn=zeJFETq7B1>}`Z?8X}RWQ9oeFfe_&h&_9s;k?@ z6~9vIl7>R^Om+QFcCHhw#WT@>P}ln@O*X~o^Q19aVJsJVNOHC9|4hwvU;;NXjJdbg zGNyNrL%!CMt)jKBf$?fshGcs~60R+gm%eqh*hW&Rxq|4(py925h8Fb)Y%(@6R&Wm5 zE&bOFnTs3-(iQqEPUcP_-=ha=*NZ{&bxiuFasA{m&tUAG<5GgE~|{|=O``G69RQ8x^} zh#G`B^f%-JP<#8LJknJ=_ih;%^n9YH@Z4={ZN_iD=-4~$VJB0irYbiT+l2Ut_@R;a zRZVR-e(%v)mQz+nmhQFjMBV(cc}ASY9J>Zx^%1ohh|t1x;0qH;4_JkSGJo*J7Jjfa zii?L0M^Vr^O}Rbx;7;_~xQeU=z;Y(2_?3(&SSeD|1%Ol3j?&}_;-w7xt9eQgZ(5F} zR0|Z2Hr_%^3&D_~%Hf?mx`XW)5>l0VN6YNL4z+RW-Q|FI`}8hCT&L;B#%xW^>=fWp zIsjW_4M7!QA+N@^M9FZM7&z|Yek%L#?VwDMh4pP_UPS+55zUfxcjT_ancEt%;{B#X z<6SxNgi%8%m@sddsCDomo5rPxMh_W&piW|cs$M$qEDKWP4y0)Z89YnW^vP|&+w6az zu-$v68|hk43fwTWCiBw30~!fiX;7 zi5Qu~$FypWNN1}O8NFx-ltYG^-CcIN%`j77-~IQSU*z_6Z$KNvqMAb>a-}+*J;$A- zKan=D6kqYyHD5$z#%ui1_kv0y+_cJ~CRtFyUa_PJL|TIGlZKboy!MZd)~-NX7;sWm zu-#UcSxwQ!C^=p2Nr7+w>kA39;9Q(xILZbQfPjv7RKMeOmj0?7afzgxn>_3th(qRPG=-6s}i%q@vs_7**r zBFuC7@Dl%eGZbdg?qAgMf7kuwNS$5G}C(nRJ1 z>CSKU4X~5z$pt`qax{0SP6)D*Fr37G?Stw156+#KLq>sYr5^?3trKX2BAk?{urwA2 zN3lu1q0&FHqGFZojNaNSnwCgeU7of(tE*?Z=vdX-d!d#)U2>UCNr(M51VNQs(#59A>I(M0ei84B6N?g=u|B>NO;Tyq~6_g6aGx6}J??gCMYu%^SvFcC8+m{>9 z9n>*gBNAz8GgiSDY{Ra`c>f>~!qMdwv*J!9PdPq-HH2B$zY!WwEc!&M_t9~&J{If3 zw825URldnRZ#E1~jogOmLigtF?7iJpuBhRT&@wy0aeaUdaEmt;a?vZ#gy8z1%k|it z84J=(h%2#aIO*2L5HvOS>YR*8U9^ype~~!=Z`}C(Cf|o=Bg!PTl#`{14;>zD7Apm3 z#O3llgnrpZ1!v+4_ewG!`8=`C^%guO6b- z;HshC{fFQ801x(kRjt(gAT>pS6|_frva(BrUcwe&`-}fWh%`zAifWw3S%{KX4g2?q z8`PieMUo${yr{U4Mz(VHZI}^1tExe%||2BJ)Vt-?q3F7%$WR9^2hbWYeybwJ`N z)kti{F6LIYFul7ebgO*c&5I(>VA#j~BB0);ef50c1jD`wenZ1&T%&ZP59p5l+BP{x zl_CC$1fC~h1gJkZW~}_j)syH%(oco)C>7aitl1mYmSc@~l$gY&{kk}dExdTF(|ty8 zQ50Ix^2)k}?TAo{I$przwx+QN+jADhF>lweJ>A!wqse!n0dwAXR(UH65~o zwbkgU24g{b3yFc=3lta!8vDFp7_S0AP;aq7^}XP{vJiY)@}z~heI@lE6+-;b zd8;qN{0-^|JR@r(zUI)z;_bZTIhOYJP(ESRiEZ?zT(bV%t`x^#q0`` z62DQ0mS1N|Dw0wL@eljKl0@3B_W7&Kay%NsnHgP4qSh;Y`gpzlOmSu zl4R^drTle46jU%s*K8n~( zS_s^J^kIrZu&1-i1psu)Db;OHprr>9{)&zDnFbL}(*yh_;sS4#ulUoS0hkIyf-cr$ z`S2M9L1?G?6lpA%9JV=*V=`MI?C=BgoMzZmF7!jzO$j~PnO^jfL7*YiKc!r;br!69 zc?pFm2r%unM$o*iLqUZj&`Q;J58H!&Z+36tFD+z3_kTD-5nEef2;b<9r%c?{|S#FtOA?wwNW@M((_eQW3E4jw%#4a(r#0EYKQn1fUxG&Jqxu{}Nb<<5mCZ*v5eVd}4t%b3!DP$bXB;Hb+h2NYr!%&Ich z(S-1q{Z1qu{4PYe?)eR+BP!+z=vZM#WsEn$(YMkmp&ksHQGp5M-x+|=NPNGERk4DH zA4cj3>HSukv^X6Ig<*y@w`J}f1ruf(=mgv^#ir2a1Z;^lWkpP`|gZ1D)x z->$mzS6`p=1J!v<@5fIvS>!28w9QPlZ&&1|NnO|8TO6A=$wiHU%bq)Gp<`$Uqq52y z&Aas(^%&i2C#G-P_Hz1ez{~WoiUq=-WFMJE0}L$OJW6g`^OQjZlZQ5r_4tI@`2g4- zHcVz#Ddsp9SaI(j=4cb1+!f+dUgh}+7Kd;0CDR2X7+s_wIm}&oN&POAuCX~mHXy@F z!=Eo}!)3-wxOZr5yXQc_94D@JjAU)AKjofL)vuE%&w#a9G=}tJrk&z324|!MV?GcY zsEeJDmYULQTR%_N;s_Sx=vQCCrgRs`i_(O>6ixq&p*nutt~`G~`Hs)$7mswBB5N6y z??i85x()L=H)5Vms6epIn|O2W%h%I7%^`jW;^3|HqOjcsJS!Ft={^GJ;MBN7&&`Qb zx`3FEPj%crqwh5s6d&yR*PV+Xj_lj}+B@D&BvT;8sZkW{sh;U$0_OYDVa0J|UR~2X zw+JAxUYt^;Xt3sYS%C!WYo&+VQAyo6336P#YO z2@;R#t0WBKSywGB=`~e)d5oZ|n9Higvi((q;d##YIZ*)@`2M}2p0fqE{HzTNO~2UU z#2mQ0GiFCzU>63TBDKwTxcF{SvF^Vz{W6CUyZsa0k~!s}f<;*wTvAwA!BIDFr4tA} zpw_?}41!brR3<4-j%EzAhv$LnzRs~Zz0zq);OQNv~S9v-XgKie>9V5 zb=F2b=+wzr5wj$KVkNF0c0oez+{2c9;qIFU=ohFPSsQ%Bu)K@YReMy}im1)Vxfhj> zW~IUEFFCLZZH3b}11;ciGOr82UHT#)Y1Kuo}=q?zY1e1XL2rAv|k}h4nILDqIzBjw)XMkcT{hZ5Wl1gQt(h9{q-x` z_cGocp*|Xg66(MvZ<-bajZ)^eKA7ZWtFv_D!lB|W5pE2v29kQ`s1)>O_Q#5dru2Qo zdn7lpqCz=Q#Qt44!P)8S_&cfWTTbHh4OS?+K*TqjNfKlr-B` z1f!+LV}~@U(O~&<8Q+uL8NP=IKe~Z{c;$FI+!i=MEi$0>139x6wn=L=-1Ff1!!&c* z(_c^+M5rg8wYD*(D9*kCSSE9Tm#uTPi2CpC{hOVkj}=bbkOr=JP0FfC7jg2D;CX$R z7myIs{axIU>PejsB9VQPxguVWTgqk9*|#RC5w8zk*(qnf{aq7uIg?tW{L`DqV-jXj z(WN1;DQ%4x!!gRMwuKB$vw}_y6XbwLQe)Eepje!yO@U3E*5_-QlIWQn@8$LVQO^*+ z<+oe$FqI)m%PCBgaqC7*DVSQdGo?h+q9{F5&rXs#+KXc?9qzPEloX>3SaPK7YuWZA zeR&weq7h>kMh;NLm{keJ9aCA9H-3la4$TPqQ4rYV zXt8M2Enahm)*lC1R>XRa{m=FV1gj=i`+EsSKa#e-+v6bCT)=Z6qe#yz8Ko6iu|EzP z?`h8eN$JDav_DM8cLuVwyZJ1KuvY0|!?@vhI}KV7%+OMKvVW#3PWUa!=}hUm}!M_V_&T{as|xQv(J%4~q1ls`$eDqYNK{i*gAf+hDh|=dEqbTBnld*?O!R zuSdMhk3TDU+Aozl9*b}O=sZ!iCq!rSu?flZ)Oiqkw8@U-A=6qzrHLtVqg4M% zm`c<>=d>|L(Iz&GS)7DL{mBC6=VRj0kgUGANxg96B`V^_GA0|UI%km$%UpJ0tMP1^ zk|zPDQ2ZMXRID+yExMDEfr-mdI}kiBJf064cD!twIfKcul!G>RyiuDsBnoNXD-QCdS!?LL936IT-|vZuo`2LA}bRV*hMT~ezj{UVr| zfso&yaaxg`yN2+kI_!T|a@M1YJTumxvN9>c9&$e+_M5{NOXNuI*H2>*nPJwy4KRTb zlwu4G9u+o@jJRe}9u*-%kHDZr~GsE}B_x z;iPFO<~;~&?9Sq{;OBXF<~;OUY4qKNwUh6Y!S`VOQ5*Fw2|O^!g20Qc?)?LytukH; zeKgTF^drch)@(FvWx0MYRE_iB=N&ph(owEpmUlwhlZ-S3%f7`fx*coIdc9@8&Tu^o zSwqjTz}|MLu|Vfry{Zb(43xVN2JxjewVL-mFOaV}N{5=Qn{G2Vv66@f){oLQTS(<^ zEh&0!)QMb;c8q;(m7|tpWpdOaBfnjSn}|*0oRcE8_UQ*K?RTu#=T4 z>We{N692QRNoEb^R+h7p$@^AVIu+X^cNdzRlDnNuubwEJW`3em{@MFWlKvrJg<$c1 zm5*{E?q^dlx(J!t zwNgwBJ~Dmf&L4G%F((9|`5T$;T<$f#pAf@+L$0i$pWq)XSbOA3qB1S#6P5KC8EHf` z=8ftQhy7fz?Yu9mS{KpV><%|5B7{xMeTG@V1&wvOsa?^3q37GMk(i1|3)gh{F$_j5 zbY^hZgUQ1q-%xrR)Q4_xcq2P{K|u1@(*Nc33BVw83bO%#VW4a|K%RmA8HnzLY?4(C zi-InWwhaE}{dz=Mub_l17w#mUPqqi8=h)fde{qThN+c_aAtKnA9(J!Zr)w+MJIs?^ zH&a?QOOBpUdwE>Jel*o$sA<|}YBzj&Av#_AaGEE3T4`jHw}z0YlWW_M?RGIvdkf%C!|0g_nELo_ z=3n(Mr@@`2nVo4TFsRx-hMD0v(tqfD`wg7(k5IjsR?g7=q<$iJjTyulQ7=9G8|S{x zguRwn-3)_&<^dioiklB3D6K8QH@QF7kQ8sY<(sVn+5Wlg;#IDvv4W{}O-9}nXP>;&S$GzA zgjp`;=m*nPN(**`nf=6-kt6Y!ROsA>u#c>Ac&+6%1Hnc=GO8j z(x&!_YSLSGo25@?9&d_K&ZtSws4OrW_%}h@XG;}2QIC57D53idmmn9n{3QootkBTX zEfcNNr zWBn#49}-j`9cQ{xe<4{q!9t1?j6 zaq(Dm#LDOP1V;d*^W$U9oGmG=Vr2DuM*;Czr2*^*?*9}kJ>rocD~0hs=qa2DRI=u? zQ#w-k15beH`H4Ri@XkMl$1GV&!Mp9YjG=%5rO%i%jsjnw0cM6q(eP)3JqaeUEDXtr z0-|uD)D3RjKKhWC6tKc+CFNt?bNFseInA^c>#~+|DfAjoOwKarg!I2323WWe74ZVg zk5hFyHW8<+PS^^dZzeJv*5;OYA7zeedQ7CQ@!vSGGN2;^d_n=ZnbF4`_?bEtE2Dv0 z>yqH5kyO$7g?V_zsSUP6nrps|J8h8`MvYB$(tQmMtRYvXI^UzK_b&?$nxqK|EulJj zltIr)4a!LW>mTCt|6~yG9~tERd!gn3ltKQ>{jww?m2;$5b`xt?xYd50$b?$k%dSIJ zAd0ewq;5>r$_*RtBVe2cVXDj-?MFI&QD!0O*42yvBH@^S*;e;A_UlwB$Almf#HvCs zMp?KT-r@G5zp3w({hGR}YE*MQ?bCrNnvvtV@p$Kgz>(VOFG-fkxoT9#?4I!EWQB&4 zY9Xtlqw=FdMI5Q9@H=_9=kkl^GYOZDx#)DKmC134sBds2;kG4Dr!p7{lk9X1I;9jy ze=8*!b<-|hx2>^f=>n1&)~wBh&FhU4bQY@gkM1~{j(p#@-J*X*7ZZyRd_Uwr#Ag*L zj5j0xa6ek~7qrBNNXU}0Ggb%A3T0;d2zahdb_XPbdJo^W;YtiH9ZatNLGCJ>EvC?U zWdPby^wiN5b>LEzWsbG8Xt4oJiD(xu5 zw{u!ylyW(o!1s3VYWntO&Lo`s&Jd>~dIc37d>zIUgs<{)MUIRP=5f>kj06Mv` zp$kat!@$bXwR|Lesm$lY0?8bB6n;;WT!mYD3MkK+QX)ZA@vKe`%pjUO83U zN5~nDizOI!PR|NCFYcYw2rCw3_m6vZF|#?lgLp;m;JjXc_G!z%}16IOGfMf zdLy2<S1LkOs$y8c-BNFw!fedimVl4N*9o-^ow(Uu0^1Bvqvn# zKP-Bi%^~k^47-}~#VI`kt-W&RtRK>;-JhGBHz1#o6r4h>UeDHUt$^S<(-lYIfqdch zu*FrzyMSS}Thf6G{pEu&t~ha94~>ro>$H;n@qw34jxfClIIy`_m^8U(s$4fTF@}$w zuS=OX(dR^52Yof-sTW`7?~3oAMqB&#>pPQUL;y5L%)9#S{ev#ACj2k~im5X!ah#sa z;0cR@T`!ay3?wA3)SuIyKiT8FKc-wl-8YpI{qX`f@ga1Cu`7l)W_sJgC<4GFqs^*CW{2Tz07iyjO|63J5BoTd0^+t+EC;6%j?(t$hl*4l>gjw&jntC zggMxB6SVRL|dC@f;#UaArfr9Fe6A-$?>R@(@B9Qo_F@9DZ;jLBs74$_& zmGlEX<5T9`y&VLI5r7Y{;;)3HApZjmK(nACOUb48f7aKDhd57OvXG7R6(Opn>QcQg zg)LF0&W#BB_HRj2K2;|wvR|ro<=bjEt`whsJEhiX>46+)(83|hI9^2BzE`*1+b-oK zZv!~Qs<#cSa;X=7!UCX#2@9nENV9Q`5&|7)synIEojo_eUaZ_VM35Nen0o|NQ*|B> z^4RH2Q3ThWk!~T8$!mRgyNHwX)ei~SQUt{W8Y|-oA zjn~cj+oI~f=lh^$$0t>XAG@Z8xKbRmWQM_6rrdqM#MpA2cBuN@ToHDN4Yzstb?a6O zO+r;aNM?=Aq3R#FC(-num66w!&OqD9;4t~7To?gmji-ZftW3e2k>g0ySpQhd>n&g( zqDvk6at!Li9?%IZsix`ASZhpd(P8&A7L3mTqXFTUeSXq~4cic-Z5|)*(-B^#JOm_}3$u#) zC$664T}IUg*NHoGv(u&8^2KR-J^)GMheTWhW)pB0WV z&L5rNf2;kflQDwAJN`^O?qm;yC5pGt@NKl1`WRygTIy-i!Xb!&2i@J``vzC=jeDdu5jkUx z`M@Q1k`;3hw=N19mjlQxFlRR_|LhyV59|wkVYgAsFo2_DG{d(j@M}08NM&!YM$LXl z?N=s?$R}+cngaE%?}(C_)17=6UWgR8MhXR^52hxeq`>O}qQt7{lg$;>QC4OLY#P`8 zioLfFyMs6{Ayu?YV~%RPx<$b3MOxKup7rbDr){pxPENl7wXZ;(kFs+~kv$MByWFZd z?1W(BKbgKswazX`F9djQqU%ei3Q1TM(=4g$69aO%%U~?J68$NRDXrFz3K^hBII_OQ z1c1{FT{%Jt-vqOO%|#%m)D++lCC+F%cT>^b`ng!Gy@CG#E1)Nm=6?2m2UPiItkiiU zZ8|42WhU}Yv2V?Ty<#B#1H4DDKRUSkk8t(%2yyUIayK9k9N8Oq5ljBZD9NF@ z%wUk7lCON~nJv|njG5#QqBV2J-Q=j zdpD%{5RhvyQz)=m7jqATIG8dP29d#iWz~}&@V;?N9qPmS47S<&>R`8G5nTfTE1Qhc zXEVfrcUoaypSp;1^v_1ml4*UveZ<*HwCSj?MeeVT2o@qqJIUA^{Fpx+Lm$)rtkp(z z;$@-)DvSsT=5{sW0gQE(J^%c0B-tnDUOi$+JUy;6F|D7KG&H_+a+#n)gG|$8+ThlSh?;Vh^3Rnwl4+4ojr?F(A!5oy z4@gPAD`VSc=yH@t^2rcVtH!p*nBI20)cGzT&b~ouhQ+8}np5-v!6j!Jh54S)+-eUU zO)@}4E=N}P>7#jgm#6gCMxk z$28KcwwNcfp5@gxD-_|I&JKibEE`-2V~2_U{R&UF}!E)IOK-x`9K;OwW?$=k&&*W}|O^AO0-UWIU%1EY0Sc{eC`-4d$%h5TDZ z%5%#CFTIREw)6;mu?;uCyrKBe2r%9-or!VD$2r6<(QdCr0`DNM!H;m_{dmBv z;yG1S6%Cgxd`##`+kC2o<`@Sth6IoxwB3MctLHk42HA_6OHWFBp4x+Fl=u(u<5sV zRcoc=G;$_sT-hnZ{QKBNV`VlW+knsiN+#hL%C~jwSjxC!HRkO_No6{# zsFTR0qXm{Ky?XibXDi6c2owYq30#XJX*x0Ttq!FOUWo!~&*7BE?KqoIGS!W)uc~U) zostfCEQe(@^=8t)P>Aow!m(B)QMU!*JG(y^f->Lucwf9qCUfGkupa!NC6?HTwK~+N zLXKugO4fkRa}`qOD(UBYRrP(`Y;g{c z+0gxj`UN`hPdUUh^$rlW3$ReQckMeJpn`r`cb zeCuwSjWLy(}E9_r4kFYm(pkq`0 za)5=W(5u8TEty%8l=UcYU6N#P1Nw`>#4sxaS{-ipxIR^G*wtkE)-|#y1Y5G2LJYy>?wc~ z%cC z{MH;~ovw`7OU@7u%(`mK4OgLIBAM|bP3MC8J1w;bEdF6s zq@1eiiqL)cJRWJ;x&4jqd%C1n4!um$Bo`Jb!vgNNdzI5I9`BoRRu9xKC1iy1`hkxY z2k@K7-$155INy5w&7Fb*K!Vh@8gAbp<@)Sx9+FrPx^&^_2P+2riatd+MPs65Jtw0d zelom`so=U#!&WKsQs9bVV7v`_R5e{6-tub4OpaNSdzo4nh^mB}2O|R*6W9k38w47I zE4uSYocZ&NeO#(JC%VhMOIS%|zArg-to5soHM(sq=@HweXoa4Ja)) zDn?T%e;Z*OTK#JM<0~NCBZBXD7espIQ2&Wr171gaHeoRHVdHB39E^>8n@`q1f4z`r>rkYFk8ku~=WD9DV2nv3c9$N8t~Ph)N2 z1(F;YiPv6I)!*nBRjKeQOVLYfLP`Mt`2_fq(T&>w!u4d~43ENt5oYt&v(OS>>Yzkd zCr90;dB4kPRRtZ7#fp=L>1B3&gyb3+3J>-V_dn3*vOJeu^zG>d=KDC`({em>>>duV znF~RV#2Ss*hZtXk9S&yvEgtqh^RY!Zrc0hZv;9V!iom8iK4YHdr;1v+n4aZ-OH3(d`7z)@?i zCJqI9GA|Pt>y0}YARCI|-c8HVezdC+py~U#E}w<^_nf5|i8n1KQ7N>}M=rqjk?n6r z?N2N&_hZ8MU%=D=p_1aB0^>a5K4-ryxb@0;)W=^REu%dw#t9WwWUEnwe!L=g{9C3( zXu`L1tp}V~_cy=zORm&cc?C&F4c@GD&If%oM3S#@KH7o=zgW%7KQxizhwK*|JGw^3 z#L-C?xaBVV#E75&tXiPDI0!)3`+Jb`WTobK6{n^sKT8@|Nob%0feG&@2Z&Z0Vv{zk zn*rPtsN?Hx#{f0%)y8=Jn<5q>ar^ORBMYIpDJHR)naa%VyZIkew_)kSxp%`Kl)3Wk zEyh`p{t9`IKnz z*RW7>3*W_TePY*6vKjL03ve^XR3o2b19K3yrE41JU=7NGFuq8$#89BLA9eHesgFwz z1iqWV$Y}h0Uv=mbl0JA4cR7yedGjJI$UMy zf{ZZ{otLx}mjj%TDu4eMu4(1uha0i|;6lvYRC+9pj@yv)daUezbRpnmPAl#gi{>T} zj?*(3eo{@lE_sJi0-%7Dx`-*L)Z19fO!8xjaIIC3v7&B^!_%Mnx%j<;?y&8?;XYJf z$p!Kpk2&unVJyt$TyZUOSUiy+C7H}KaDxwvJtz+*p#r=}H*f^zMr_}iPx51s#aeTS@` zmC^5wM?u1x<7E;)LQ0>t;lR-NduJ#)A=f==nYvJFD8H&o;2nn%0g>1s2?|7zS70Q= zq)D}Fi_EMQi1ilT-UUeO-<0b) z>8KXU2=vF{4fo8HG&6?Nr2mWvfeXlRjEu4Gqx#61~-pTfoOY5vrmsLpuV6=11A19P?)j zGEAmvQJ!W9QS6!DEWaa8o~A1yX(UbwLV~$226gq7=Dvw_X=7c|Jp$LIUDG*ITXeHv zq%mE;K_}33GyP`Z$$|;g`#ru)R~m;~6zMGw!v*FJNMcOhi;7P6;OdWwniJ_ZGk$t4 z4uQ=CxhPRfXedXM$8@<(w>_8oWyG`)OzOlk~CWv9S>s>u5Op$CQKJb~s zP!mo@R0}&gq5zvw#clKZ@wbT=C1|0s)u>?!PY7)?rDn>K(L$FB(^lF?$et&ZeZ`9Q zpy);igD9wHIv9?Da;G|(^1W|k=(uQQk{w#IbWGS%rWS~D@P^Z^M@CWxOHe8B@#^6SH|dE%n3Y)Vr_g#iF+}!C+PG>PIs=dX(0O#mp*_00HWkr9NLnn&v;jRyBme3te1*wU z`mOH44$P32RfEZmErmCpqlTa&rs?HFlA%AFEW$YTMXVLrGPqNYM(F~V1efGTD49Uh z40T=*S(9YTKGKPUTaUsFkhFw{nUOrcI5Ugb(CN$pk>Bu=oU&DG*%`ssfkV&0!mqbd zZ$I%)ql!laWjS5%(fH~}c*N4U`zSJt3r1=tvZI+}hZ5ek{l!J(^&I)mj~Hjz^^zd5 znvBc@8jD?7_&+V6x@2#heedN{8oWXiRF}!;t?vKK%}DMegJmHx0ZZ+H;rNNOgEM(Yc&ruVB z1}ANSapQc-PLRV~^%fAtGF#1U&NJ4cwQ!KY)NG?;Kx;$7x4c>Rt^m`u!Qi>YFbLJU z&n~>dT=b#xw)3yvJ&9#=VR8?c@cdW*-*~+uN@(IA;6I~n-`{U?Xk@-`V-pZ#@WAxK z^Xs&}tF@<~wU%xfPR1d)VosSC4tYbmpf@Mpws4&V-Sv>e@9xVfb=DG4Z@vaMc)n0L zLc;TKFAI+uIp7ZNX;uBy*6pZIoMLe);PG3Y8dA?K#hnp$P@eHhYS}$vjTal6e@tlR zMv?3C!YMaX;WpOkrDR23p)NXnWc<=bqHC+A75uhUtVljb`Ti)x+Fzwmd69!91u-or zK1eqx^!G*pfGMRwkguh>1is;IJ}3&jh99f~{_=?k;P}493}Gh~2k;T-GgqkYLN!eP zQG_GgAutYuH6;bjT=niPE{HTDQ}~G&c>lK#{rpG8A+fWU?esC)(ubr z9TP6Mi%sOj13^kkQD40HkF)qH`yL4=cX4ymy^8Olo5R8X^;Z$s`3p_1jWgoQzB{{p z=AupI%p{_KQIKqhH@5d=Iu_Rj8v5~3&*fHvX$+sqUMS247Cv{fi&3Es44E)M&UQ_V zLIFVMn#Q9PRqEU;omlR&4x9-!R)Q!bqg@^B_YXDQ6T${I3vRgjDEI`h26rufp9kRw z>Zpt4hY3K$ar*=ZAOJwNr91>_0B!)bm~C4)B>~_v0B{*H?+pqv%9tMj0JXOCR{RF` zt@|IiD(dk@DjgavTX>8DiSlSyL~q`7_R(q-*(y{SPZm>CPF3P6BiL#z#@AmB?PJ5Sw_fd^jG@k(i4V~Z#_Cc-H z!iXR$r)(l^-hK6jaa00%P~VOM2mqd=tXY5`MCZLNB1j*|y0kZ=-~TV%KK>Q~T8eME zZ(UuHN8gX6)q`Ww{GT(3 zO8Qyl{5r3ySs*JOc2o|Xow3_=%Fbj@J9TPI9MK)4?)pw$xEM47M{smgcnJcbP#{1b z0}ueI48rS>F&v#X{)PWaEIV2~4%AV`3>X0UKX9{F+WkQK08d-|QhGnn=LP&YNdSZ& zn0yiP&5{TJIuD=>T3_d9bZRgMV-XMLyPb~GDsid{{+|kCrt+OM+Q-rf^kN9 z{y#iY1FwO9e$X03HZ^_I2VKz^bdrtFi1wFxoSve39Dq$CyFr=6I5T}sSPeIUy}#zZ znT;E+I;7dt%5*(&p;VvjrX?kV2Nqn-s0J$d(q__~7<&WL5f3YlUmbX${9so?2vH(u zCyct?|8Z}KaA-DXmLc$f6>yzZ2tn}Pye@#KU_e!aiWCP60zd@foqA>f+yGs3udIRw zA7}C_wD=K@<|F2=L4MpX8h$(Em0M(klV)`jLxW z^lnjU@;0A%Xz@WaK`D0zhH8m_!&e|^je^W=KPK4`eT{PVQ4Go9^|M7H8Y)? zfsEM0vh4F)&+N^%w*b!dx?>GA!xSsX`U0gsM!3pLoA7q$C7%4$$RVjjrGIyQ#@h%d z%WU5Fali_|;a1d@%;PN*U_N0^mS@U@v2sYoO@He^m#uLiwvfgrs~f$(K0M(cUmYp@ z9u-{)C6CRA%CEQsi}-erCzX;r-@56&QtQ5Dc2lTZZ)+5I>j%qZVAakI%m5;7Eu3sB z9eQ!PM!(M-kX#`Zs4I_ynXKW5zTMZGNNo;$wIO}wL9_&BIyETcG}_X(0L=}NP{{Wn z7;7$_(B7GGEp&pAc>gGIg&>>RG+4Zu;%H}J#V!3vz=UW6r1C!UN#`ZIwD;=z?s4Gn zr%5!8{SB>@!Luwv2FaekQQPRk=Q+2TTi-ZycMHGIdRO%rF&qTeZ}@L25H#Mv%8QW_ zviCVjzo5w`$Z+bheaUM5#fWx{tUokymA6PJzdV zu--GYp;=qfsqm$A_coNmY;yi$T3RdMh>2$scF#D%3KgOUN8yd=VN(C#!K2@C1F0;+ zrl3Td5g}fK{xS-~&E#)c7a-qE;;ZoQZB|(Q1}XfTq^He&q7Ff&8CX;xMV-j3;R<~D zo=G+9AIjaMOAv|NQA&7cPIYS%V>O=1mI$}A#Ap7j)kQ@9X{D^#I-mY4=uY{i^Ajh< z^9heTEwgl}Vivu?Qq2%CVwmS*8R#k*L{rFn)V=@3?BMJn;AH&ogF|>KKw67EGZg6o z^exFkM@Ccw+=;HVLgOU;>X1=o9 ze}N67ydgOuISkHA$gj1)WeK$aJ(STKalAR%Ln`))1>-ZJ)7Q_x#q~2C9A*6RmAfbp zV8W~xvRnsPE&N+qBF^*qoRR72mM0ZF+O~t9rLvD^eOp#WgXNOmq+92 zOSAElC0_0r{xYR_mdgPiFR5B|4Q^rX&oxCHwrHep=hob8L)*T#pxsUc|1EAcM(&U# za-clTD(ppRqe`nhm3*TRD1b>|umyzx^&Fl=+OIklNhW|fJvQuezvadz&6VW{?ja;9ssr0C29=EScoV|Mgmw(LnhJ z1&Et$I$<1sr_ zYo8(_@YEX{XbZ@LhzUYJ#V*M&-Xq+ zR6g2|tjZXCh-oM&h#x?X*e$PO!ZF}7Jk`dP4!XI{$Cq4JBW=Yi3 z_;Co#(2Ft{1GRHgc=AP2yD^O<8AfGkR8cNWO2?m0As|UY(Eh?gEq2zWIWNzKg7wUx zYZt~zO9M*c_y_IE5&5_eEXF3L}Q}LDT=b9(5V>h z8hy53zZGpEK#Wwa`e)n_1L zEP5_K(cX{4f)k%I^KQAaKf_wlIi>b94Egj!=WO7u^V%B@L7LdVa2$44B!56==UTo|gT3Mx!V$YEHOmYAdaX9xn^JC-O5 z24=c0HzA0!{Y*w8Gwf>P{A3$dzHv-2ZzeewENp}ImO`Z*?`3NElf~?hx9fFgn6TCt zE=gZyb0?Qdw41-+G_h~Gb-Cuo1LLBOT2WzYw+Hfu)x{n=C7XwQ&VmCX zBulU=4g~4@)F9o=BS+YTKRey8LQW_iH_Ga|9awmMOS&&r4nxwv->hbqREj={-fl5G zHsh%f!~avAJs$&zueDU1p?hSzI)Be*Tv;3Z3seuO=`((jaNOB)N8%cZKP0!hymmg}=5cp2Gk|0fH7~e31?aRk z!OF0Jt{`+>G6!HY9kwU{)p|0>!FPAoVDvD^E8wS$BOJaBLsjKhjfL_a|K6^;bd~0n zjXxlxhZ;N~#D4o_T?wd!FWPQtC5Ot1GNZ-YpaO~6*@%8YZ%TMcx-7PsbVX>=j9EAS z2b8qvNYlQi&+DWV##U_&o&!Lv{y7J%RQ_qVPpIdx=*G8(G*`vZ~* ze=aK7_Zy@{5%7iV`9*YW#sZJ8%81an_>SN;JGOuL8oUC;X)J+oOF_$!3)OkD#d55v zDs+%&fT~ds{d5H3Psizd7hj{`^sl7x!LBf=%XqORy%U` zs?h}ndG`gbUhDQr-8e-Ctd`o8Lq3WF)rJ2aDkU_rSJL>iI0=*k+(m5pE2?B+e8mc- zP;)snMh|$LeJJ7r-!=I?#-lhon8Yf>@I(pz@y#5VDeK@}-`GAxc1UrKkGo{o=Nvr~ z?@imjsvP__XDUWWy_3E=*$$;br`k!;MiL$_iFy#o54i-V!{ljNC0~g(PZN<5Ec~1_ zz7fPD>eDLBdyH;M^I$TX*@czlcNxF@1)2c1d-~qF0>$ht6Mb zUJevu$XQcpXos#U&(}gun9 zhKwEz!E%=Oa#(l-WRnTigR;YMHm4+Yo=z#HVl(j{_7`)l0# z7!wUKtz0i@G(9sdxdIEw!4)AuH-!tJ7G^_Mvwm7?A@&cgB2F^Bf)e90cFgyFW(0sP zYf_y9r*_0@e&b&_lEA#>+N4z&@F`RT2}ecRy#)$lx}8569C1m>)OVF-iW_~MW@%lg zcr^ChXi0KOpg+%EBnt{p%LSVhmE#+xq;tgeea05jb5uupgM&PxvhL@3bH?qA;r} zN|wSoeTitr9)qEc+(4^BgR}HlY zdmcCb%<;^3Gn&Q&=881YBOrMC*GC@E-Dy#V?3zHFbWFi_`D5|(?&o6X!Z^}+VYJx~ z%c+pNxlw@~p&uIz_{f*%PtPyrg#&Rmo z?zc2Mv!f5bi&-A7%%l=~ufQyVsX8Za<`rKm=U^zPlY0MY128SFCz!&N3JBL^rsw&Q z9SDFQ0gPNg4uJfcq3C%GjK}(dj%3o`mK}~SP=<3E$odeKJSPh`2a4k(mKb=v?lHP-v*b>dh`A>MP$mela5YN)*?(_X)^*zF_ zvA6Azhb;D-Pz{P`A{!BP`CP==pWt_9KH-J^h>%XPcAoS=P{P1JBCa_Cr-589h^$lx zTCX&N9KJBJx6xxQdB~wM4lHox#hF0_0^gw#LIJ#nd^mr4pf9Nl6Zwl;{l6J7 zWimzv6N!|LmalwsV$!<2hnCs~SR=AsATN@*6BM~W&+nvqu za%S+KsuU&#Wm(SYg0|Pe>dWmqVK;jzpV^fTqGNL9E8N&4=pf)?FA4o(65Ob8QNDd= z<@g@`{ha-Uyw59Wa_$7*`t6LeDBjYgd8x!T^#BIO@8Q=8!pYZ@f9wAlU*DlSZzRIt=CdAPnc%JghXDL?B>F#8#{a()`Qt;TF z$p*hl5CMpc}N#Kep_gfB)ALML_BQ$v;p(^3Pw9;EMnA7R-P0gFdm$ zRBL&(isQRq9xvw0Zm+m=VB43B1h>y~tGzW-E!`bn#+C^iLGEVH7>#vr<_xtn`bw2Bwi9W3KyO&|8MS%nsDts}yOcz3-E;r)YXN1Ws+l^nE)4~{v9EzHC_Y(eBh>{CDsmJ?Z1ZK?sAG@+G zy2fjVn(cO@jYLI(=8sbNZLHFggt_(k-$;?J6}8!MK4u;?S-72I!CVhWp$!ff$(Djl zGVf;8@|Hr8?d!6OZ16B71&@&ehQCfQ3H6070CU}~?g>n_*cku7BbnMN}Bd4c$>- zpQFSNoe(29(76;-MNdPnzzg5bRCZgw* z9~bDKK%k-oPg}UYXw}Y$h3Xm`4eh`$4EV8ZQ|JH$NLXG_eO<!`##I;$$jTx#1$@${XX#FUiEVt zDrfO_b+@QYq+HPuQ$8aHA%|}}2{K2^OwbVq81NX57zX>|%*vMZt>bfYJGV`6x6h~# zYqok_=*hW$2r0SRYf8I0TKk-ZKz{sW5QHb6z(~yW2VQ?@71z4EHoz+ih<;PhhOB`; z0-@}Iuey%wO}9vG%xzugzOsScw0`T}-~f{rLw+y+$E|JcAAVMf8B#&EtR&`ZZDFM< zi67}o@+x~6Q7~2Z)fol*9&>{+S^)HR3KxZdIX<_96K_VHqn5386-MmAQny>eQ`4Je zGgixLm%5vE2T28TEtdD&^48(73CeZl`~C6(Td=NQ3?lu8+v#<)Hwu%UB%wjP0RfwzwS0XG&Z8NsH=9r^u#w8dkR^~lZ-2QPp)6y zs{O9s$!%xKDLQe}PY**S@qFX-;`$1+F%$@>BH#K+Y2bk2sEq_tfN zad^c}VaHY;aShi@jNcbG9s~2SkL>Xu$*?bBcV_^;hQRM>a)E<5nxcpa#9;(o4`$z8;MOTObASXD|QkPVSkR!LSeogE% zGezTt$^PDVhz|9!6BPZ)MMER%jsuBHGvz1!WY*DQ`ThoC^O|4L6Ho1T15;ZJe>~HZ zrb&j8gUcdaTsE+D3Koi5gAJ>>?itsryY<=Lc8q02V6=M#j$RUJaNtAQfx!$CF?jDDuVZ(7F3}uh7r*Ok zd_qL#LrQ975PAd~R{dUN!Z*I?oDdi&i0^jKO35?BUcA79hWsQeMcW(cT-PcAu`se^=`7Kn6b?+iE>5E{FY9`A|WvT9+CG!cgC7t z?Phv!lZFb@wxNk8@U%m+IWY_XC*iAN8;>B@Ac$!!h46M-$}UlM29=;tS5Ylyt8|SA zlf#1|&>3|`6flXci+8y`nnp-$&22qD1M5NiaSM4FLG%Mg&DxNvLT%;4(r4kn1Rq`eZ*bo*X1cK887e!H4Nvm1Wen%;k=Yu$^=GO z9^o6C(}05Tirxr~Vk93A#oc;R6+{V-xC$&@oXA~o$0#B>@CZ)0a+WC&I%5)H=aXev z^LICY*f8vDw$O{%<5p1@h6s9Hh&8u!FdKZk{31?8jcyEKoClqI7UYyc#(6YC-{DZ4 z@9&j6FiI0Mg9!>Q+U-$gS6)` zS0r|dVj;1zgb^nCskX}ly@c?o-6Bzjc`-*H{TmucOu8<*V^Fvx%q*=u#UZETGqwvV z3=aV#UPOm$ovuCmSxeW%!nT`Y4T;99U+(X@21eL&{?Qi9yrwqcd7<~3;4gFa`I+|6 zrhG6;e?4eEb>fvNyS6e3)mk+_$h^O)|7h1y@VK^%U=*%KDoensQyW}Af06B}OwP9l z+}(4uN-m3sup_Apd8m(YKWd;l#PlhJ7JhLMz5Jo28~0ceQKsE$&Wa1=`KiuN3=TcG z+p8=|2!OM5A+B9go?!xs4|=jiN-`}u5X1t|P#S9dKsZ~_f9Z!b17Xtbq&=*nphF0J z_4hZ{WGQSP7y@2ch%0i%nb8dTEbIcczBC%mtLK3UqTS8sPt{%5sT}VrD5*{oZmC;6i1pXw!WL;OZ62v{zD5frW5tS(2OSUttE!%KHHn$ypO zT^pfh;fYl)<%>s%G8xo#D!ca*3Ut$>1zhL*8nXW%Ti+Dj>C!zNPHfwDGO=w;Y}>Z& zOgyn|+qP|+6YKZoob#^r-Tbef>%De$J=N9SyOcsW>|gZYAzz6GleX~Y5bKmW-@_%d zciurK09*zEyTDdf0KlO4^s^N1rE%t_RGs>F{?W4?;}#mSAk|bgTV!DAtOi@UlXw=y zlwCqM)FlIG7%3*ik3^o3?n*D$it_v9S+M%yE5LRPHt(gt^&)v#4z2l30z#qoK?&K$ zlc6R?dwG#IQ}Tm$#n&XLOLw$yXd-<*tJE79oHig+Mcl?VH#H5 z1bMQ4%)JAShWag#WC}$}WT4aUq=AZvn!Rcv6@UL=WIPMZtw3qxW-V%kInJE)4QIS7{iniE*b`e@GOT>x%u4*1 zL#I6+xb}F6qqkInYRp%2DANY&-#SK?itey}XR(t8hjRe|Z>*`knS7D5d*hf$0YBoY z875(LrY7he`YfpcFOL|Ux+;9fwFbmuiVLs$u+*XlF-oG)I2luTG|(20Cus_HkPBWr6fJ$PG?2`Fanx=u8`UzN(un%^BhgFr3hA1fI53{+?oMxx3@2 z&2Qx^i{3~9VRU}Od64&EbklYWx8rg5YECQLi|BV9_=tKAqC_DS2dM$}{L{cr97J7= zh=P&E_dJy^fPuTQlm26H|05_3A~N2e`Zdi!Vct&nLm92NvE|2mQw^ecm2@rJ;2Ac@H4e3MLkRvFyfvbkID|%Oc z1>j^ON!@Dz-cc9h!VL?#01H45$9V(W`{aJli3jz@%6>tjNvIR!21vRv43Pbfq5ffu zdmItvRfC^&v)UJ}XwisoLf>)39uQDZtcS|Qu8p29kO*jJVbl5`={KDJqbt z>~iTuWyG9WiUwT$cYPi2<=MOb0(C5+QGuq!!&fXt}ghCM14q8@P8+vX*7cF z3)}Q&D%q;nJ6%*ZnLRgA#X;}c9lykNo*iOwgl*9i2jvm;7vwG`?GpG~K6LxYHayMQ zKHmz*19mP@)hfr%CU=*0 zdKKu%Do1O3_E*2OaBBUU3+rJIM?5Zx7t2@4UNyt0wic`fnZ25Q3=WTkX{K~!3N=9# ziE^tUFpj@yrWt{-+MJ<#yqo;MAK|Lt_Ifo#aX=A!4YVb288An4{53zKRl;)-y|vl; zf^aw+pLc5sTf_il@-1(f*Ns95bcr%I;sYist~r>87yN^!iS&{)}0X$PK=&uZzA_7HO7g|D&D% zDOVc$)m6>FC&THHe}FdR$2E&cnN9g#lgym2%(K26)5B7IlBjw8y%dO6lAyN&t7}<$ z?AQ597dUv(u?jkx1i_=b>>vqPLGrt3C)CG1IX11s*KYpf#P({Ia~+yg!NL!1c`+HI%!+96jf_pAH>2FIcOvC0go0k~?t{NO)5VhB<7`TE+_=z6L1LHL|M+^klEh z@!S?Q6YtSEfY~ua+L)?p;-HQ<;uR`bhosE^-GWK||27Epw++G?HX;6h+92y=W1ouS z=D9vO@Xz>C?0q&ZKZ)tq%WqSZVXRSaMFNm&hc}AcL(m19qA#Z~Pen6+3pr{h2wRr{ zMLL0}J97I8aLLShlRaDwe<2d0RgjJuH{w|f+1S`Owg50~O5`(xmZ}#Ed&G+Sd z2i7xc0Ybc5LbHW&&re6SScgV+4ie!T4AmWfL@Xr*9=s2VU$c1DT0W93varUc9OREi zhk9LJ#m*1hvY|Ig+fSeCj4=A^{T&3M*ZZ`_YdAZSF@%`MZOD8j8GEcHW)$)v>xS1W zQuxZ7)AC@w1s3wUD)F1P($v|sNHKH2@?UOy?z<0dH11~d`-!)_BNl_{Hh|0lFZyN4NX{Z^3?mB`z;-M#B| zc!czQ`lN^;-TEIHvn{198;Us6jz?mujWxHzeW=JNR$GMnM8qoP6~j}^e0$ROfLsKU z%c=@-0J@BX&7#l#?2jTC5%HmjKgpfF?uM0(oqRY#6ywS-rg;1%p7%G7cyVjyH2kmy znMD=wqfOu9HJNuFs5X!hEHrz3IZO!v6_Tye5~0rQg|1kt0YcmPQpq5X;)?RYr{Q6v z7CJC{%ei1E@O2;WRvk+T_&Ivv{Mn+Crl6P?SUqZ@^uv9)+#he1wSc6ED84fbwKs^} zaUd4IFU0lU@0617(Z9w2WHYM47;5;iW>$eZq9v&=mQoL8gk(*QXArwb7kL~OK!E9==k<z}Fm-~M zL)ku@dwsf|S7@peJn*Go!(KndYm8ka9811>W`45%rFRj6MbAe1! zEA6BeyZVX}{IrV1IBCh=e3~@PPC(7;SSdLt20_uaDhWloR%Amduppd?4X%2;sr71< z-@DJF{HhP&&t5S6-#T$IsqCI-az;Q${x~+;=^Pa&;ga6VD zQz-)m88fbeBn)vA`U5(Zw2M_uvg#xkymy)>X5l`~u~!pR$jZ>!MA)5kzI41_h2KuY zq0am8j&j=NDs|}2h1(6CIp5_!aQ^PEEn|btjLDf_0}?%3>;=ojyr{1(A~{duUnHt#qJ;d)xa0oTw??QWQ_r-ehk_{R0_%4%<9-3zP_cZR8*6DlFP=Tldg@bx%;>Pb z8}bh~D-x_%vpa~4<_N#@9%8AU!w!H7Cg5#xGIR4z1^H#h>|I(C8EAz$b!6?E@DxP3 zUSW;N2=zdrhFo6R`Y`?ba0_ln*~|j*WyLf$5fgJTdp(TZ@5f>qxIgCVG_}PeRRQh| zu{CmJrw!E8|q~vOtwj`?nzMpjzrLQ#N_*U4DdcvlKd)9U>k9MWxqrv zY6o@Yl6O2_@lLhb@Ey87kXo7~dG-KfD=f7d7_{n3hJx}Ytb5cr01!mZ7{wCGrvec7 z<&Bire6sStaQ?TymQ7{WVn*}?P6hN3RHq`aI|J&A5{`8ple5oft6I3!YaWqZ+y*2# zzq76u_P<2oMzdCT;h(>_G1%(1!iX3_!=*ow_|BK{I;XUtHr3I2Z5RR+{^H0g_~>c9 zZ19n;lGU{t5`WI=k>+2kZQWf%!{`q{yR% zQZ5pHq6t}|2-!d7QRTUH^PbR_Tasrj=C0U{qN{u-w*-h=Cd?O;o`0e3lKR0Hsj}1}QzI?m>2y2GdKcbhGU1ZGwI;vZ3KPhP#s#UX{3 zlZP64lNa(78X^&+Him>v3%atkQ0#AAnI#cODXVAn1|CkSVrccZ__C#rC36TmI^dA8 zTIgXNKwL=*PU~`D7?#h`%0b|o!N#FWDTW*~taG`q{648)Rn;YB_v6fMJ?nD#ioS_y zVV-9_7oF4H?ZE6At&kjAJ+CXR3y-S%O?P1zO*f*pohqx1=jGCrAg))?Mm1DJSldzv z2dMO6(aC+C9pv#RGg`F#rW|mUOinkfaNtuN)0N%0id(Y&6d39%tfs-?) z@W}lgy@|X9I(qaW?+iz+#QG*vCLfEa;+Z1qiqg3puEv9Nt8{ z*Xcs!^qtWnSI0CkLYM<8vz1UlBW!F&0?0ki|Kp*u&jH_TkX zHO4xBk^At=>whavo(CdfUgVb#)%rFzG7H1T2@JIMp<@R> z*sq%+)LejD{MGBWQ!@x(gKH{WYRpepVp*jh$cRD?W^(r)0RoR#wwp?UN1!8_%`wrI zRnuLo`G~Z*JGLsToXG<;aigl2lFJ)v_q-mz+9biZ0cU<}5KYbVpKKM%AXHdQ`6yW* z|G0YWiNC%4ci&{9?5uFSn*tTJbY`AgMEj6si z&G>BKF01FCT>%%a2y`Z%Ll~yQe_AM#?D7g-6`^(!m@9MzgbrRr?U(Nr>E>2-G8Tbq zK<+=poktjv4c*6+iy|My66IvztK)p;!^tV-MR!~b5u{Ctr3VC(Fc>{K}*Kq}U{ZjXPGL#CV+4~jR^3s-i-(CuwG&sSnuKm!R z%n31whr0&0bm-SdS`E|o!)wG=fAsR;vGFutqI>og5zV|qoMPdxs#yZl{edc+@hAd? zHO$cryc&9waMJUFngtGa9KFR?=&02LOdF9WWvEoVQp23ft%dOv0Rn#1i+vGkHaD5s zEwC5AE5xYy6_rvA{HBXihO#Y^CsDJ)pI!bqp-zAFmWYAgPi?QHzZ|=vf!S%yl^}v8 zUC4eZE>a|m3)P(FjQd&l%o`25@8-4ew3~N?<|uaO!z(#{0zlsL5kb#SDQ|5JLIbsG z#6qezVZJNN5s#DagNrp+HBh{#oMYdmcco#vmR|6vga>o_k&Xn)=e&PzR z^{n-{a^@yTf?Dl@d@`KbnQ?0h`Th9M1`*i!|27EBw+-T>$w}~k+93bKz8Ql}se8*d z5lNvv5vK1w%~MTxSIFE$4xZgtVO;n5utEL?w*6#HAxwKPBSUAlrz0^k?+2^|)21@X zr9&i=U|!CLO}HRp@$IBr_bpMDhathaB!QKvb=jyq=och_HA zQr5|hAWJ<`<-hHWFoC1l|HHlt%8+aP%jUFtbhcneA8V+N#=N*Ba;SB|(K;yFDs+^F zO@1`-B#>v~g)#i=^3MoB(~e!TD#XXpRY$tFV3*KaQ?;Ki?w8nYj5vr`ZHfVUim(XZ zN(S-7S4hP%{|*xJu$h2R_ageMXR%@yMhg8`K@v<{aB=9bhd+NhuIPt~cKem`fSg_A z`R6#|`2;E{j#%V$p)_%J39$x=Kfq#b?CySx4fFX0^+NyLU{_LxQH-F^#JNL$GH-uy z`dU9|%4%@#(vq8pc{u^KR6Pxk@Z~Y~+x6Mz*d?>}Pp0ecdAG(efKJ9t{Kh^H(tm+5 z<^BZOgkS-!imS-5)7;*@$bg*N;{!sUW)x3_#WwWRH}vD4{XUyDKD7Dj!1+S!Jes5q zqB5}Ei|Z#UBn0RWsd=nR;r9s@4~Y2~-t$5r5g@WP65c0H^LteoX>eF{(67v(5=xE` z8MhR{)3xIk3QFWDAnK4y$AKj@V4eF0hk!vyv#F9lQ1-kUB1M7Z6Kuk(s6s(3$?Dsg zbumfJMh>5=*DZqsnK4@jK@#~euaT)YQe`Em>!*&Su zkc%RqB9y>B_~1s&4I6^6p;D}lg#q&{= z2(U=6t$+PUz0T0VFDY5x2xXIALeuE&kK`a8Pb<4Lq_ye4qaMOER6Nyyt-&Rb6 z-=c;}i~_72brP3`5P5jjs>ILvziTi^Gq$nPGt1bOJLF|qva>hY5L zT*drPU?AR;W)o(YFv4?<0gAVYeBO-C6kOrLo!86Yb zwr#=vTRHWk9m;9}(&)(vR<5Yk5R-hgHvCoAj}cWk`2zFIXSRr%7nR@^#PT^iW<60K zVjX7hseA>}txyI0e{fFb_`)XYLJvUovtw7epsN&=O0XVAKw8DA`0`8l2$h*uj?&k* z3X`76P@O0&F+xsje30Xp>YL}_T@R_UA={bL2y|OP`AkdPTNtaS<$bjo;2$zF&UWxs zLx);SE>cfxj>oALND~tQ60iT+izBxr<0hg%l{_bkxNTaQs&~Rnf}7WG+vq#J;f z?24trZDaWPPz6WmOuL61HJZ&2p1R*!+1kaosU6;?3OwV1xr>@;_KS}-`FQAZ=fYKT zXKd6}b9bwycfRR3=)xYcGdAZ9BlVg|8Hz1IKrI1H3hXrobC}%VhW|tCXv|Ez9VAQFR;^rS8dy3=D^dQl+~j*`~k#eG7B8JBV8vMe<9s zH^GEzR8$%t$Y#eOzZ2;^fME?uQ|`G@znzt%J6@rIT0=aJ`_lITSM@s}o(fkC6sLUE zJob6H0Lb;re$4ro ze8n0m7R?ajC8iVw?`&ea=72QF&g`$`a)JiOH@vZQ$cby^ErrSandcR_Z7w%PV;xT! z`h&SbYwV43I;S?H4m6v?u6eCe&(4YEh3BkkqBDi^oKSZ}3aqkFNpu52E!CE=hXkNN zq8EqNS|u*0adgorW8{V3n#C&#{(F+=6($00OgMj;A>8+*vBQmB<@$wc;o~Wkz;=&h zsrwvy-{GE5MnbN^3JkSncN1ra$~6Dfp8kG2Dz?QP%~oeXMwW>HM=me-l?Zmqd?W(< zhI2gYSAb(scX8C^eq@~tbI%dulcneEfza)oVT~CoW?8N*lOZr}!yh}z_G!ClVbU3q zCX1_u-Y?^O{iZ)cQux|;0?aW+3#B!%`NAdRrgWSk8jX)-#xO51zgf=`2&l_Tb|L<< zYIkFp!>(wQUnC(CWY&|-olojSO-=;Qb+>`}6Hfvnz4OmKvjL{n=0Ph!J3=c0(X_~a}X@ea?=hfyTj>(Ht%pQhwL z2L>l|K(73<@qEF}tdI4d?B*C?RyT6!;`6{1{azuzNI4bl&pZYf7k@lA!HsJdER(Zn zfg1^osJfKwdlDNMXV34CS}!NRfLAl!64V&Ua%*!F_> z=j~m+00o;7(}2}CWcK7{KwO=?gd)WYdWP1^eB2}uj<}B%V0Sw;V0I*+<~ptNKkWg# zcHeiGYZsEN6^Kq;Hh!(=Jin*i?z_2-sXZf9k3uKJ;%Vji3>A5V785#uqUG(fW6qsd zNFY*CL;M=u-1DcF-d^CZs+leDSzpX!B(fSZem91A@*Bv_u~xmIU|B?JiSgf@E!R?*Esa5j&k7agS%< zF)B%~4vhGctn!YOoi8qaK2Si}1g&U{GvcPq>4!)7XCLZ)u66F--!C3_fClI3+WpW{ z{6IEl+qdS|YjttSO18)l0~3CECJOL`jz z(hV|&_KinCoKYCt&}cexCqZ0Dgu;=KX<*Fseki)V2Bo}Q5T@l|65xjPE?Pe(7NSM%v00p54Jz)Z=E-IhBQz~UBf;A zg|$U#oWxBAGJZvWKXi zp9t2nB;pG}q$GqZF`2G0*YnnxT4(Q=W<|~olOz8b|8uiu_Yz<;m;&492eSAUUn$Kj z8sy3FL>@~}_kLV4ua!192bSHRE^rWSr>>}|zF^nt*PBQDjw}H-KU$s(MCJy`dpZ7H zF84wrv_Rjf3&gc}swzBf*z=eyCBjJZ(w{j3W0a~Ue>A+fv9CY@&JVEr9BVY`U@30=g6qL2Red93RrY6h3GL?LkNR98Ul1#zck-3Tb~Fwnv0u*+ zn8h58J+h^zwBmL2HI)8jZ@VHSz`kxw>=+#loYZgkPJQu$WkPrA>If8_fB!{F#oZ0{?DU_KbhPv0ES$hq?&HfnC00k zyaE}IV-^-p9jO6~<5D^%#F71wj(l7)nnn}coH0ruOYv3>*Ip30bh0b?`Y*3Tt9?&} zz^UnJ|2|r_@&f0?%OVh(wu!1k?*SYWgMP{~XwB3Fnk`}=@phIyhfsI}Ct)BfNe9IW zMWgc*Rw@j??* zvF3HeaN{emZ!!5RRmhn^hRP|pl7%Xb9k>n?e2SL3i5evmzYNj?z5ZMVQNl^w{kKsG z_=2AwM}2FzQv8uTH`aEa6WA? zJ_FU2se6>wW7Lkhg;J&c--)|b+`5T^@(p2^xX3#(4f=G5A%mc~-qNwFAwUM01klCd zJkjB#56cUhd4};rcVl9w-VieCQHk`1n6_2_$03aM{u7%b+H40a5!6dFx1aGqJ_9+ zD4ZYdlg|?Y+y5=tPcjsS|HlQ24BS+E2NF5xzWn%m%BVjMIQX>G28_=z$B3kY8SQ0g z1LUHjR}pjT=zsyv>@=fX_3Q>w*naWQJHMQZMw3~7OMv-HXD~xBXZJ=K3*pt1c4H1% zC)hv|{4>LyWT843u`$YV2r0j<8hh!JKt6gzfvE;f6A3^uto_Y!SEt2{z$IPDms<4# zy0t547-5(L2Ji%ga)X-d2ll_)Ao!r)=Er|Q!LZ+7k}FN5|Jw$MhxQj>K~xbIer%cy zbJB8>@M$_Z7(C}z97QbOo8s@^$G2*D^Jd0PKD*Pb``yyCe%+!%dT);F-oLe2%@hFd zP6!d`&_FZ3wJ2aVYW>LLr;|V9NJ?KpA2#5nZn#8jXm`a-1QNHh(EIA4n}r5n z2d==1al_F)LJ7M%J!1}kUohd03Aa-8!Vop5Sfx7|+KEMob9V-=s&a?aToSJ+W)JF8 z#|4Je<3@e#%}$8*#G=UA#c@IE6`!r*H5=aJEssU1SGHuC+G)<o`KCrJO)mtB0GIwE(N=T|W z>e8`zNsRI$S~6M~AGC6Fe5Q9Cw@h`z-NqPWjElhK4RH%t!Cez5L(< z!|w*$|8l+$jOX?{v4hu5*jeIE;xjy5Jdp*K-XK4szp8bR4ru@ww1}#eHqevQl$7EB z5F2&$fsJ~@2oSQQ*A?8%d6G@HYd0V6zS$i~F5y7Gva)*WB@lo%lM<6e`Cqw_tu2bV z7V{yb=lji@==j+`E}1uBET5`h0yUg|bETb*nYl^YHsR>e;gII%zj^f0fpGdh;{rG8QISgZ^yXldGRX~{Ps0?#q6vUUjCb)AY( zhkKH51C%^WP-{o#+xd$C@ErS9WW(2+BYA=P6;Yzr&qJVgi(ar=A4rK`C_s6v(!l-w zsT4{*pUJEy_p}6NVEC|YvZNyzxq)+H70hHE4NX4kW4{P%uxad5FeLptV*Jf*RI7U5 ze&7gy$EuEQ@7RvxLw5i}nsKxLL*)&Loc|;sZLO_c)T>pkaEIwZrhn8tPNlFkR<8yT zf+!3+PNAL)|6)w99k>hQ|}+ zcODXf1J6dv|b)Kw}9btqXKQ#{LcG zhRkxnksvS?gjFj!2`Lx7<5P{Kx%=5{u4B_Lv+9fB+`=6mq8(m66q!q|BMSwqOPK8{ zH_A`qxg=?zXQsj4ZMgx@k77%t(f#QeUe~cwu7YfAfLIvoN;OGZ2bCjD_1Mw-i+$t) zeU=tmhRF+l-OS7c$6~W)HEk`J>PxZivnEUQMiEfhnsgfCH7_RNwzx(BX_O_(D;ymMeZ!1rJ$o$qpM$vW!~P75Qf$)DshLZ)pznmmR{ zeWpI3uUd07;cjLW8_E$0AJ@*FaQK(-z={&P3H?gx4 zy2=NwEWyz7Ik4(rKD|Z>xCR!k#*8DL`eqTc^h?()u74~~VdQZ{7qL8daXxTWmFTD= zky!`w!DFc=$8`KgmCp`9x(qA)Sx^aRDkw(4+cL%yf8@Ymm40Y1SzZ1!Ltze=xEv>{ z?Bamv@2-65Qg3-e$%c#$*BaMKB9kk28ekkXaj6x8fFz`gzK)RaovTM9grAfkA+_9_ zcd_ScBTD}@%*@MPpJEjy)M&gv&L^6xi2f-SYytZk#rHeYWb;9nXU<+J6C z;J8v()esl~<-`N@A@eUaW-!+^=6Rj%E53J4HuZbV!Im!^mmBxa5@g6MO`fyWhA}QK z7!u`4PkAf}tn8qxV;qASG`Hx%qHglLV}T|YjY5HCX#{kpj0(b#VnaeIo(S?ihf>Vh z)*2(pu24@V1zV|K5ckXIHr`1PEppsD95?c6H|i?$2V)C=L38&m*G5PlR5;|Kv=ia< z+=Qbk3qaM8PU-`9ozLq4a9{se$w8`2E z`M?iQjz!I&1E;R42g>NPkivZE4(v;G8g}mrTlBk@cXTo7Z!yj`<*hQHL%!Y5sG#5-Io4%yc4Cgn?;jdY zOJBJaCfHa|%Wb1QK3X9La+7_RTld=`-**)RNFGA21z6Y01+A6cJU(C{=QJeDwCzs+ z<6=!@@h;u(-pBQE`xGkKWq6_;`X^=`H7E-6B*UM#?^h501vYowxW#SU<%_P}w*BYLH$MqWHwJ;{}tK; zH8$S~IpV5=AtZ9gTg^03$Iv?SJ-N3p?8LeMxtIVc1G$cScmwe2wmk_U^>KA{RJh|m&mO0%evl3 z?ivy5y>cKbgjXb641sel@%;D4v7do|xU$#SaYM{}S~y?4e2#~BJvpu5XX(Gu=7cE? zYKX7UMG`UqkON#E)Lenl4o^5@&(j*?5Fl-!8%BKbXiA<7=j6-f@$TeDZwQ7}eWTWz z3!RnAcCxKPKBCU=HkT#cEaL#YwuT9?>r0n=-~BD7X#mOZgoEpqD0=IeE1>gJ6bTPEppf& zlFv|AqWS!&iKc^-e-u%4?MeM?@~}9H8`$y|<9i9^;@7QoZ=y$JmuAT$dGy zR-vTIF3H=)lIWHQG$8L2l+7}$f!(6ATzvVs;1NV~p)>1WcCPWj#C0+(>-BjF*d_YS zu)A{*oG3*4$Ie$Ksm?5+99NsB=Dp)hApTvkpRt;1m7)yv`!6ik8lHbRJZ4 z9RVriKxJU&j)g@O7CIh3{LeGxGXlikXl$?|r+CjL``ZEQr2sQQ)!KwSRY>v?P%v<& zhm6~(Ke?&nZKcog#7oB?8?u)9czxf@(VS_T%5;S^HzC53Tah1-AZ}96_~rMhLfGF4 z5x_?812UOVw2LC8b@AgLy0U*!d7F`)T?q!lkS%}_O+8LqclK<_rElix_M!uCD<%9W zlzMBgv;UJv0_~m-eHg99!n4x79VhIN-DNqAjus1g3>7q+B7~cgM(e<`ID-d9Gm%Z% zlz6wx0a@;$V3s2ROLzC-!4g$1_bYdQ_p2I@u^VUvG0PgJRYvn?D7bQq=_SkwcbzzY z%UlgdrvMb8cy`oZK0=f3j(vy}6k>%*fjHG&8+MCckJ_f#Le&+Q>oiXHs{VH0{qaQrVv7=YU;;52MDY|H^&SruqhO zCN#rdMh1&c4zp{zOvu+5zs60TCXuwtVSX)qXviWaHIzZ*_Ik)Q5~6biPw?Y}=6L^OWcB)KkD7RS>`oY5`@V{+{nf4weYD%;NqBO(4osC^(bMdLWV$bi2g@Wfmm^;kLM=fYTN)w}#h zS5ULVr!<}1-jHrzN70&PXXDT(AF?A^KqGgG*vD~#xg$7p+k%8zYlY5k^vYozm6jn( zsYdfRXh3V{z^}X|C1)3#j>u0!Zon%n!lJk!!TwbJ`#PqhqYGbUTYdz9Y;hQ#D_)C@ z7fbHzpM$Wd1co^trQvSgtNRX1_9PQgQ@s^3yad)XH{cHZB) z_n#O}Fu&Sx3|zz=wKI}nmw>A!F{itoe;`I1VaDJ!Cu3y5T}oRn4XX(QvsTFq5>kQi zn{`>XtJ6H9dj1478WgJj`7F0FT9ZdM0J+aH$c)WUs%`tDz|z@>VfqT95)wDT0U4+B zq0;|VD!!)QzB#5`tfIHFv+xyac~0fyA@3?cLW`cAi!#pDEK2jsV`kWR5;`6{%;%PA1MYkyD*dZED!Arw%-BVJf!HVDLS;gZjS1( z=g9VHq*Q^;`^Q=CBQ4C#HZKJc{*|8$HAu{tp;^KpM0PNGOUnUC$2@*J;l=x6t2U$P zcUY(`Zj?*NPDv4Kn<+*3=$HSJHtVsulopE_QdD$Yl39hRlOhC+j}tUGg~2$m+JHfYSjccsUjDGqI&kHw~jaW9`Mt? z3oc^vz`Gzve0IT^!laKc_~4tScy;EJH+cLhdSNm`y3)X*%}CJ_mZFrYpadjqLewBK!R6%h9Tio2~lALjBVi-BSg=l&U(B9 zsKW^&p2nAi{o1~rTXWBBb6n!P?FPSA>t8B}ZX&F|@{Qm<$t zfVG&9QB-z;>;yvo**AVG6O4fd$y?+od@N%E*{>S%v4aoj`%uOCAF@|1Uymcr1FXhW z3(0slT%mdbkf}YaQZ+)vl_|@@v_tI58E@vyTk2@btqh0)DJj&FPM$fkV=kNw>GNnG-}iV^`=YJK6BhFjlPuvKd8@RHK?Pwv?Q^ zao(Ez^Nd)6Bur}RG#;X5Q{dhltnI#SujE-}c%^Etqhf-57#4sFm}4cM5`~q1 zelI{LeY8FI@w@j8H>};$g1MC$Xm|DmEm2C5j*!=uj)GiAA{Fjj>_2kl&LAD$xkN4r z()He%%mrQA+F6gb-q1a4a!bKK%|%w)VQudhoV09A`dPE!8+XrD1YpOJJFHWic=Ot^ zZ79d|&PD}4*3b+X_$MM-*5^iNe(WId+5>>+HjoLJCCVx^^)hz74tI?_n#BRO#r-||uYPBWTfq3Im7r*>>Zrk+q z&&eOEbux+!{xIC{INU9mSQE!JVYeK*2w~8dc{qlDj2q(kv48F&u!toz{v7{XV)}On z!9oi_t`0x4oX-RO0I~WUfC#Gvz!_dSnhJFZA=OMw_7}YEPDE>>MRM0-%r{X^3!{hDcxWH{Ebee1W3$ELAWi z`wIAm^Yr&GKPUIWcE68^->9Ux+AIB;HRb+^QUc36sxgv;sZ6e?#9i|vZ070Aw2VuF z1(Ltr$*M41)o3HiP>Z)sbTbuyxPxMiFEQ2K2eWYky`jUnqC&X?zo`hWBk>q^_D_r) zy^7ZvNX6X5I>rO?7yQEjC$i-5G4k#=C-sPhA@>>dXp0+Zz50 zxR==UCtZJ0@XPmm2yS@&TbY*V^^P!2?Yu3k1sjF}iz>_f0@;m;;}!n`XLPyPR`TOP zEczhCFJ?Ro;{S2>PeGQ1UDqzW%C>FW=(26w?6PfJT~?RvsxI5MZQI)QJl`Ap-G9V) z^q=I4Je+aQl`(V7k>d(x=}lEr51`SI+>UrxcW&5;$uv^xNVNv$eeCGU2?zY$&y!nN zDlt<;vfg5qYk4Cx^&615zArf1I0{3pz4>KFkrr*$g8$;BKmxR14WtEoN&KDHfG**z zV=;%A$ffkVT_-oVM{ldAVBj~zS|n}RQw#Qq?M_!|&&~W@#qw$i2VX^jCyzAT2^o>Y zXxrW|`o$VL-~bND)w02C5kladiCzG=qY$&jkqIr8|AK>re;1h6w zED5T;aS9r`4;%9q7wkCTdz#gwBk090J;~9UbL#Q^daD-UKV8g1QyR094%b?Rt(Bx% z28HLCLu+@65(>Ibc5Dm!ZeY<$V80{-C`u9R3j92s1&FuKn$gtM1~{G>*m~~yiai4m zi7(XCpr*v`<-~-UG%peEQ`?EePfO2NN%f7a;h+VwRvAV11DNR+5psifq(VS>jM^Ye zn?HwqT#s8BLi7FvWw^Wl`;(S7(ZJKgi&QAkkplIfgpwyTRoa z=#sIc@8vOSW7#jLR2Kj-QZ(Mqevsn}{vVye?+^5Jm33DmI;o-P!|ifOSD zkbDcP`9h&N3vD&oL9q)YI((-rLH%lv)0^f^i&$)f7n z7rQHoL2S8m3LYXB#ZFvcs#=|gW$uXx)WU%RC9SpuH6vG_ruH>oclqc_@X;^kiw;bh zzVj`b@6322eETX7(r6eWOdiJU=I21Bu-FzH3I%V&h$AVdAUSd^{+bYkr5<-I2cjl2 zAGL<=bm-*y&)@gow2rhhGR@Md&R&`)-sa>jbUnLlJM?y{`h{Mth zvy~Rx?d)>e+2>1lJ2a@g0!{9CR9Wz%{HUVc0y3TdAs5x1Fm`L-T?*A&-dzk|ZwWep zt&DMEXWqCa&SqNQshiC|X-2ia214$}6{kL9U0o9*!>A-&C-Ij&?68=@$0sC|o94t&oTUt{fOWIPJ zBLM;-_#U@Oma=q5T)<=I7bt6ZF?vvHzz=Yld>+VWI^kMLkj<}hXqSu>?&=sp&wPSd zWtqf|Gk-C)?6b^zM}hK&wv$GA^10P3_4Qz-`I>U6)+X)#5zTlel1Cev(q-mWkE*QJh!Yz7%c2g?#hNZaw`JcfBN_Xovzk+!cDK2-o(1hqMmY9nmiL zTpLJX2QLgKq3!T^h-P?E`iGqq&NL+#qKoR_1`l@E7i-3m6}QWlY0N#IV#PH)(P@w# z#o@QE9&iT!jby?&3NO?4$euh1yCo@EE7V)w0xEma4pX##|eH}(*AMm0kdS&Ou)@cVEG zXG?&EHP%eJS+pk}6?6h-#ajChXa{)w(0CSub=>_ZQAdN+4ZKKbd?{3} zlmOk=4B)XyRY9jG{J%h;X*SeZ1|9{v=9mp>o>ww#U#*oO4nhf59VBj~f`ES7xw=!c zFz$GwL6DXgp90VoN~QVBrBd+c=elCy*Ir= zMS*IX4%~ZNn=yt3__vD9$|#WtoTppRPMnTOpWM#1eeF3QzkmIvXN=(ora+q5mH&wE zrf1a5*w#sYb@4)g!((ZQ)%9rdWGZO95&*%z%l^^C&7KMq;Znc#$-DjTw}yOycEtl} zMwQ`WQ?3;MH332V=HnuBi3Ik1M;;ATCPb{l3piXAr|Bnft#UF^S)P!3R|t{Jv@MKG z7Y)#+-%$a_I&VNxt-7D5U-YOKl@^24BWJ)hS;ytX8qts=`INj^9{4lxQJ>rCqUq=j zXLJ%$u9n`}Lh0~ovYmU5cg|g^F6!3PWxP^D(IqZegz?;S>kDUt??~!JlaAy4lw!vh zocVzngAgCv|ICK--b-}#-e%bssm#CQyt24d{*@er*F@v6v}|=KyVN{$uNpT-bhA+519v^2X{_*A||w! z%IO-M@fA*jLi)v}ezkD|dcjsUpXiU9!(9nGR7rzoI$^=Ny8vIyf*SX=wJZ9*Cw(V` z17%)FY}nE^A|)zGbEvq}N>-kMeCh3|e6Cj`!j`Bq{jj0=Ga&PmbNE;Yuh^#NZY|GL!Pp#)&#L z90nCRC2+E|I)CfVrzS9_Nq8L`fbT`JW|szu^~hHBE=u`gwz{aueHKB}v+wQ&HX3(s z!~r+dbwa&;gEZg~+%>zB9&Q71(JKF;67&JY*Lcx*LySA0lyiWdgw9>u#1-gqOsL2B z1n5rOkjGOEK7{19=wJPZ>1K&R*H@{5gW5Zh+Efm9+jAEjvEM@F%_9fi`8%DY5%$+; zJ}o7CyGr;hez`6zZ_$m4On@;Iiqrw%O4*VgiEvtI=!aQw9#W}$;Z@9wXiJ+rvw z-E&M8d=nGbX*8Yxn0DRcF$SU&lJv=&T7<@dzV@sxpWEg`v){(Q4u|dJ3Uw92c?w3* zE}|1gwKUy_-R(mXw38sWufVoMR1^OhI={=b>j>=Y{_1Qq9bejnTb)2He?hayzl$+T z!Yvk)*JNGKdl*KHu9y6dCqb#w8GY!wX&UAKrYkkHYG3*d;o~@xmF_c6&q@&ce1nTL>KyvZHG00g}=jgF$QdVh`I#mn}6A zmLDJQE~yk4ffO=<|5}q_-sU=>@K)5!_ZW^um*1@K#R`+)mwyUN?X|W7`?BB+Gg$`; zZK2xF$At8)m98&P`q-eR)%FPxsv<^L@CrahLj9=#(RSQml^1`BST}q4QN|}EH04Aw z&IV-Yh^VTreUPIUvM=sJHV0Q;CRF{GUbNl)=;VjAV+`OUh}Dd(j0a=AT1lBt^lN0~ zsEkljzRYI-W@GQ!*Dz$*|KjYXtgx=a^Vh?j0=-6*u_^cJGxzJpwI=c0)a3~E?lb#U z(u=d$LKrY-llWNiw@)(d)~jzlum{JO{UVsVfiIT%^T5!5mkaty3XB-3jy}&}(uyZn z4m`A!rR#No9Ht%RU*(q2B9=$08|w)uqlsk6))ZKA<Un6*)SM9{VwhSTD_k_TJM;3(?N!dycU)5UHnBMqx^@#9PW8^6sr&cvg%60 zn+Zy`zzPW)YG44q_2wtX$fT&(7GKUE=!$Y?kEbxxgGmC$`hm+JY6Jtt>heG3<_o=b zGoa3{q#C5`Zb%xRAYe1u3zMBHQQZLL4d}v6j)k4hTT7Uf${4}|%*#SPm;PKp_5HQK z?d@kI%5+$XD2t+N-ds4cu04ts)9rD1oC~gIxD$JfuF{x?f3G!fvS({R&}tYbOyId7Rw)MU&{oO7eu+IN$I5yg!+<|X{|!?uH~ zWK-mBnF2h|o}jK9Ek%m;!Kc6n1!}DQ|Iqt-kok(vq)$XisS3$bgc*ZRqD6Hz$tmcV z6KaxX7>KwDWOx;4b1!#?lxy-P4Xr66+SHZK%UX~vSnv&Lhp8{C8GhnG4^n6Yx;#R2 zVCGB?fv~zA-6HrM^J}0b5A&OXB;~;}_0-hEQTH8$^H@~=vca=$Ev!&`0*g(3aBSxK z?%Z%?O!`GI_ zG%K$?3qxsv{~!?q_#H=|6&c?loIma&_F$vWI21K4C6_&M7D(h9A9qrt*s zQIhwA%&`G&a~U`H4Oe9)^M$|z0|86{qn+ew(ojfXL8K`M`I+&Ur79RJ8xjof=s)D91E&RD&!l;f}?baEKLC8j>b zI72N~U!Xth5*5_0tW~XLb6tM2oM4?-OCvLApu_hDf<7z?*pG*zl_v5 z0H6s#JsX}-Y^308;{Z3y{j_sm!`M$d|A6TZ_ZW{M;?HlN-%Rl; zz+b^Ftn_Isj8CEb3#Ku?zb*KZ_p~)*O4S?hSFa&*=0kjGBvCH@^lCHl@m_tHhjL;V zyeI+>D92K&acv&F_>gj&B;OP^s>@O2yHXTX)Q6->5s8GN-qQ-Z-DOvR4W8CiR~n+3 zbFXKoQYW<~3a;Q4yh*|6;^j%SW)zM1kb zm_vOt7DcfMYo1@O{5<2)$U;nMG>`k?D|Z?YTijDWk0JDsz6%4{{%ZQqk4`58)<=6U z2xQ@pt;A}mMtUHeZ0+u+pNM+UebK#Z<~q`?uzdTf27I^~5wkq*o>DI{Z|T;JL8t?Z zuoIv5{esD@Uy87KVv`2$io+eb-zksVDT_*;cs;Y2*;^o1_`8UMz~&8B-d61;0>A=* zco>_vhYqMU6NLNk|KKG*QO93H2iMT?-%=N=JukayUNKzjlAA@Kp43UqaQj^KT-g#M z-xam-nneZJj}@8%9Dk!*&Sr+M&yyEB>UjUij<9jscbP#LJ{}>H^qBh0x=A`Pp_ZR> zm|cfOXo+%A2;WlVZT|-^`QPi; ze_x!lAc1-wOG&7OTPzWOA=dXR!jW)S;M_Y~0jjZ0h%p&4&g1mDRfd3$o?Q%EhbiO} zR~-`OqPGUZfjS}p<(8pYBraw;pi}Q+JBEwk`m6$wm#zC|>@?w_IxAB?U6+Ck*Sop-J<|_0|4~@1BMQ_BGdb7MgtIYNyQ}ZxVDJw zvSR8!wD)B{-*i-68s5$c!%1)lZhrQO=tA664?oauO$Q?h8wVNZu z_qR#&jRIJ?R*laMAxvK-=EVZGw0zfR_F;m!vogg^y|c@VO7a_8^&4nz%NO4`c2X)I zZS%D8jeed97O)621jPBf^UD^{31{D04MW^HUe|0C)|{1dTCe97?gwR=O9|@*f|s=B z4lweL0Agdj|1uO#H=2-mAIiM@Hu2GvS?#;`UvAqqV9%3TTDw_|+e&$QZFMZrFAjFLW)zFm@cS$|^kYAcDjPfLg0S*QHk_85CxnLBvG9(ef4 zAA=|`WRWB?5o)ykynKzl029qXx=vy5AXDavTYn7|w5x^H51snH=u7u;9?3%fNBHmn ztjThAvS7&IbDq9g{J0FF{kuwL?>7I~2Wg;o$#b0X_8c<9OwKI}zd+{`to#5GRYRQt z2`nqzv6KK2@P1TmBu=XFW~nEgv&F`LNX5EVmYBbM+1O3>9ZgfWUr&G&cy5ZXY{UyF zq~g1{qFfbV+S-g*rGjcwKoEq7`f2Bo;;pZnqY1s38x^O0K{0tZx3O7-QzNoMEepAJ z2+BVc?d~cbV>WFMld6v`U@O=N%o4TzzSB~4EKd=GWSu#Ex}G@V3Jd>64RkTzO^nC5 zI8prP7{#nDp1A`9cF8hTc2xkRE>beA#9^osNa2hR1po(E7Ja5_$uq}|!0L5oluza3?KuMY! z{@K-9>ZSx(iZI=~nnhKig}}_FWNea5S1SpjqgJO`Egm_NA&Y)@j+W`k#i_H+JRR|9 zI+d-(lFI(8BVyPJ6wq*=Sv!>D-M@#!UzH@Fy3KbDT8{b#qMC*?^WWfAZYr~+& zSQBHMrIV*a5}yi)kgYKQJ-(?;u+vvWye9>u7x&h1PAhZwO{|C!2}dFBb1qbg+GQ}} z{wHQ<C*KFBz(Vc!zOCAVg)?5GcRnYhU>OcrTIuIQbdE@`p4r9pU zkx&M$^ErV4KPu#5Xw+4Yv67+n5a;fkhdxn5v=3VR>zi7X%dvWW|8btYR)aaO9t_H1}Gg{{fC6J6f z2Ukn#T~k+bBC@?079>4ofimRw+oX{W)Aeu=`A5=c60c~Zm;4sYhlxN|3~Yv%pb?K< zKHPC1cwVV3!1+C3TkUDOiLS(SPuvCh)$RXJ#o+BFD)!Kl=}PK;NZ43jz<*$-&+XpZ zm{<@?l@`lo*zDZcCpRytX9x|1UYO(((2FAlr|W{8swc{B)apozpOIadislM}C`zMI z1F3F^bM^M-tG26;TgiSJZ|}-y{xpTBzVodZ;!SR&HZhyFiyz9u>49qk;@%?qCu(#*tgqP%B_pgd=+IMi&1aWMi zS$(Y;zW$4op^#7jBJ&<&Y{s&IsbOxgxYx0IqvFSgB8y2uH{=UGZE0WiEC~bJ28d&& zmMh2QC}~xNE5-vDM`c0}^4XT}FK5|Kp@FZ)v5b{{C^l6d`(v4!*bSLquk$DG-+s_Q zKNF-q_J+uuJ0zxqYnOkxd6WD>2i)q;ZlOeoI6v^5Qcclg`C0jYR3KW25dYpduF-mK z@#;7>3=MjqPVUd`UDlSa)bYA{;DW(4BQp3)%UPox5_hrvo9T28l8fe3Tmr^sz1w?4 zJv_TrU1EWhZT=VS{j}-+_!$RLM>{JJ&Y<0<(lIfrBH$X6M}qW6PunF)UO9icL=7-?Jdcx=2&KE2(tvIgXe7%h{O9EPUZ1vocFsC3*dFS z+t>w2{Wtksuyd<&LL9j<-;EkhW zNahQTKwo{MAn*||*7Tioc01EzFSa78K#xAwDEwy- z(-wtu6&SY{FPTQtBT5|KD`hjgRIoY64ao&py#>wlZ@5zl*4;hESmAx6-1ME?8j%bw zLa;tA%+^SPv|bRH?ct@9G#$WYlmg-9u)2xx7OU=fSXQ0&f{?c@*<8bvg6_>~@ICk2 zo~WOM2|PSEY2qgkLCyeN&KV&et;zR{W7=0s|bZ~c0gnTk$B>W&_wiTDxu2((5vIX#M_a4&pi5y1kP z9&jWNUL0FNk+6n>n~+54D3E~MlEIrsk)Y!IpULEt1JkX+a?Q3))XiYuCiK{~7UoPj zM9%u~Epy?b@&zU0HOZyNU^8dD=sws{%xJ3v6#5A8A8He7H2l-YP=H!op79pw)GXvLla3ciqZ5MRZ z!Z7MitxjN_`aNNmCe|BP?d5xMMiDq9E(-kaFF>TtwBjQS108pP5#NQDc5MEI$y}BD z#k_7nY7YAE9+4WF#ruoE9c4q!@w zLi$J=+k8{?wH^g|N!3w@Cn?{cRZ(LQZCh+awOi5=<}Rgdi+UHPDR(JQrZv;65j=AqesC1^Jsk#V| zm-h8)lMlP3;lo$p|A%2$@BJ}4Lp?oemF)SOSf zvBJIjaAyUchbv0n_V|dcbi@37l2X&Bw)iQGIG!5mYF`f_a}Px=em zjB9M~0^IY11>w8apM|EC{p&RhZAxKY^LQ4IXXmPKwjY&JP|_xI7FS#vGq|!al&;Wb zlfSFF>T9@w*0VW?nqax;93ehYmwe0 z=nIU}IJKNGa?LpWO37ArI5^s8YNdz`az%289{&yB#Sh9|C5ZRkK-|t8JM5ERImD*z z59lowYl3()B00)3rIDRe)Ce(o9XDIIJ@*sZ+)T#6Y}xk(eQsS=tv?j%>noHOmHXXq z!^vhuvF;ZTG)d3imr%17kO-ij*_%S3XXljA&Cpk0DFjw9f?Q{7TW@wk6lOP@N)i0k zhT!CGRTe<+XO*5;GixS7T>$oCw#mFJ zHh93^PsaCX8vf;86Hc)iNIsnLFU*r`7#AHs38!##QZ$arlDoqOD#QS^es_5hn%|5h zZt$2K8+kc6rB-+8>d(ODXsX}AnzW?q4Uhozx8E!OW}m$J^nC@KCL|o~<@2pgjA<9Q zq~`wnf`jP`(L+y?5OHo3{<|mzG&lua+#L{Elm%uMGkYt)HH^isU~i`-6Y?f{Nr9w2 z$CuBMGA8-Iw)c@m3-z~uC6v#5Tg~=(__<+G+++py8^Y|xa7s-(%k{Teexvafyj-`! zy)xJE4}Eh>M?#l&=lnPopppm(&R97Vt%qcU~`jp zi1A)d;OA%vjRCf18lMk75lFHufz}rI2YyLTS>eYRlTAw-aj_E4gH@MBP6@nb0~qZV zOJwLg{ckY6|GqaSYn$pe>4>O4Do3UqCe%-=f7Wbu9xQW!S1}w#SboRgg_Gwc-bWYVi==WuL#&;4@peQW!(iw$v+z?y;2uWazg+t?wrG1@%%LXz&w zVbj>z8(yLWJvIEjfkl-T!RtrwfxVT2?jdNXHFYoKzX`y}(x?P*(_0^rg)65Y~_UAA9uSLJnSTK8@-@WRWUvnaz5EKkCPHNH4o z22jI7AuEubVGaG8gHsDb#DF1)HehpNklg{M&f~YKmsC(FR{((d?6c;;WbV)Bk%UNJ zm92A%A$0UUU3tCqnF*#}603yHeDRG69`Z$?96uM}67IUJ3&n$$P&`X5@^jrfhmhMR z+VRp<mjj7J1 zo*OHZwJ#af2TYxeEBcvtH-sTPWAoR?%7P?CQ)%^6OIqhRErHscSqFbSh zetLt1Q%(;nJVr3R7%a*gk+vOSp%>H+ecEZbt4{@?c=qJfyCw>J2y)xXG?be)3(g6D zU}&-w2IJ@`H2^8=1U%4MBigb{xp)-H2Jn*wg+~KEULwU*(ghf0-HFIcpY1c;s^dE9 z9MP7xZ8-Su28T~+0wzO_JR|klP<%9pH3%71-?8uc+-D(q|C6IQ{`^N~iLUnp3TkAV z1R}u-6`ASmSFq;B{F#xIwEZjFF-$h>fjfK9pVH+?CP{|U*I(_Oh2Kw43N>JWM}(i* z`G&yZv5^!`Ah(rNKg?e(to13=QXYJYv#73d?r|#HOBU8oTMxgvoVDHm)H+YWZ_>x$ zv!ap=&&ZzDw`AIidi$=)v>20FAAtvdP*pU#{?ZRSrK#H5-{p+$&9ARV;nxeB6-Dia zy3_$C`2a^^_EVZTgK8^h@x6ag4r?Y2js7mEW`H=c%&BwI!VhcHB__5JG@4eEtP zH@!!hv*OHtovacU6JpbXrf3k-SrPZ%A;E-I8<$QggzAuIO9S#deowB!VD}zY*GgX( zJuRUZg1ea-dU83LL93{>IJltV`(O#z-@M9dO;Ral)W4vyGl2&rf0f@D_Cf7 z@evX(tIT;=4Z4^1I7^BUS#{j{q(oybbhgnnXW0Q;LUtfrtzGE(((I3?PHzoeQAd7$ zWQ++hi5@Z9*h#_gc9QzUHjbJm@yRv7MX+`^WJze{KVm4sbLHCWDE7txiWAPSfzDMe zHiJtejasBRS3`+NiJQ~Wwvp^Da?~D`RC6b6ROmR*HRZ^4BnZXB#CVio~O zEdjtDnjRdGB=j#|u`$(>7w%uWvM#mqFL|2FQTg^lEa}TF-7$UkiS1P$Mdt5lwD`rAadNCK&Oxe43T8;N&&5FU6wcyJ2j)i~P&r=@z1>&yyYH0_a`m{auXIY1T$;z zuZ~emhx9%wVM7HBKp{4CoUEKT+YDqbDvB9=FcjJ&>bhs%9K#|1O0Z))l<(zlZHQ8k zMuliIJ@epUxMGie;iCQV)>v}*dnLls&Wm$$hf0YV?36C{aVmMgFCu4v(J%|Ng{=%2 z;U2!E%LHk5Km4`+MwvqxSc8)|X$(ttOVO#taxPK+*NSgMZmGY-MkpOr+vOP)!yos2 z&3F)hb$i>^K)5P;6OX@kwV^9u3NrYdN=`5xA>^}PtsXY1dvtd~fd%J3lcxf4M*0qS z7gzJ|)Mdi-00k?5;Ce$&*fpY!WYH5(4pWa+ubY6CC}iB;A?o~f;al+7*5yGG)i)vW zzp8}#??dniK$LtNlUg#~T+=V1;=QH1)%JRr7WmsM-^4E=a!L-7N4gk#)(R**RXRy}|3-aJEf?x!n%kNY(-SB>wdscTVsY=AE(6roLG zC&obokR2+U?6`N88xqAItO+@ytYETe`Fof!A0TgJ!9|n|fyex z1Qh{91l1FYt=?ux5LfOe+{d>EJJ6r)a>;KjU6?B+zFK0|yR9iQ66WuO&gvOA7X7>e zk~%5G7C(#UXtZ+kainD}$~U(9zvaoXHCL+3sbp{7288qyq}1xv!~3;7UFW?ytXc4X z6garf_a@8ftVh)8u(%qv^gNe6G+QRo%b)ajC~=Y#7bqDqg`WRs=Zb6HSyrpU2s+)K zZ_UXuJ7au76{Fjd`(Zp4<+rriV6GuIgDpEjk=m7subqOqxw_xRj@i;gGTF<*p9{2O zfMWgRk0b!mMe=40-~k}`Fr9+d0^9*MhH-R@UG^xv;(57FAl{Rx+8YQ(2)H;iUjN5E zp!%+}%=sK^Q(0{wC3|Bye4tiu6737xZVY?CX$Ir|zIWvApL8duv`lXBcJT^S-44)~ z=KTySRi}~HoVQ9#Ye=y7Ec?~a*EOqr@yH_r_yfK4)v@omYXo84gZ4Lm=m_C55rl-> z+vzh9HOP4x5vyF`N_90c=0Bx!n&f4|B1kMicpt{D!{9fgazZ*PynzC9m9Tc<;8NS@ zhoYOaQZTl({5fr=n1THNW1W7V1QC<9cZN_7jRXAqXWiOGK)tpK*JP^cCV9?GU&}@~ zxuzkV@DPShwbH;yyz=8ChJkB;*p-GYJ~%z3V1u=i6!mTq1oEoeH;3X1J>PC2LgSq! z5DiMte#bUlr}%_^;CsnjwbSx_^GvK}+ct!-!@W6TBAJS$(Qiuze3r({UvwbTU0UdB zm@Yo$ ztK(Z%IQ1$U3r-e}JVa3*Fx)MW{37ql7^L_KK;Z}YF94BWSu(VSV-vNYkiY>|1+qJ&Cn1U+IN?n*=@Txh8`fl;j*wLyib4^_cX&EZ85^k3(I5W; z`DUx`yW`E8W;KJ^7!krP=*X#)pK62IxeeKCAEg%dd;E_Jq) z##@7sifY!#x<|AI!LUAHN+^>Em2Xf;1K-ELUP9qhlxs-j^CrN^DZV%NZKJg^NX(rm zqJ2P6VnW2{KW?!We0DnWzuL6n{l>?9E*!YN&-yt%TQ}6(pXR@pr43FWW+z*XDvD7d z2k#PXgDuTjR*4=Tnle4#J5x2+4y(M5wbuCg3tC z9IF=sewz+(T9)5r$OQ1J^E@@%vl-L;xVBc;`vQRn!~{oWFksr%!XEK0OIBN+wvMYM z9?&svB(8!IRCuWD0Un()XB0@*pgzd%lSu0oi)}!d0WI<@D$>%)wg39IMj-B?;*&BF z^Fmu66@CWG|U81VmIe}^T2Z7eMMhU=gNh!Agb%_ZUd zrurf~o4=%zkecSqcW%;>be=spZ#dPCS{mP%@X1gi6jEXy%r!gkvT0{cn8TT)*M`N?NS2avi(()c zSl>Ga)uc z1Gag~SjKec+U&Et+v!M~SEx&vy$5*3AHwg`()xqy8|2ek2kBd$iQmD5Asri85l6ot z&SbXcN6~427-jUOpcd%WRtV?5~Yzr9lLcW39Om8!`*hj>71TliWVVw=a zYQm+G-6pd9O~H+OWhdu-Xl7!G1)it!LNS3j0%s%bZ%#|HyV0hT$nMN%&ec{e{Han@ z$l$m4KNB zy-Few!MuR|^<&AJ&mF9`APcy+_WAgRJ=fAq_LdDs>2*w}R=9`6$~zug>yVjUc}}9d zoyR2E{{yiNQwHsVqS2);qn}>VLZt0M#>w29K>C*lNDn-0{7l1$vWTLcfF6UABx1&Y>4p{S5xagXr9aAhQ zqsS3fS#Imxzneoub+hIKPnX~8LEH*|&9rMi!-FMNgW)~0sBY+q>xf{@TZ{h`fXGqe zKhL=tAa|17{=Ls!2Q}yCb9gn*RpdZ1^fcPqyS?yV#}B6%R&AR)eicU_6T)nGlPQ@+ zh2z6T9t;Ay2^HAbw9B`CQJ@jkrco$Be^Ajbr&;BH6e7GNMtPF6YD1YdD|1sPgJfFS zNFa_N8c;Rr9AYO@y4DnbAfHAOjcA)2_k+M3&o$Mq%)qi($cRmaqb}7+AlN z-SY{Y9~dI+sJkd3)poCO7hu#USHGuic59b!-w<{MnSO}aynqeEu37Yh<`HD_Uw=PG z(=0!g16dzTq<^Y0NtyHfwDbQdSPM9wBPMO*#dAr{W+x5&n1T+vOGeP(xBvH1Zsu$4 z;<^k{<7vYq#JxS)0vD`g_4=V`X5*Jzt{-LZ@KEuh)>rb4v{B8)%jn8ZYHSn zm56%YZ}4V-6x4sTOb}zW&9&avR=>K@eU)|3t5=?m%Iiub~L}-L{t*2M^cu zk=d~3-X`<+kS8|lX7E*^{~%8(tI;1d_Ia?Odx~HGW_1GqNGy$FQoRsSt zrh=89@qT?as%3iN9|ASDH)}c%&4EiQ(oU)`%Yf0eQ$&IGip90^%rZIx+3t~A5c+O2 zMCDk7lVd`LZ5`N`7GOpn*J|K`MN%*J|-iz z#do7bQcw9R5={M#WYW+-1|6qplguVrnHw^^pz!ntI7!Vt2|V>Mb{-w{SgHH#{n8=s zbXPUkfSC+oJU^%;=~-;Eyb5>!Ua=qUDS^qd?q_ zl?945ZA#(tHF2l1#L|pLs*^0ag!8g~#Uf5uMY6dQUD)yMqmWkIt87>0xAy+_`+2T; z(d?lx)_+?VmhOAZTGB=_CJ(2Em{Y-4MD$t$u*0la<6H^m0g>X4g6U8`@04~*NKTH? z1uKprAMnVaEXFlh?+cvNIcDuL6i#i%R>VCAKl+{Grz?q(9L}BWqOvU?r}N zz2$GnZ;)Do(Uz0K63Q@=S|A}h!)`=IQa>7eH6ABf2?P@Fun!FA;bFe=yc*LdT{tym zNaeS2DxTC0lCSp1HP<~R5YQ@9rrN#aQwb?gidykj!a-zUc^; z{fT*+;gw4W@2vxc;f=y=N*l%It)YhCIF-HA>DMqoMd-|^y`?qAX~h{Q;s6H>OQ4p@ zOs!WJ^^v&1Idz00pINP*|CwEPa)n2!Sfp)N4?&n+hK$F<69sI)mAGabXWlxO!}$#r>PY7HPL|bI`bLv_BER@3g=xjd?)>Z zbG!yO4v(!b0`r_;XO52paoMo1zmYpG6b$5Fc7y!r$j-{pn7OY77FZO51cc0#xR&R2 zLKxwh{*NibEZnEJg}SxOelwS3_$P*n)Q}*+J#+h-oJ|DnocKeAWaLE?V}{e(DSYme zn%BaDCDU~cIKluW3E79YVJ9*Vd+%UDH9ijSt*PHr`L`t5+q1iWd9*`BhI__JPEI7D zTRWZlxNSrCMb2I}s=J8D>7gbV%n-!CEMgWoF_WHz;m$6U_CxK^tDY6rg(>pJ&_lc# zfjIYW>rq{y+!mDcWDfd~wQ4Hh^?(&S^^i2Q8Kk3kk$8?u`FVb{k)Ws_R2#iw0a{{E zY9+%=G5?CjYNr+brHDw(-x%)W-&!ocpv=ZDg63{hBqa^!Ca9;D^-ih%w*Ar0w&*^mFLL>T~S7!sA zxVi;~rnH#8QT8Dr%1NG6QbdD^`{WC{04>Wa3;!d+=J)5O z>Xb3R`!`6c_&={}Y;`>0(DsfDxk(=0EFz=(#!go-5f5NCjTvw8rK%_CmP+YDs2&*xs_8o^FXVe6wA*;6Gp~Qtx6~>UPfV#43xJzf`-V}&!oBff7tq_ z@JySn>Dab0v8{=1+nLyz*tTukwllGviEZ0>{=Dzr|FuuPqx*PWtGc?n?(SM)f>;?x zWOKIZ`*f)qvbG|U9jxdXlX4?GTLhW}w;f>(2w38K$DM=vkW>T9zLd$dXEDf}v7bIO zy^L`HTS?Fl(yQk5Z7jgLTb5il_|lQfCjrNUu`)vIAzgARKf+n$Uzx(4sMz;kPM1UQ zL|LhpNaPy)@asF+a?pQpRtyuT=;vjr`FMc5^AYlE6f!wU#$6FzWZV$suC)Xdz8r%f z#@aQ)=e)MR@x>bxQX&0OgK@a>)^?5>Vlw3yZH9f-%wT;lcqBs&fDwJCKEYnj%ha1V zEB~DqNMZ>KEm~0#jL)$J@@tY7bZcv;;%d)N2|j~1CPDzAlfBCy(qBHj=j$ifHLFS4 zSz@4^_wUm3O(J7cU4!E1jTjUDnD~O`VPE<$L>k*0UICtz1BHtCG-Md9Wi7xza0Z=k)8aR|rBzZ%9ft|=D`eCk+F9>~Ed6Uimx{B6fpb4pA%XTg#u8Z&Y z)Ou!bM?fewWPjR=s)C?<8(4Y!_-sWU(Sd6Yjwp08OB^KTH4hX>kmYYgv3@l?g1Sbp zdR=|H5ZEPV@8&?=3Dk$vsF`?ifvvNzo4Bd=vgL=d1*wMrM+G0IrFoVBB~CNgBv4zA zBtnfL9+q3E-}NHdR_U~M1<1gvjvd7OujsJ$*{z;gmLnIS&f+GjwW&Ck4E5o;1gQqT z?pGLiE6oNMkPiUrGo=j0npZGQEFP`6)>Gu){{BUEBW+Dkyu#djxe{M1&cs zqe^~pt@!8WAqlBo$;cyB*OuGxc1&MxEcRkmV4{g&Zx8KKb*O~If|g5y1CR|m>W6LX z+E3ZteG0MJL4Qj5IFR-OijPd!f!7{+38XNIJdx>HfghTlKWVEcA@BrR=BRKxs4hEU z<1^(C3{3gyx4E|_?hEijfoW(zyFT*d;s+-pi$+IcLHy!rs?;r zg3wf(ZW*g?P$f;4<#*z1D16IMAQ)n0*I|iJIUdt<4p^Kh`Wk1mpp!9lg}vVScqYp< z3oR*-IpfvtpV$wUNWenMtD2D1z(WR-W>5LleGWF9-0N;vT?&3wQ-g9)m7WFcAhwT}?M&S(sZC~^(X zg?}r(2tPfI|F;B{L%QXpm%~e|ajnpfHlZF}@nD_6S&DgKlW+C~`+3q^J;(1peE6k+ z_oMS`fR3BvVz|Viy_gY$DfeM(s1x6Xmu9lhm(sv8+HiA;A~-d#UoSWw_`?R}rpBBkYNY;M=$D{KMzLJsW2r`dgE`vUNc z2q>=Y1A3E)?1NG7GIITfbMnMEmykmO?TWgRn#s~^+sklK0EcQyUeD`xL)sec)NtdM z+&O_DrI&-!Zolt%C#mZYi0f#vzh{-HP{Nft-};Rtd8n?G8;SEMgMlqzx}I&!^VOS*FjK8HXU2s?dK+Lvlq_Wlt&!YbvQC6q{wUrfS1!N0p~ zsB8KHlM-AzlZ@>|l+C$1&Cnnvau6Ryu+u5Fp0xDjVp z-?y;lk(BMr%>a#hlurgVnrrPF4_{*}@9+JvPutw;e{5PRQkjWeUAr%>{(-X#vt7EH zUqu2FOt~I15{V}+$kPS6>Xp7B@=SUr;rXG8;$BeprkVEX=+JTa7HvC2(b_IP?`K?# z$gf)Mf$!;eT`@>+FEsa>OyL=2ljmqz@b|Z!o%ctF_NV}VzapvM=N?_#Gp4d8fiSVk zl`NB<%_U(IW^8#`-lD@1C7pqnrW3y~s9Rclouz^rX>zDM^-gzPjk&rm&hZjUW+w;G zL^IBmP!~n`pz=D)y!56NC*cSzGNGjMi-x!o?DW#c(XhVQE=;9eWYJBiq-NyyI+YVS zj)Fmj0fBZWtleIub|;{n?Y5r>#ZjBzaL$qz;eQzYzS>NMS}he62%B8JTe&mDViE@e zoBTvKKF`gE&H2}VAi;oF**Np=5&4;K;w=g`gI30q(#J=uUB7B`m7w65w~SO@yh-BW zjZjlWqfVca_%S~F+ykjpeyLJ2`n;l5G%I~utTwot6x52g9L?fIbV;2~0wCZzM zSZXEhS8c=&0of$gWS(^YJ#ET%J?Kz~a*Dzd@egkMBFHVx24-MWs<3J{U_BkBQ?3$L z7Z#%RAl5UKWk>v=^!Soe_pg=X=%yD)Irz!iJ`T3Ispqj(BWgFj4I%aN@Cs6JvGo zNxvf<9muu>#7E4~B^xr1_#LsXO8IXXdyQ1#7!5DmZZ#6vdl_J9{|IySH_im03kWyV zeaay+SNyS7e@f`u%m0G(mPd#vio0Pp8W(Ln8*Mr`&#?%SG$L2sg-fZApPo6@@4060 z104fhermkaYfwqd zzJ)xd%ZjO4cW+10>!ukl5|RCM6*9+F;}(68;EHRFuigvO2asn{39j9cMw2wA{D{#x zHmirogEQjz>qiD)w}gH30=mjQJ~>+!>$s=Wf(dN&BFI$}AXNQh%zkktf8 znf#&Le_7Y5e$7L5nL|0_wevj^7C`3J@sN9WWu|Z|^zf;sQa(#SJ7?*5XU+maf@^9z zFKd3_dy#+d$>S;*n+aHMoU|`h8yA1$yX@#Bu$i~~YqHY82;@PLKLcSICiZJl@v(fP z>R{#ZU3wEWN*Of;5Vg)D#J&4Dzdqv&9Bo6()!VRH5jY+LjrDtl;BrE`#{I}V^x)@G z74@FJ?Ruw>(bj~jw=XG1_ZAWU#5sc4l$q!K<_WpQQ@Rx*uwh%+#W*BXXvFd@YZqxriy z$QK(cgswbN@j{3dU$2pI&2jck3PP`-5W!QZj%g^Vt||1}wC_Aw$JlvuU)~MA2?*DP zx#iZI3-?ncB#6v=+ge>kIZ}=fad)d`aVioJQ>3WQqoJ&|z6r&$_@h6ztU>4uu&<`H zOIiWk{(Bo_{C_qG%C`+-U(ZMIf7&3~+^aJ456p`gRC&{>UV##O_qTZj#W1 zTRK`TUiwnZ3yqosYpQPxa}P96XLI;&O20v6#=>C4^&HqiI)T_LBMH{)9u&L22(sZb6A5 z4xfLba3h{3aLgo(tad2{cMp2%i0JM8kuZ8KNGH_&`v^)k4aN8A4S-Dwy93%WPj`8J zO#01jIl$!)XOWb?Kec^?>k$H8g{#$ZRzekKfETy!U2v6-lcftBGa@^~w2X-)iwXzS z!pu~Hs_^%Am%!B-H+G3!mpPMRfBX6XwM|s3j0ubJ-EEK&<*qP^TaM$;5Z#Vi8$U2{ zQrG2XC9aepAi>Fd?kdP0sQehuPhI<5}Zt6sOriARpkSIb{q)hndS_G4+PFp0}y(0sN+0lvGGad z)ZCYYRJAerF9Lyd__kkw`$6FNr-Sm^X4OWH?&-fpZW*J9w8uC@n#ekd)R!S2(zE>@ zsszfk+q-zTkoYPAng^wJoS$gI7A_N_hGnwy_K<3$!PuS#16ybLx_^J=^9zDB5TG46 zzJhU>+!2Qu5m>&|$$naPROd2e|Gp=-V|CP-*(2 uJQ2t!@1qt`~RFD(J(=FRaL) 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 literal 0 HcmV?d00001 From a0a03c9eba7cfa82e3201ed4582930df2e9e112e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 14:29:02 +0100 Subject: [PATCH 053/271] Added voice call service base --- sbapp/main.py | 53 ++++++++++++++ sbapp/sideband/core.py | 41 ++++++++++- sbapp/sideband/voice.py | 153 ++++++++++++++++++++++++++++++++++++++++ sbapp/ui/layouts.py | 28 +++++++- sbapp/ui/voice.py | 108 ++++++++++++++++++++++++++++ 5 files changed, 380 insertions(+), 3 deletions(-) create mode 100644 sbapp/sideband/voice.py create mode 100644 sbapp/ui/voice.py diff --git a/sbapp/main.py b/sbapp/main.py index ffb2cf4..e886cbd 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -239,6 +239,7 @@ else: from ui.conversations import Conversations, MsgSync, NewConv from ui.telemetry import Telemetry from ui.utilities import Utilities + from ui.voice import Voice from ui.objectdetails import ObjectDetails from ui.announces import Announces from ui.messages import Messages, ts_format, messages_screen_kv @@ -267,6 +268,7 @@ else: from .ui.announces import Announces from .ui.telemetry import Telemetry from .ui.utilities import Utilities + from .ui.voice import Voice from .ui.objectdetails import ObjectDetails from .ui.messages import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem @@ -352,6 +354,7 @@ class SidebandApp(MDApp): self.settings_ready = False self.telemetry_ready = False self.utilities_ready = False + self.voice_ready = False self.connectivity_ready = False self.hardware_ready = False self.repository_ready = False @@ -3148,6 +3151,15 @@ class SidebandApp(MDApp): self.sideband.config["hq_ptt"] = self.settings_screen.ids.settings_hq_ptt.active self.sideband.save_configuration() + def save_voice_enabled(sender=None, event=None): + self.sideband.config["voice_enabled"] = self.settings_screen.ids.settings_voice_enabled.active + self.sideband.save_configuration() + + if self.sideband.config["voice_enabled"] == True: + self.sideband.start_voice() + else: + self.sideband.stop_voice() + def save_print_command(sender=None, event=None): if not sender.focus: in_cmd = self.settings_screen.ids.settings_print_command.text @@ -3323,6 +3335,9 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_hq_ptt.active = self.sideband.config["hq_ptt"] self.settings_screen.ids.settings_hq_ptt.bind(active=save_hq_ptt) + self.settings_screen.ids.settings_voice_enabled.active = self.sideband.config["voice_enabled"] + self.settings_screen.ids.settings_voice_enabled.bind(active=save_voice_enabled) + self.settings_screen.ids.settings_debug.active = self.sideband.config["debug"] self.settings_screen.ids.settings_debug.bind(active=save_debug) @@ -5234,6 +5249,44 @@ class SidebandApp(MDApp): self.utilities_action(direction="right") + ### voice Screen + ###################################### + + def voice_init(self): + if not self.voice_ready: + self.voice_screen = Voice(self) + self.voice_ready = True + + def voice_open(self, sender=None, direction="left", no_transition=False): + if no_transition: + self.root.ids.screen_manager.transition = self.no_transition + else: + self.root.ids.screen_manager.transition = self.slide_transition + self.root.ids.screen_manager.transition.direction = direction + + self.root.ids.screen_manager.current = "voice_screen" + self.root.ids.nav_drawer.set_state("closed") + self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) + + if no_transition: + self.root.ids.screen_manager.transition = self.slide_transition + + def voice_action(self, sender=None, direction="left"): + if self.voice_ready: + self.voice_open(direction=direction) + else: + self.loader_action(direction=direction) + def final(dt): + self.voice_init() + def o(dt): + self.voice_open(no_transition=True) + Clock.schedule_once(o, ll_ot) + Clock.schedule_once(final, ll_ft) + + def close_sub_voice_action(self, sender=None): + self.voice_action(direction="right") + + ### Telemetry Screen ###################################### diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 0a4e780..6e70381 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -167,6 +167,7 @@ class SidebandCore(): self.owner_app = owner_app self.reticulum = None self.webshare_server = None + self.voice_running = False self.telemeter = None self.telemetry_running = False self.latest_telemetry = None @@ -531,6 +532,9 @@ class SidebandCore(): self.config["telemetry_send_to_trusted"] = False self.config["telemetry_send_to_collector"] = False + # Voice + self.config["voice_enabled"] = False + if not os.path.isfile(self.db_path): self.__db_init() else: @@ -837,6 +841,9 @@ class SidebandCore(): if not "map_storage_file" in self.config: self.config["map_storage_file"] = None + if not "voice_enabled" in self.config: + self.config["voice_enabled"] = False + # Make sure we have a database if not os.path.isfile(self.db_path): self.__db_init() @@ -3715,8 +3722,8 @@ class SidebandCore(): self.periodic_thread.start() if self.is_standalone or self.is_client: - if self.config["telemetry_enabled"]: - self.run_telemetry() + if self.config["telemetry_enabled"]: self.run_telemetry() + if self.config["voice_enabled"]: self.start_voice() elif self.is_service: self.run_service_telemetry() @@ -5183,6 +5190,36 @@ class SidebandCore(): if not self.reticulum.is_connected_to_shared_instance: RNS.Transport.detach_interfaces() + def start_voice(self): + try: + if not self.voice_running: + RNS.log("Starting voice service", RNS.LOG_DEBUG) + self.voice_running = True + from .voice import ReticulumTelephone + self.telephone = ReticulumTelephone(self.identity) + ringtone_path = os.path.join(self.asset_dir, "audio", "notifications", "soft1.opus") + self.telephone.set_ringtone(ringtone_path) + + except Exception as e: + self.voice_running = False + RNS.log(f"An error occurred while starting voice services, the contained exception was: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + def stop_voice(self): + try: + if self.voice_running: + RNS.log("Stopping voice service", RNS.LOG_DEBUG) + if self.telephone: + self.telephone.stop() + del self.telephone + + self.telephone = None + self.voice_running = False + + except Exception as e: + RNS.log(f"An error occurred while stopping voice services, the contained exception was: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + rns_config = """# This template is used to generate a # running configuration for Sideband's # internal RNS instance. Incorrect changes diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py new file mode 100644 index 0000000..09837d0 --- /dev/null +++ b/sbapp/sideband/voice.py @@ -0,0 +1,153 @@ +import RNS +import os +import sys +import time + +from LXST._version import __version__ +from LXST.Primitives.Telephony import Telephone +from RNS.vendor.configobj import ConfigObj + +class ReticulumTelephone(): + STATE_AVAILABLE = 0x00 + STATE_CONNECTING = 0x01 + STATE_RINGING = 0x02 + STATE_IN_CALL = 0x03 + + HW_SLEEP_TIMEOUT = 15 + HW_STATE_IDLE = 0x00 + HW_STATE_DIAL = 0x01 + HW_STATE_SLEEP = 0xFF + + RING_TIME = 30 + WAIT_TIME = 60 + PATH_TIME = 10 + + def __init__(self, identity, verbosity = 0, service = False): + self.identity = identity + self.service = service + self.config = None + self.should_run = False + self.telephone = None + self.state = self.STATE_AVAILABLE + self.hw_state = self.HW_STATE_IDLE + self.hw_last_event = time.time() + self.hw_input = "" + self.direction = None + self.last_input = None + self.first_run = False + self.ringtone_path = None + self.speaker_device = None + self.microphone_device = None + self.ringer_device = None + self.phonebook = {} + self.aliases = {} + self.names = {} + + self.telephone = Telephone(self.identity, ring_time=self.RING_TIME, wait_time=self.WAIT_TIME) + self.telephone.set_ringing_callback(self.ringing) + self.telephone.set_established_callback(self.call_established) + self.telephone.set_ended_callback(self.call_ended) + self.telephone.set_speaker(self.speaker_device) + self.telephone.set_microphone(self.microphone_device) + self.telephone.set_ringer(self.ringer_device) + RNS.log(f"{self} initialised", RNS.LOG_DEBUG) + + def set_ringtone(self, ringtone_path): + if os.path.isfile(ringtone_path): + self.ringtone_path = ringtone_path + self.telephone.set_ringtone(self.ringtone_path) + + @property + def is_available(self): + return self.state == self.STATE_AVAILABLE + + @property + def is_in_call(self): + return self.state == self.STATE_IN_CALL + + @property + def is_ringing(self): + return self.state == self.STATE_RINGING + + @property + def call_is_connecting(self): + return self.state == self.STATE_CONNECTING + + @property + def hw_is_idle(self): + return self.hw_state == self.HW_STATE_IDLE + + @property + def hw_is_dialing(self): + return self.hw_state == self.HW_STATE_DIAL + + def start(self): + if not self.should_run: + self.telephone.announce() + self.should_run = True + self.run() + + def stop(self): + self.should_run = False + self.telephone.teardown() + self.telephone = None + + def dial(self, identity_hash): + self.last_dialled_identity_hash = identity_hash + self.telephone.set_busy(True) + identity_hash = bytes.fromhex(identity_hash) + destination_hash = RNS.Destination.hash_from_name_and_identity("lxst.telephony", identity_hash) + if not RNS.Transport.has_path(destination_hash): + RNS.Transport.request_path(destination_hash) + def spincheck(): return RNS.Transport.has_path(destination_hash) + self.__spin(spincheck, "Requesting path for call to "+RNS.prettyhexrep(identity_hash), self.path_time) + if not spincheck(): RNS.log("Path request timed out", RNS.LOG_DEBUG) + + self.telephone.set_busy(False) + if RNS.Transport.has_path(destination_hash): + call_hops = RNS.Transport.hops_to(destination_hash) + cs = "" if call_hops == 1 else "s" + RNS.log(f"Connecting call over {call_hops} hop{cs}...", RNS.LOG_DEBUG) + identity = RNS.Identity.recall(destination_hash) + self.call(identity) + else: + pass + + def redial(self, args=None): + if self.last_dialled_identity_hash: self.dial(self.last_dialled_identity_hash) + + def call(self, remote_identity): + RNS.log(f"Calling {RNS.prettyhexrep(remote_identity.hash)}...", RNS.LOG_DEBUG) + self.state = self.STATE_CONNECTING + self.caller = remote_identity + self.direction = "to" + self.telephone.call(self.caller) + + def ringing(self, remote_identity): + if self.hw_state == self.HW_STATE_SLEEP: self.hw_state = self.HW_STATE_IDLE + self.state = self.STATE_RINGING + self.caller = remote_identity + self.direction = "from" if self.direction == None else "to" + RNS.log(f"Incoming call from {RNS.prettyhexrep(self.caller.hash)}", RNS.LOG_DEBUG) + + def call_ended(self, remote_identity): + if self.is_in_call or self.is_ringing or self.call_is_connecting: + if self.is_in_call: RNS.log(f"Call with {RNS.prettyhexrep(self.caller.hash)} ended\n", RNS.LOG_DEBUG) + if self.is_ringing: RNS.log(f"Call {self.direction} {RNS.prettyhexrep(self.caller.hash)} was not answered\n", RNS.LOG_DEBUG) + if self.call_is_connecting: RNS.log(f"Call to {RNS.prettyhexrep(self.caller.hash)} could not be connected\n", RNS.LOG_DEBUG) + self.direction = None + self.state = self.STATE_AVAILABLE + + def call_established(self, remote_identity): + if self.call_is_connecting or self.is_ringing: + self.state = self.STATE_IN_CALL + RNS.log(f"Call established with {RNS.prettyhexrep(self.caller.hash)}", RNS.LOG_DEBUG) + + def __spin(self, until=None, msg=None, timeout=None): + if msg: RNS.log(msg, RNS.LOG_DEBUG) + if timeout != None: timeout = time.time()+timeout + while (timeout == None or time.time() timeout: + return False + else: + return True diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 6155953..e520c34 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -96,6 +96,16 @@ MDNavigationLayout: IconLeftWidget: icon: "account-voice" on_release: root.ids.screen_manager.app.announces_action(self) + + + OneLineIconListItem: + text: "Voice" + on_release: root.ids.screen_manager.app.voice_action(self) + # _no_ripple_effect: True + + IconLeftWidget: + icon: "phone-in-talk" + on_release: root.ids.screen_manager.app.voice_action(self) # OneLineIconListItem: @@ -1790,7 +1800,7 @@ MDScreen: height: dp(48) MDLabel: - text: "Use high-quality voice for PTT" + text: "High-quality codec for LXMF PTT" font_style: "H6" MDSwitch: @@ -1799,6 +1809,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: "Enable voice calls" + font_style: "H6" + + MDSwitch: + id: settings_voice_enabled + pos_hint: {"center_y": 0.3} + disabled: False + active: False + # MDBoxLayout: # orientation: "horizontal" # size_hint_y: None diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py new file mode 100644 index 0000000..2c2c135 --- /dev/null +++ b/sbapp/ui/voice.py @@ -0,0 +1,108 @@ +import time +import RNS + +from typing import Union +from kivy.metrics import dp,sp +from kivy.lang.builder import Builder +from kivy.core.clipboard import Clipboard +from kivy.utils import escape_markup +from kivymd.uix.recycleview import MDRecycleView +from kivymd.uix.list import OneLineIconListItem +from kivymd.uix.pickers import MDColorPicker +from kivymd.uix.button import MDRectangleFlatButton +from kivymd.uix.dialog import MDDialog +from kivymd.icon_definitions import md_icons +from kivymd.toast import toast +from kivy.properties import StringProperty, BooleanProperty +from kivy.effects.scroll import ScrollEffect +from kivy.clock import Clock +from sideband.sense import Telemeter +import threading +from datetime import datetime + +if RNS.vendor.platformutils.get_platform() == "android": + from ui.helpers import ts_format + from android.permissions import request_permissions, check_permission +else: + from .helpers import ts_format + +class Voice(): + def __init__(self, app): + self.app = app + self.screen = None + self.rnstatus_screen = None + self.rnstatus_instance = None + self.logviewer_screen = None + + if not self.app.root.ids.screen_manager.has_screen("voice_screen"): + self.screen = Builder.load_string(layout_voice_screen) + self.screen.app = self.app + self.screen.delegate = self + self.app.root.ids.screen_manager.add_widget(self.screen) + + self.screen.ids.voice_scrollview.effect_cls = ScrollEffect + info = "Voice services UI" + info += "" + + if self.app.theme_cls.theme_style == "Dark": + info = "[color=#"+self.app.dark_theme_text_color+"]"+info+"[/color]" + + self.screen.ids.voice_info.text = info + +layout_voice_screen = """ +MDScreen: + name: "voice_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Voice" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.close_any_action(self)], + ] + + ScrollView: + id: voice_scrollview + + MDBoxLayout: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(32), dp(28), dp(16)] + + # MDLabel: + # text: "Utilities & Tools" + # font_style: "H6" + + MDLabel: + id: voice_info + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(35)] + + MDRectangleFlatIconButton: + id: rnstatus_button + icon: "wifi-check" + text: "Reticulum Status" + 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.rnstatus_action(self) + disabled: False +""" From 143f440df7a0fd945ddeb8004a55cc620729efe7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 18:32:31 +0100 Subject: [PATCH 054/271] Added basic LXST voice call UI --- sbapp/main.py | 39 ++++++--- sbapp/sideband/core.py | 28 ++++++- sbapp/sideband/voice.py | 15 ++-- sbapp/ui/conversations.py | 126 +++++++++++++++++++++------- sbapp/ui/voice.py | 169 ++++++++++++++++++++++++++++++++------ 5 files changed, 298 insertions(+), 79 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e886cbd..ea0631e 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.4.0" +__version__ = "1.5.0" __variant__ = "" import sys @@ -1597,13 +1597,17 @@ class SidebandApp(MDApp): self.conversation_action(item) def conversation_action(self, sender): - context_dest = sender.sb_uid - def cb(dt): - self.open_conversation(context_dest) - def cbu(dt): - self.conversations_view.update() - Clock.schedule_once(cb, 0.15) - Clock.schedule_once(cbu, 0.15+0.25) + if sender.conv_type == self.sideband.CONV_P2P: + context_dest = sender.sb_uid + def cb(dt): self.open_conversation(context_dest) + def cbu(dt): self.conversations_view.update() + Clock.schedule_once(cb, 0.15) + Clock.schedule_once(cbu, 0.15+0.25) + + elif sender.conv_type == self.sideband.CONV_VOICE: + identity_hash = sender.sb_uid + def cb(dt): self.dial_action(identity_hash) + Clock.schedule_once(cb, 0.15) def open_conversation(self, context_dest, direction="left"): self.rec_dialog_is_open = False @@ -2750,7 +2754,8 @@ class SidebandApp(MDApp): n_address = dialog.d_content.ids["n_address_field"].text n_name = dialog.d_content.ids["n_name_field"].text n_trusted = dialog.d_content.ids["n_trusted"].active - new_result = self.sideband.new_conversation(n_address, n_name, n_trusted) + n_voice_only = dialog.d_content.ids["n_voice_only"].active + new_result = self.sideband.new_conversation(n_address, n_name, n_trusted, n_voice_only) except Exception as e: RNS.log("Error while creating conversation: "+str(e), RNS.LOG_ERROR) @@ -5257,7 +5262,7 @@ class SidebandApp(MDApp): self.voice_screen = Voice(self) self.voice_ready = True - def voice_open(self, sender=None, direction="left", no_transition=False): + def voice_open(self, sender=None, direction="left", no_transition=False, dial_on_complete=None): if no_transition: self.root.ids.screen_manager.transition = self.no_transition else: @@ -5271,21 +5276,29 @@ class SidebandApp(MDApp): if no_transition: self.root.ids.screen_manager.transition = self.slide_transition - def voice_action(self, sender=None, direction="left"): + self.voice_screen.update_call_status() + if dial_on_complete: + self.voice_screen.dial_target = dial_on_complete + self.voice_screen.screen.ids.identity_hash.text = RNS.hexrep(dial_on_complete, delimit=False) + Clock.schedule_once(self.voice_screen.dial_action, 0.25) + + def voice_action(self, sender=None, direction="left", dial_on_complete=None): if self.voice_ready: - self.voice_open(direction=direction) + self.voice_open(direction=direction, dial_on_complete=dial_on_complete) else: self.loader_action(direction=direction) def final(dt): self.voice_init() def o(dt): - self.voice_open(no_transition=True) + self.voice_open(no_transition=True, dial_on_complete=dial_on_complete) Clock.schedule_once(o, ll_ot) Clock.schedule_once(final, ll_ft) def close_sub_voice_action(self, sender=None): self.voice_action(direction="right") + def dial_action(self, identity_hash): + self.voice_action(dial_on_complete=identity_hash) ### Telemetry Screen ###################################### diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 6e70381..291a437 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -107,6 +107,7 @@ class SidebandCore(): CONV_P2P = 0x01 CONV_GROUP = 0x02 CONV_BROADCAST = 0x03 + CONV_VOICE = 0x04 MAX_ANNOUNCES = 24 @@ -2639,6 +2640,7 @@ class SidebandCore(): "last_rx": last_rx, "last_tx": last_tx, "last_activity": last_activity, + "type": entry[4], "trust": entry[5], "data": data, } @@ -2790,6 +2792,27 @@ class SidebandCore(): self.__event_conversations_changed() + def _db_create_voice_object(self, identity_hash, name = None, trust = False): + RNS.log("Creating voice object for "+RNS.prettyhexrep(identity_hash), RNS.LOG_DEBUG) + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + def_name = "".encode("utf-8") + query = "INSERT INTO conv (dest_context, last_tx, last_rx, unread, type, trust, name, data) values (?, ?, ?, ?, ?, ?, ?, ?)" + data = (identity_hash, 0, time.time(), 0, SidebandCore.CONV_VOICE, 0, def_name, msgpack.packb(None)) + + dbc.execute(query, data) + db.commit() + + if trust: + self._db_conversation_set_trusted(identity_hash, True) + + if name != None and name != "": + self._db_conversation_set_name(identity_hash, name) + + self.__event_conversations_changed() + def _db_delete_message(self, msg_hash): RNS.log("Deleting message "+RNS.prettyhexrep(msg_hash)) with self.db_lock: @@ -4630,7 +4653,7 @@ class SidebandCore(): RNS.log("Error while sending message: "+str(e), RNS.LOG_ERROR) return False - def new_conversation(self, dest_str, name = "", trusted = False): + def new_conversation(self, dest_str, name = "", trusted = False, voice_only = False): if len(dest_str) != RNS.Reticulum.TRUNCATED_HASHLENGTH//8*2: return False @@ -4640,7 +4663,8 @@ class SidebandCore(): RNS.log("Cannot create conversation with own LXMF address", RNS.LOG_ERROR) return False else: - self._db_create_conversation(addr_b, name, trusted) + if not voice_only: self._db_create_conversation(addr_b, name, trusted) + else: self._db_create_voice_object(addr_b, name, trusted) except Exception as e: RNS.log("Error while creating conversation: "+str(e), RNS.LOG_ERROR) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 09837d0..eb346f0 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -92,18 +92,13 @@ class ReticulumTelephone(): self.telephone.teardown() self.telephone = None + def hangup(self): self.telephone.hangup() + def answer(self): self.telephone.answer(self.caller) + def set_busy(self, busy): self.telephone.set_busy(busy) + def dial(self, identity_hash): self.last_dialled_identity_hash = identity_hash - self.telephone.set_busy(True) - identity_hash = bytes.fromhex(identity_hash) destination_hash = RNS.Destination.hash_from_name_and_identity("lxst.telephony", identity_hash) - if not RNS.Transport.has_path(destination_hash): - RNS.Transport.request_path(destination_hash) - def spincheck(): return RNS.Transport.has_path(destination_hash) - self.__spin(spincheck, "Requesting path for call to "+RNS.prettyhexrep(identity_hash), self.path_time) - if not spincheck(): RNS.log("Path request timed out", RNS.LOG_DEBUG) - - self.telephone.set_busy(False) if RNS.Transport.has_path(destination_hash): call_hops = RNS.Transport.hops_to(destination_hash) cs = "" if call_hops == 1 else "s" @@ -111,7 +106,7 @@ class ReticulumTelephone(): identity = RNS.Identity.recall(destination_hash) self.call(identity) else: - pass + return "no_path" def redial(self, args=None): if self.last_dialled_identity_hash: self.dial(self.last_dialled_identity_hash) diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index cc58db1..d677c73 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -6,6 +6,7 @@ from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty, BooleanProperty from kivymd.uix.list import MDList, IconLeftWidget, IconRightWidget, OneLineAvatarIconListItem from kivymd.uix.menu import MDDropdownMenu +from kivymd.toast import toast from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock @@ -53,6 +54,7 @@ class Conversations(): self.app.root.ids.screen_manager.add_widget(self.screen) self.conversation_dropdown = None + self.voice_dropdown = None self.delete_dialog = None self.clear_dialog = None self.clear_telemetry_dialog = None @@ -91,6 +93,7 @@ class Conversations(): self.app.sideband.setstate("wants.viewupdate.conversations", False) def trust_icon(self, conv): + conv_type = conv["type"] context_dest = conv["dest"] unread = conv["unread"] appearance = self.app.sideband.peer_appearance(context_dest, conv=conv) @@ -106,25 +109,28 @@ class Conversations(): trust_icon = appearance[0] or da[0]; else: - if self.app.sideband.requests_allowed_from(context_dest): - if unread: - if is_trusted: - trust_icon = "email-seal" - else: - trust_icon = "email" - else: - trust_icon = "account-lock-open" + if conv_type == self.app.sideband.CONV_VOICE: + trust_icon = "phone" else: - if is_trusted: + if self.app.sideband.requests_allowed_from(context_dest): if unread: - trust_icon = "email-seal" + if is_trusted: + trust_icon = "email-seal" + else: + trust_icon = "email" else: - trust_icon = "account-check" + trust_icon = "account-lock-open" else: - if unread: - trust_icon = "email" + if is_trusted: + if unread: + trust_icon = "email-seal" + else: + trust_icon = "account-check" else: - trust_icon = "account-question" + if unread: + trust_icon = "email" + else: + trust_icon = "account-question" return trust_icon @@ -166,6 +172,7 @@ class Conversations(): iconl._default_icon_pad = dp(ic_p) iconl.icon_size = dp(ic_s) + iconl.conv_type = conv["type"] return iconl @@ -187,6 +194,7 @@ class Conversations(): for conv in self.context_dests: context_dest = conv["dest"] + conv_type = conv["type"] unread = conv["unread"] last_activity = conv["last_activity"] @@ -203,6 +211,7 @@ class Conversations(): item.sb_uid = context_dest item.sb_unread = unread iconl.sb_uid = context_dest + item.conv_type = conv_type def gen_edit(item): def x(): @@ -366,23 +375,58 @@ class Conversations(): self.delete_dialog.open() return x - # def gen_move_to(item): - # def x(): - # item.dmenu.dismiss() - # self.app.sideband.conversation_set_object(self.conversation_dropdown.context_dest, not self.app.sideband.is_object(self.conversation_dropdown.context_dest)) - # self.app.conversations_view.update() - # return x - def gen_copy_addr(item): def x(): Clipboard.copy(RNS.hexrep(self.conversation_dropdown.context_dest, delimit=False)) + self.voice_dropdown.dismiss() + self.conversation_dropdown.dismiss() + return x + + def gen_call(item): + def x(): + identity = RNS.Identity.recall(self.conversation_dropdown.context_dest) + if identity: self.app.dial_action(identity.hash) + else: toast("Can't call, identity unknown") item.dmenu.dismiss() return x item.iconr = IconRightWidget(icon="dots-vertical"); + if self.voice_dropdown == None: + dmi_h = 40 + dmv_items = [ + { + "viewclass": "OneLineListItem", + "text": "Edit", + "height": dp(dmi_h), + "on_release": gen_edit(item) + }, + { + "text": "Copy Identity Hash", + "viewclass": "OneLineListItem", + "height": dp(dmi_h), + "on_release": gen_copy_addr(item) + }, + { + "text": "Delete", + "viewclass": "OneLineListItem", + "height": dp(dmi_h), + "on_release": gen_del(item) + } + ] + + self.voice_dropdown = MDDropdownMenu( + caller=item.iconr, + items=dmv_items, + position="auto", + width=dp(256), + elevation=0, + radius=dp(3), + ) + self.voice_dropdown.effect_cls = ScrollEffect + self.voice_dropdown.md_bg_color = self.app.color_hover + if self.conversation_dropdown == None: - obj_str = "conversations" if is_object else "objects" dmi_h = 40 dm_items = [ { @@ -391,18 +435,18 @@ class Conversations(): "height": dp(dmi_h), "on_release": gen_edit(item) }, + { + "viewclass": "OneLineListItem", + "text": "Call", + "height": dp(dmi_h), + "on_release": gen_call(item) + }, { "text": "Copy Address", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": gen_copy_addr(item) }, - # { - # "text": "Move to objects", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_move_to(item) - # }, { "text": "Clear Messages", "viewclass": "OneLineListItem", @@ -434,11 +478,15 @@ class Conversations(): self.conversation_dropdown.effect_cls = ScrollEffect self.conversation_dropdown.md_bg_color = self.app.color_hover - item.dmenu = self.conversation_dropdown + if conv_type == self.app.sideband.CONV_VOICE: + item.dmenu = self.voice_dropdown + else: + item.dmenu = self.conversation_dropdown def callback_factory(ref, dest): def x(sender): self.conversation_dropdown.context_dest = dest + self.voice_dropdown.context_dest = dest ref.dmenu.caller = ref.iconr ref.dmenu.open() return x @@ -448,6 +496,7 @@ class Conversations(): item.add_widget(item.iconr) item.trusted = self.app.sideband.is_trusted(context_dest, conv_data=existing_conv) + item.conv_type = conv_type self.added_item_dests.append(context_dest) self.list.add_widget(item) @@ -519,7 +568,7 @@ Builder.load_string(""" orientation: "vertical" spacing: "24dp" size_hint_y: None - height: dp(250) + height: dp(260) MDTextField: id: n_address_field @@ -540,7 +589,7 @@ Builder.load_string(""" orientation: "horizontal" size_hint_y: None padding: [0,0,dp(8),dp(24)] - height: dp(48) + height: dp(24) MDLabel: id: "trusted_switch_label" text: "Trusted" @@ -551,6 +600,21 @@ Builder.load_string(""" pos_hint: {"center_y": 0.3} active: False + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(8),dp(24)] + height: dp(24) + MDLabel: + id: "trusted_switch_label" + text: "Voice Only" + font_style: "H6" + + MDSwitch: + id: n_voice_only + pos_hint: {"center_y": 0.3} + active: False + orientation: "vertical" spacing: "16dp" diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 2c2c135..f07fc04 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -30,9 +30,10 @@ class Voice(): def __init__(self, app): self.app = app self.screen = None - self.rnstatus_screen = None - self.rnstatus_instance = None - self.logviewer_screen = None + self.settings_screen = None + self.dial_target = None + self.ui_updater = None + self.path_requesting = None if not self.app.root.ids.screen_manager.has_screen("voice_screen"): self.screen = Builder.load_string(layout_voice_screen) @@ -41,13 +42,131 @@ class Voice(): self.app.root.ids.screen_manager.add_widget(self.screen) self.screen.ids.voice_scrollview.effect_cls = ScrollEffect - info = "Voice services UI" - info += "" + # info = "Voice services UI" + # info += "" - if self.app.theme_cls.theme_style == "Dark": - info = "[color=#"+self.app.dark_theme_text_color+"]"+info+"[/color]" + # if self.app.theme_cls.theme_style == "Dark": + # info = "[color=#"+self.app.dark_theme_text_color+"]"+info+"[/color]" - self.screen.ids.voice_info.text = info + # self.screen.ids.voice_info.text = info + + def update_call_status(self, dt=None): + if self.app.root.ids.screen_manager.current == "voice_screen": + if self.ui_updater == None: self.ui_updater = Clock.schedule_interval(self.update_call_status, 0.5) + else: + if self.ui_updater: self.ui_updater.cancel() + + db = self.screen.ids.dial_button + ih = self.screen.ids.identity_hash + if self.app.sideband.voice_running: + telephone = self.app.sideband.telephone + if self.path_requesting: + db.disabled = True + ih.disabled = True + + else: + if telephone.is_available: + ih.disabled = False + self.target_input_action(ih) + else: + ih.disabled = True + + if telephone.is_in_call or telephone.call_is_connecting: + ih.disabled = True + db.disabled = False + db.text = "Hang up" + db.icon = "phone-hangup" + + elif telephone.is_ringing: + ih.disabled = True + db.disabled = False + db.text = "Answer" + db.icon = "phone-ring" + if telephone.caller: ih.text = RNS.hexrep(telephone.caller.hash, delimit=False) + + else: + db.disabled = True; db.text = "Voice calls disabled" + ih.disabled = True + + def target_valid(self): + if self.app.sideband.voice_running: + db = self.screen.ids.dial_button + db.disabled = False; db.text = "Call" + db.icon = "phone-outgoing" + + def target_invalid(self): + if self.app.sideband.voice_running: + db = self.screen.ids.dial_button + db.disabled = True; db.text = "Call" + db.icon = "phone-outgoing" + + def target_input_action(self, sender): + if sender: + target_hash = sender.text + if len(target_hash) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8*2: + try: + identity_hash = bytes.fromhex(target_hash) + self.dial_target = identity_hash + self.target_valid() + + except Exception as e: self.target_invalid() + else: self.target_invalid() + + def request_path(self, destination_hash): + if not self.path_requesting: + self.app.sideband.telephone.set_busy(True) + toast("Requesting path...") + self.screen.ids.dial_button.disabled = True + self.path_requesting = destination_hash + RNS.Transport.request_path(destination_hash) + threading.Thread(target=self._path_wait_job, daemon=True).start() + + else: + toast("Waiting for path request answer...") + + def _path_wait_job(self): + timeout = time.time()+self.app.sideband.telephone.PATH_TIME + while not RNS.Transport.has_path(self.path_requesting) and time.time() < timeout: + time.sleep(0.25) + + self.app.sideband.telephone.set_busy(False) + if RNS.Transport.has_path(self.path_requesting): + RNS.log(f"Calling {RNS.prettyhexrep(self.dial_target)}...", RNS.LOG_DEBUG) + self.app.sideband.telephone.dial(self.dial_target) + Clock.schedule_once(self.update_call_status, 0.1) + + else: + Clock.schedule_once(self._path_request_failed, 0.05) + Clock.schedule_once(self.update_call_status, 0.1) + + self.path_requesting = None + self.update_call_status() + + def _path_request_failed(self, dt): + toast("Path request timed out") + + def dial_action(self, sender=None): + if self.app.sideband.voice_running: + if self.app.sideband.telephone.is_available: + + destination_hash = RNS.Destination.hash_from_name_and_identity("lxst.telephony", self.dial_target) + if not RNS.Transport.has_path(destination_hash): + self.request_path(destination_hash) + + else: + RNS.log(f"Calling {RNS.prettyhexrep(self.dial_target)}...", RNS.LOG_DEBUG) + self.app.sideband.telephone.dial(self.dial_target) + self.update_call_status() + + elif self.app.sideband.telephone.is_in_call or self.app.sideband.telephone.call_is_connecting: + RNS.log(f"Hanging up", RNS.LOG_DEBUG) + self.app.sideband.telephone.hangup() + self.update_call_status() + + elif self.app.sideband.telephone.is_ringing: + RNS.log(f"Answering", RNS.LOG_DEBUG) + self.app.sideband.telephone.answer() + self.update_call_status() layout_voice_screen = """ MDScreen: @@ -76,17 +195,21 @@ MDScreen: height: self.minimum_height padding: [dp(28), dp(32), dp(28), dp(16)] - # MDLabel: - # text: "Utilities & Tools" - # font_style: "H6" - - MDLabel: - id: voice_info - markup: True - text: "" + MDBoxLayout: + orientation: "vertical" + # spacing: "24dp" size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] + height: self.minimum_height + padding: [dp(0), dp(12), dp(0), dp(0)] + + MDTextField: + id: identity_hash + hint_text: "Identity hash" + mode: "rectangle" + # size_hint: [1.0, None] + pos_hint: {"center_x": .5} + max_text_length: 32 + on_text: root.delegate.target_input_action(self) MDBoxLayout: orientation: "vertical" @@ -96,13 +219,13 @@ MDScreen: padding: [dp(0), dp(35), dp(0), dp(35)] MDRectangleFlatIconButton: - id: rnstatus_button - icon: "wifi-check" - text: "Reticulum Status" + id: dial_button + icon: "phone-outgoing" + text: "Call" 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.rnstatus_action(self) - disabled: False + on_release: root.delegate.dial_action(self) + disabled: True """ From 1c9342d772a374bfd7a481451451869279b912f0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 19:16:54 +0100 Subject: [PATCH 055/271] Added full RNS status button on Android --- .gitignore | 1 + sbapp/Makefile | 3 +++ sbapp/main.py | 19 ++++++++++++++----- setup.py | 1 + 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index d7d285d..7750d9e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ sbapp/bin sbapp/app_storage sbapp/RNS sbapp/LXMF +sbapp/LXST sbapp/precompiled sbapp/*.DS_Store sbapp/*.pyc diff --git a/sbapp/Makefile b/sbapp/Makefile index b6b55dc..d0f9028 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -97,6 +97,9 @@ getrns: -(rm ./RNS/__pycache__ -r) (cp -rv ../../LXMF/LXMF ./;rm ./LXMF/Utilities/LXMF) -(rm ./LXMF/__pycache__ -r) + (cp -rv ../../LXST/LXST ./;rm ./LXST/Utilities/LXST) + -(rm ./LXST/__pycache__ -r) + -(rm ./LXST/Utilities/__pycache__ -r) cleanrns: -(rm ./RNS -r) diff --git a/sbapp/main.py b/sbapp/main.py index ea0631e..c816eb8 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2572,21 +2572,27 @@ class SidebandApp(MDApp): if RNS.vendor.platformutils.is_android(): hs = dp(22) yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + full_button = MDRectangleFlatButton(text="Full RNS Status",font_size=dp(18), theme_text_color="Custom", line_color=self.color_accept, text_color=self.color_accept) dialog = MDDialog( title="Connectivity Status", text=str(self.get_connectivity_text()), - buttons=[ yes_button ], + buttons=[full_button, yes_button], # elevation=0, ) def cs_updater(dt): dialog.text = str(self.get_connectivity_text()) def dl_yes(s): - self.connectivity_updater.cancel() dialog.dismiss() if self.connectivity_updater != None: self.connectivity_updater.cancel() + def cb_rns(sender): + dialog.dismiss() + if self.connectivity_updater != None: + self.connectivity_updater.cancel() + self.rnstatus_action() yes_button.bind(on_release=dl_yes) + full_button.bind(on_release=cb_rns) dialog.open() if self.connectivity_updater != None: @@ -2595,9 +2601,12 @@ class SidebandApp(MDApp): self.connectivity_updater = Clock.schedule_interval(cs_updater, 2.0) else: - if not self.utilities_ready: - self.utilities_init() - self.utilities_screen.rnstatus_action() + self.rnstatus_action() + + def rnstatus_action(self, sender=None): + if not self.utilities_ready: + self.utilities_init() + self.utilities_screen.rnstatus_action() def ingest_lxm_action(self, sender): def cb(dt): diff --git a/setup.py b/setup.py index aa03687..8d4fea9 100644 --- a/setup.py +++ b/setup.py @@ -123,6 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy<=1.26.4", + "lxst>=0.2.2", "mistune>=3.0.2", "beautifulsoup4", "pycodec2;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From 9e058cc12ede4643685c652b9ab7944159e5d154 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Mar 2025 20:44:48 +0100 Subject: [PATCH 056/271] Fixed inadverdent audio message play on swipe back --- sbapp/ui/messages.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 6eb696f..3a0722c 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -730,16 +730,23 @@ class Messages(): if has_audio: def play_audio(sender): - self.app.play_audio_field(sender.audio_field) - stored_color = sender.md_bg_color - if sender.lsource == self.app.sideband.lxmf_destination.hash: - sender.md_bg_color = mdc(c_delivered, intensity_play) - else: - sender.md_bg_color = mdc(c_received, intensity_play) + touch_event = None; block_play = False + if sender and hasattr(sender, "last_touch"): touch_event = sender.last_touch + if touch_event and hasattr(touch_event, "dpos"): + delta = abs(touch_event.dpos[0]) + abs(touch_event.dpos[1]) + if delta >= 2.0: block_play = True - def cb(dt): - sender.md_bg_color = stored_color - Clock.schedule_once(cb, 0.25) + if not block_play: + self.app.play_audio_field(sender.audio_field) + stored_color = sender.md_bg_color + if sender.lsource == self.app.sideband.lxmf_destination.hash: + sender.md_bg_color = mdc(c_delivered, intensity_play) + else: + sender.md_bg_color = mdc(c_received, intensity_play) + + def cb(dt): + sender.md_bg_color = stored_color + Clock.schedule_once(cb, 0.25) item.has_audio = True item.audio_size = len(audio_field[1]) From b1678a1532f6eaf584b56c7ea4e38c759965ba5f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 10 Mar 2025 17:25:40 +0100 Subject: [PATCH 057/271] Voice call UI additions --- sbapp/main.py | 31 ++++++++++++++++++++++++++++++- sbapp/sideband/core.py | 27 ++++++++++++++++++++++++++- sbapp/sideband/voice.py | 5 ++++- sbapp/ui/voice.py | 4 +++- 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index c816eb8..15f136b 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1096,6 +1096,10 @@ class SidebandApp(MDApp): self.hw_error_dialog.open() self.hw_error_dialog.is_open = True + incoming_call = self.sideband.getstate("voice.incoming_call") + if incoming_call: + self.sideband.setstate("voice.incoming_call", None) + toast(f"Call from {incoming_call}", duration=7) if self.root.ids.screen_manager.current == "messages_screen": self.messages_view.update() @@ -1370,6 +1374,15 @@ class SidebandApp(MDApp): if text == "o": self.objects_action() + if text == "e": + self.voice_action() + + if text == " ": + self.voice_answer_action() + + if text == ".": + self.voice_reject_action() + if text == "r": if self.root.ids.screen_manager.current == "conversations_screen": if self.include_objects: @@ -5309,6 +5322,16 @@ class SidebandApp(MDApp): def dial_action(self, identity_hash): self.voice_action(dial_on_complete=identity_hash) + def voice_answer_action(self, sender=None): + if self.sideband.voice_running: + if self.sideband.telephone.is_ringing: self.sideband.telephone.answer() + + def voice_reject_action(self, sender=None): + if self.sideband.voice_running: + if self.sideband.telephone.is_ringing or self.sideband.telephone.is_in_call: + self.sideband.telephone.hangup() + toast("Call ended") + ### Telemetry Screen ###################################### @@ -6241,15 +6264,21 @@ If you use Reticulum and LXMF on hardware that does not carry any identifiers ti - [b]Ctrl-Shift-F[/b] add file - [b]Ctrl-D[/b] or [b]Ctrl-S[/b] Send message - [b]Voice & PTT[/b] + [b]Voice & PTT Messages[/b] - [b]Space[/b] Start/stop recording - [b]Enter[/b] Save recording to message - With PTT enabled, hold [b]Space[/b] to talk + [b]Voice Calls[/b] + - [b]Ctrl-Space[/b] Answer incoming call + - [b]Ctrl-.[/b] Reject incoming call + - [b]Ctrl-.[/b] Hang up active call + [b]Navigation[/b] - [b]Ctrl-[i]n[/i][/b] Go to conversation number [i]n[/i] - [b]Ctrl-R[/b] Go to Conversations - [b]Ctrl-O[/b] Go to Objects & Devices + - [b]Ctrl-E[/b] Go to Voice - [b]Ctrl-L[/b] Go to Announce Stream - [b]Ctrl-M[/b] Go to Situation Map - [b]Ctrl-U[/b] Go to Utilities diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 291a437..168cb7c 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1224,6 +1224,27 @@ class SidebandCore(): RNS.log("Could not decode a valid peer name from data: "+str(e), RNS.LOG_DEBUG) return RNS.prettyhexrep(context_dest) + def voice_display_name(self, identity_hash): + context_dest = identity_hash + if context_dest == self.lxmf_destination.hash: + return self.config["display_name"] + + try: + lxmf_destination_hash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", identity_hash) + existing_voice = self._db_conversation(context_dest) + existing_lxmf = self._db_conversation(lxmf_destination_hash) + + print(RNS.prettyhexrep(lxmf_destination_hash)) + print(f"VOICE {existing_voice}") + print(f"LXMF {existing_lxmf}") + + if existing_lxmf: return self.peer_display_name(lxmf_destination_hash) + else: return self.peer_display_name(identity_hash) + + except Exception as e: + RNS.log("Could not decode a valid peer name from data: "+str(e), RNS.LOG_DEBUG) + return RNS.prettyhexrep(context_dest) + def clear_conversation(self, context_dest): self._db_clear_conversation(context_dest) @@ -5220,7 +5241,7 @@ class SidebandCore(): RNS.log("Starting voice service", RNS.LOG_DEBUG) self.voice_running = True from .voice import ReticulumTelephone - self.telephone = ReticulumTelephone(self.identity) + self.telephone = ReticulumTelephone(self.identity, owner=self) ringtone_path = os.path.join(self.asset_dir, "audio", "notifications", "soft1.opus") self.telephone.set_ringtone(ringtone_path) @@ -5244,6 +5265,10 @@ class SidebandCore(): RNS.log(f"An error occurred while stopping voice services, the contained exception was: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) + def incoming_call(self, remote_identity): + display_name = self.voice_display_name(remote_identity.hash) + self.setstate("voice.incoming_call", display_name) + rns_config = """# This template is used to generate a # running configuration for Sideband's # internal RNS instance. Incorrect changes diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index eb346f0..3754fc1 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -22,9 +22,10 @@ class ReticulumTelephone(): WAIT_TIME = 60 PATH_TIME = 10 - def __init__(self, identity, verbosity = 0, service = False): + def __init__(self, identity, owner = None, service = False): self.identity = identity self.service = service + self.owner = owner self.config = None self.should_run = False self.telephone = None @@ -124,6 +125,8 @@ class ReticulumTelephone(): self.caller = remote_identity self.direction = "from" if self.direction == None else "to" RNS.log(f"Incoming call from {RNS.prettyhexrep(self.caller.hash)}", RNS.LOG_DEBUG) + if self.owner: + self.owner.incoming_call(remote_identity) def call_ended(self, remote_identity): if self.is_in_call or self.is_ringing or self.call_is_connecting: diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index f07fc04..fa00ea0 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -54,7 +54,9 @@ class Voice(): if self.app.root.ids.screen_manager.current == "voice_screen": if self.ui_updater == None: self.ui_updater = Clock.schedule_interval(self.update_call_status, 0.5) else: - if self.ui_updater: self.ui_updater.cancel() + if self.ui_updater: + self.ui_updater.cancel() + self.ui_updater = None db = self.screen.ids.dial_button ih = self.screen.ids.identity_hash From a24f1f107357ce56a68eaa5fe36abd18a53b3c6a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 11 Mar 2025 17:35:04 +0100 Subject: [PATCH 058/271] Adjust window size on small devices --- sbapp/main.py | 24 ++++++++++++++++++++---- setup.py | 2 +- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 15f136b..ba65c34 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -25,8 +25,8 @@ import base64 import threading import RNS.vendor.umsgpack as msgpack -WINDOW_DEFAULT_WIDTH = "494" -WINDOW_DEFAULT_HEIGHT = "800" +WINDOW_DEFAULT_WIDTH = 494 +WINDOW_DEFAULT_HEIGHT = 800 app_ui_scaling_path = None def apply_ui_scale(): @@ -176,9 +176,25 @@ if not args.daemon: sys.path.append(local) if not RNS.vendor.platformutils.is_android(): + model = None + max_width = WINDOW_DEFAULT_WIDTH + max_height = WINDOW_DEFAULT_HEIGHT + + try: + if os.path.isfile("/sys/firmware/devicetree/base/model"): + with open("/sys/firmware/devicetree/base/model", "r") as mf: + model = mf.read() + except: pass + + if model: + if model.startswith("Raspberry Pi "): max_height = 625 + + window_width = min(WINDOW_DEFAULT_WIDTH, max_width) + window_height = min(WINDOW_DEFAULT_HEIGHT, max_height) + from kivy.config import Config - Config.set("graphics", "width", WINDOW_DEFAULT_WIDTH) - Config.set("graphics", "height", WINDOW_DEFAULT_HEIGHT) + Config.set("graphics", "width", str(window_width)) + Config.set("graphics", "height", str(window_height)) if args.daemon: from .sideband.core import SidebandCore diff --git a/setup.py b/setup.py index 8d4fea9..2dfcbba 100644 --- a/setup.py +++ b/setup.py @@ -123,7 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy<=1.26.4", - "lxst>=0.2.2", + "lxst>=0.2.4", "mistune>=3.0.2", "beautifulsoup4", "pycodec2;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From 5e749bc0c3fd1af9da0c4ad4fcb0df3ab07d3273 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 11 Mar 2025 17:38:42 +0100 Subject: [PATCH 059/271] Fixed voice dialog not being dismissed --- sbapp/ui/conversations.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index d677c73..ac263a5 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -292,7 +292,7 @@ class Conversations(): yes_button.bind(on_release=dl_yes) no_button.bind(on_release=dl_no) - item.dmenu.dismiss() + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() dialog.open() RNS.log("Generated edit dialog in "+str(RNS.prettytime(time.time()-t_s)), RNS.LOG_DEBUG) @@ -321,7 +321,7 @@ class Conversations(): yes_button.bind(on_release=dl_yes) no_button.bind(on_release=dl_no) - item.dmenu.dismiss() + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() self.clear_dialog.open() return x @@ -345,7 +345,7 @@ class Conversations(): yes_button.bind(on_release=dl_yes) no_button.bind(on_release=dl_no) - item.dmenu.dismiss() + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() self.clear_telemetry_dialog.open() return x @@ -371,15 +371,14 @@ class Conversations(): yes_button.bind(on_release=dl_yes) no_button.bind(on_release=dl_no) - item.dmenu.dismiss() + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() self.delete_dialog.open() return x def gen_copy_addr(item): def x(): Clipboard.copy(RNS.hexrep(self.conversation_dropdown.context_dest, delimit=False)) - self.voice_dropdown.dismiss() - self.conversation_dropdown.dismiss() + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() return x def gen_call(item): @@ -387,7 +386,7 @@ class Conversations(): identity = RNS.Identity.recall(self.conversation_dropdown.context_dest) if identity: self.app.dial_action(identity.hash) else: toast("Can't call, identity unknown") - item.dmenu.dismiss() + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() return x item.iconr = IconRightWidget(icon="dots-vertical"); From 86e68f0dba0de71b4e19db43bd93cd8db582059f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 12 Mar 2025 10:52:05 +0100 Subject: [PATCH 060/271] Fixed key mapping --- sbapp/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index ba65c34..c157d92 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1289,13 +1289,13 @@ class SidebandApp(MDApp): self.messages_view.ids.message_text.write_tab = True Clock.schedule_once(tab_job, 0.15) - elif self.rec_dialog != None and self.rec_dialog_is_open: + elif len(modifiers) == 0 and self.rec_dialog != None and self.rec_dialog_is_open: if text == " ": self.msg_rec_a_rec(None) elif keycode == 40: self.msg_rec_a_save(None) - elif not self.rec_dialog_is_open and not self.messages_view.ids.message_text.focus and self.messages_view.ptt_enabled and keycode == 44: + elif len(modifiers) == 0 and not self.rec_dialog_is_open and not self.messages_view.ids.message_text.focus and self.messages_view.ptt_enabled and keycode == 44: if not self.key_ptt_down: self.key_ptt_down = True self.message_ptt_down_action() From 3d7e894a9d9fca71b9423e389d01698d13115327 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 11:21:43 +0100 Subject: [PATCH 061/271] Updated dependencies --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 2dfcbba..83d4476 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.2", - "lxmf>=0.6.0", + "rns>=0.9.3", + "lxmf>=0.6.2", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 4d9bba3e4cb2ab2a6746c6f2c70eed0788fc324e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 14:09:38 +0100 Subject: [PATCH 062/271] Added audio device config ui --- sbapp/Makefile | 1 + sbapp/main.py | 3 + sbapp/sideband/core.py | 19 ++-- sbapp/sideband/voice.py | 24 ++++- sbapp/ui/utilities.py | 4 +- sbapp/ui/voice.py | 218 ++++++++++++++++++++++++++++++++++++++-- setup.py | 2 +- 7 files changed, 250 insertions(+), 21 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index d0f9028..11bdb19 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -104,3 +104,4 @@ getrns: cleanrns: -(rm ./RNS -r) -(rm ./LXMF -r) + -(rm ./LXST -r) diff --git a/sbapp/main.py b/sbapp/main.py index c157d92..d9e3390 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1457,6 +1457,8 @@ class SidebandApp(MDApp): self.close_sub_utilities_action() elif self.root.ids.screen_manager.current == "logviewer_screen": self.close_sub_utilities_action() + elif self.root.ids.screen_manager.current == "voice_settings_screen": + self.close_sub_voice_action() else: self.open_conversations(direction="right") @@ -1534,6 +1536,7 @@ class SidebandApp(MDApp): def announce_now_action(self, sender=None): self.sideband.lxmf_announce() + if self.sideband.telephone: self.sideband.telephone.announce() yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 168cb7c..56f5249 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -535,6 +535,9 @@ class SidebandCore(): # Voice self.config["voice_enabled"] = False + self.config["voice_output"] = None + self.config["voice_input"] = None + self.config["voice_ringer"] = None if not os.path.isfile(self.db_path): self.__db_init() @@ -844,6 +847,12 @@ class SidebandCore(): if not "voice_enabled" in self.config: self.config["voice_enabled"] = False + if not "voice_output" in self.config: + self.config["voice_output"] = None + if not "voice_input" in self.config: + self.config["voice_input"] = None + if not "voice_ringer" in self.config: + self.config["voice_ringer"] = None # Make sure we have a database if not os.path.isfile(self.db_path): @@ -1233,11 +1242,6 @@ class SidebandCore(): lxmf_destination_hash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", identity_hash) existing_voice = self._db_conversation(context_dest) existing_lxmf = self._db_conversation(lxmf_destination_hash) - - print(RNS.prettyhexrep(lxmf_destination_hash)) - print(f"VOICE {existing_voice}") - print(f"LXMF {existing_lxmf}") - if existing_lxmf: return self.peer_display_name(lxmf_destination_hash) else: return self.peer_display_name(identity_hash) @@ -3458,6 +3462,7 @@ class SidebandCore(): if self.config["start_announce"] == True: time.sleep(12) self.lxmf_announce(attached_interface=self.interface_local) + if self.telephone: self.telephone.announce(attached_interface=self.interface_local) threading.Thread(target=job, daemon=True).start() if hasattr(self, "interface_rnode") and self.interface_rnode != None: @@ -3545,6 +3550,7 @@ class SidebandCore(): aif = announce_attached_interface time.sleep(delay) self.lxmf_announce(attached_interface=aif) + if self.telephone: self.telephone.announce(attached_interface=aif) return x threading.Thread(target=gen_announce_job(announce_delay, announce_attached_interface), daemon=True).start() @@ -3759,6 +3765,7 @@ class SidebandCore(): def da(): time.sleep(8) self.lxmf_announce() + if self.telephone: self.telephone.announce() self.last_if_change_announce = time.time() threading.Thread(target=da, daemon=True).start() @@ -5241,7 +5248,7 @@ class SidebandCore(): RNS.log("Starting voice service", RNS.LOG_DEBUG) self.voice_running = True from .voice import ReticulumTelephone - self.telephone = ReticulumTelephone(self.identity, owner=self) + self.telephone = ReticulumTelephone(self.identity, owner=self, speaker=self.config["voice_output"], microphone=self.config["voice_input"], ringer=self.config["voice_ringer"]) ringtone_path = os.path.join(self.asset_dir, "audio", "notifications", "soft1.opus") self.telephone.set_ringtone(ringtone_path) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 3754fc1..9222c10 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -22,7 +22,7 @@ class ReticulumTelephone(): WAIT_TIME = 60 PATH_TIME = 10 - def __init__(self, identity, owner = None, service = False): + def __init__(self, identity, owner = None, service = False, speaker=None, microphone=None, ringer=None): self.identity = identity self.service = service self.owner = owner @@ -37,9 +37,9 @@ class ReticulumTelephone(): self.last_input = None self.first_run = False self.ringtone_path = None - self.speaker_device = None - self.microphone_device = None - self.ringer_device = None + self.speaker_device = speaker + self.microphone_device = microphone + self.ringer_device = ringer self.phonebook = {} self.aliases = {} self.names = {} @@ -58,6 +58,21 @@ class ReticulumTelephone(): self.ringtone_path = ringtone_path self.telephone.set_ringtone(self.ringtone_path) + def set_speaker(self, device): + self.speaker_device = device + self.telephone.set_speaker(self.speaker_device) + + def set_microphone(self, device): + self.microphone_device = device + self.telephone.set_microphone(self.microphone_device) + + def set_ringer(self, device): + self.ringer_device = device + self.telephone.set_ringer(self.ringer_device) + + def announce(self, attached_interface=None): + self.telephone.announce(attached_interface=attached_interface) + @property def is_available(self): return self.state == self.STATE_AVAILABLE @@ -84,7 +99,6 @@ class ReticulumTelephone(): def start(self): if not self.should_run: - self.telephone.announce() self.should_run = True self.run() diff --git a/sbapp/ui/utilities.py b/sbapp/ui/utilities.py index bf46914..d3adcc7 100644 --- a/sbapp/ui/utilities.py +++ b/sbapp/ui/utilities.py @@ -40,7 +40,7 @@ class Utilities(): self.screen.delegate = self self.app.root.ids.screen_manager.add_widget(self.screen) - self.screen.ids.telemetry_scrollview.effect_cls = ScrollEffect + self.screen.ids.utilities_scrollview.effect_cls = ScrollEffect info = "This section contains various utilities and diagnostics tools, " info += "that can be helpful while using Sideband and Reticulum." @@ -220,7 +220,7 @@ MDScreen: ] ScrollView: - id: telemetry_scrollview + id: utilities_scrollview MDBoxLayout: orientation: "vertical" diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index fa00ea0..68e13d0 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -10,6 +10,7 @@ from kivymd.uix.recycleview import MDRecycleView from kivymd.uix.list import OneLineIconListItem from kivymd.uix.pickers import MDColorPicker from kivymd.uix.button import MDRectangleFlatButton +from kivymd.uix.button import MDRectangleFlatIconButton from kivymd.uix.dialog import MDDialog from kivymd.icon_definitions import md_icons from kivymd.toast import toast @@ -34,6 +35,11 @@ class Voice(): self.dial_target = None self.ui_updater = None self.path_requesting = None + self.output_devices = [] + self.input_devices = [] + self.listed_output_devices = [] + self.listed_input_devices = [] + self.listed_ringer_devices = [] if not self.app.root.ids.screen_manager.has_screen("voice_screen"): self.screen = Builder.load_string(layout_voice_screen) @@ -42,13 +48,6 @@ class Voice(): self.app.root.ids.screen_manager.add_widget(self.screen) self.screen.ids.voice_scrollview.effect_cls = ScrollEffect - # info = "Voice services UI" - # info += "" - - # if self.app.theme_cls.theme_style == "Dark": - # info = "[color=#"+self.app.dark_theme_text_color+"]"+info+"[/color]" - - # self.screen.ids.voice_info.text = info def update_call_status(self, dt=None): if self.app.root.ids.screen_manager.current == "voice_screen": @@ -170,6 +169,120 @@ class Voice(): self.app.sideband.telephone.answer() self.update_call_status() + + ### settings screen + ###################################### + + def settings_action(self, sender=None): + if not self.app.root.ids.screen_manager.has_screen("voice_settings_screen"): + self.voice_settings_screen = Builder.load_string(layout_voice_settings_screen) + self.voice_settings_screen.app = self.app + self.voice_settings_screen.delegate = self + self.app.root.ids.screen_manager.add_widget(self.voice_settings_screen) + + self.app.root.ids.screen_manager.transition.direction = "left" + self.app.root.ids.screen_manager.current = "voice_settings_screen" + self.voice_settings_screen.ids.voice_settings_scrollview.effect_cls = ScrollEffect + self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) + + self.update_settings_screen() + + def update_devices(self): + import LXST + self.output_devices = []; self.input_devices = [] + for device in LXST.Sources.Backend().soundcard.all_speakers(): self.output_devices.append(device.name) + for device in LXST.Sinks.Backend().soundcard.all_microphones(): self.input_devices.append(device.name) + if self.app.sideband.config["voice_output"] != None: + if not self.app.sideband.config["voice_output"] in self.output_devices: self.output_devices.append(self.app.sideband.config["voice_output"]) + if self.app.sideband.config["voice_input"] != None: + if not self.app.sideband.config["voice_input"] in self.input_devices: self.input_devices.append(self.app.sideband.config["voice_input"]) + if self.app.sideband.config["voice_ringer"] != None: + if not self.app.sideband.config["voice_ringer"] in self.output_devices: self.output_devices.append(self.app.sideband.config["voice_ringer"]) + + def update_settings_screen(self, sender=None): + bp = 6; ml = 45; fs = 16; ics = 14 + self.update_devices() + + # Output devices + if not "system_default" in self.listed_output_devices: + default_output_button = MDRectangleFlatIconButton(text="System Default", font_size=dp(fs), icon_size=dp(ics), on_release=self.output_device_action) + default_output_button.device = None; default_output_button.size_hint = [1.0, None] + if self.app.sideband.config["voice_output"] == None: default_output_button.icon = "check" + self.voice_settings_screen.ids.output_devices.add_widget(default_output_button) + self.listed_output_devices.append("system_default") + + for device in self.output_devices: + if not device in self.listed_output_devices: + label = device if len(device) < ml else device[:ml-3]+"..." + device_button = MDRectangleFlatIconButton(text=label, font_size=dp(fs), icon_size=dp(ics), on_release=self.output_device_action) + device_button.padding = [dp(bp), dp(bp), dp(bp), dp(bp)]; device_button.size_hint = [1.0, None] + if self.app.sideband.config["voice_output"] == device: device_button.icon = "check" + device_button.device = device + self.voice_settings_screen.ids.output_devices.add_widget(device_button) + self.listed_output_devices.append(device) + + # Input devices + if not "system_default" in self.listed_input_devices: + default_input_button = MDRectangleFlatIconButton(text="System Default", font_size=dp(fs), icon_size=dp(ics), on_release=self.input_device_action) + default_input_button.device = None; default_input_button.size_hint = [1.0, None] + if self.app.sideband.config["voice_output"] == None: default_input_button.icon = "check" + self.voice_settings_screen.ids.input_devices.add_widget(default_input_button) + self.listed_input_devices.append("system_default") + + for device in self.input_devices: + if not device in self.listed_input_devices: + label = device if len(device) < ml else device[:ml-3]+"..." + device_button = MDRectangleFlatIconButton(text=label, font_size=dp(fs), icon_size=dp(ics), on_release=self.input_device_action) + device_button.padding = [dp(bp), dp(bp), dp(bp), dp(bp)]; device_button.size_hint = [1.0, None] + if self.app.sideband.config["voice_input"] == device: device_button.icon = "check" + device_button.device = device + self.voice_settings_screen.ids.input_devices.add_widget(device_button) + self.listed_input_devices.append(device) + + # Ringer devices + if not "system_default" in self.listed_ringer_devices: + default_ringer_button = MDRectangleFlatIconButton(text="System Default", font_size=dp(fs), icon_size=dp(ics), on_release=self.ringer_device_action) + default_ringer_button.device = None; default_ringer_button.size_hint = [1.0, None] + if self.app.sideband.config["voice_ringer"] == None: default_ringer_button.icon = "check" + self.voice_settings_screen.ids.ringer_devices.add_widget(default_ringer_button) + self.listed_ringer_devices.append("system_default") + + for device in self.output_devices: + if not device in self.listed_ringer_devices: + label = device if len(device) < ml else device[:ml-3]+"..." + device_button = MDRectangleFlatIconButton(text=label, font_size=dp(fs), icon_size=dp(ics), on_release=self.ringer_device_action) + device_button.padding = [dp(bp), dp(bp), dp(bp), dp(bp)]; device_button.size_hint = [1.0, None] + if self.app.sideband.config["voice_ringer"] == device: device_button.icon = "check" + device_button.device = device + self.voice_settings_screen.ids.ringer_devices.add_widget(device_button) + self.listed_ringer_devices.append(device) + + + def output_device_action(self, sender=None): + self.app.sideband.config["voice_output"] = sender.device + self.app.sideband.save_configuration() + for w in self.voice_settings_screen.ids.output_devices.children: w.icon = "" + sender.icon = "check" + if self.app.sideband.telephone: + self.app.sideband.telephone.set_speaker(self.app.sideband.config["voice_output"]) + + def input_device_action(self, sender=None): + self.app.sideband.config["voice_input"] = sender.device + self.app.sideband.save_configuration() + for w in self.voice_settings_screen.ids.input_devices.children: w.icon = "" + sender.icon = "check" + if self.app.sideband.telephone: + self.app.sideband.telephone.set_microphone(self.app.sideband.config["voice_input"]) + + def ringer_device_action(self, sender=None): + self.app.sideband.config["voice_ringer"] = sender.device + self.app.sideband.save_configuration() + for w in self.voice_settings_screen.ids.ringer_devices.children: w.icon = "" + sender.icon = "check" + if self.app.sideband.telephone: + self.app.sideband.telephone.set_ringer(self.app.sideband.config["voice_ringer"]) + + layout_voice_screen = """ MDScreen: name: "voice_screen" @@ -185,6 +298,7 @@ MDScreen: [['menu', lambda x: root.app.nav_drawer.set_state("open")]] right_action_items: [ + ['wrench-cog', lambda x: root.delegate.settings_action(self)], ['close', lambda x: root.app.close_any_action(self)], ] @@ -231,3 +345,93 @@ MDScreen: on_release: root.delegate.dial_action(self) disabled: True """ + +layout_voice_settings_screen = """ +MDScreen: + name: "voice_settings_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + id: top_bar + title: "Voice Configuration" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.close_sub_voice_action(self)], + ] + + MDScrollView: + id: voice_settings_scrollview + size_hint_x: 1 + size_hint_y: None + size: [root.width, root.height-root.ids.top_bar.height] + do_scroll_x: False + do_scroll_y: True + + MDBoxLayout: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(32), dp(28), dp(16)] + + MDLabel: + id: voice_settings_info + markup: True + text: "You can configure which audio devices Sideband will use for voice calls, by selecting either the system default device, or specific audio devices available." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + padding: [dp(0), dp(0), dp(0), dp(48)] + + MDLabel: + text: "Output Device" + font_style: "H6" + + MDBoxLayout: + id: output_devices + orientation: "vertical" + spacing: "12dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(48)] + + # MDRectangleFlatIconButton: + # id: output_default_button + # text: "System Default" + # 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.output_device_action(self) + # disabled: False + + MDLabel: + text: "Input Device" + font_style: "H6" + + MDBoxLayout: + id: input_devices + orientation: "vertical" + spacing: "12dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(48)] + + MDLabel: + text: "Ringer Device" + font_style: "H6" + + MDBoxLayout: + id: ringer_devices + orientation: "vertical" + spacing: "12dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(48)] + +""" \ No newline at end of file diff --git a/setup.py b/setup.py index 83d4476..604c0c1 100644 --- a/setup.py +++ b/setup.py @@ -123,7 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy<=1.26.4", - "lxst>=0.2.4", + "lxst>=0.2.7", "mistune>=3.0.2", "beautifulsoup4", "pycodec2;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From dd12a76bf998255a815282d655f7e76cb2fd3b27 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 15:05:51 +0100 Subject: [PATCH 063/271] Added option to block non-trusted callers --- sbapp/sideband/core.py | 16 ++++++++++ sbapp/sideband/voice.py | 6 ++++ sbapp/ui/voice.py | 66 ++++++++++++++++++++++++++++++++++------- 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 56f5249..e758455 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -853,6 +853,8 @@ class SidebandCore(): self.config["voice_input"] = None if not "voice_ringer" in self.config: self.config["voice_ringer"] = None + if not "voice_trusted_only" in self.config: + self.config["voice_trusted_only"] = False # Make sure we have a database if not os.path.isfile(self.db_path): @@ -1074,6 +1076,20 @@ class SidebandCore(): RNS.log("Error while checking trust for "+RNS.prettyhexrep(context_dest)+": "+str(e), RNS.LOG_ERROR) return False + def voice_is_trusted(self, identity_hash): + context_dest = identity_hash + try: + lxmf_destination_hash = RNS.Destination.hash_from_name_and_identity("lxmf.delivery", identity_hash) + existing_voice = self._db_conversation(context_dest) + existing_lxmf = self._db_conversation(lxmf_destination_hash) + if existing_lxmf: trust = existing_lxmf["trust"] + else: trust = existing_voice["trust"] + return trust == 1 + + except Exception as e: + RNS.log("Could not decode a valid peer name from data: "+str(e), RNS.LOG_DEBUG) + return False + def is_object(self, context_dest, conv_data = None): try: if conv_data == None: diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 9222c10..67a91ca 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -51,6 +51,7 @@ class ReticulumTelephone(): self.telephone.set_speaker(self.speaker_device) self.telephone.set_microphone(self.microphone_device) self.telephone.set_ringer(self.ringer_device) + self.telephone.set_allowed(self.__is_allowed) RNS.log(f"{self} initialised", RNS.LOG_DEBUG) def set_ringtone(self, ringtone_path): @@ -155,6 +156,11 @@ class ReticulumTelephone(): self.state = self.STATE_IN_CALL RNS.log(f"Call established with {RNS.prettyhexrep(self.caller.hash)}", RNS.LOG_DEBUG) + def __is_allowed(self, identity_hash): + if self.owner.config["voice_trusted_only"]: + return self.owner.voice_is_trusted(identity_hash) + else: return True + def __spin(self, until=None, msg=None, timeout=None): if msg: RNS.log(msg, RNS.LOG_DEBUG) if timeout != None: timeout = time.time()+timeout diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 68e13d0..60d19fd 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -200,6 +200,9 @@ class Voice(): if not self.app.sideband.config["voice_ringer"] in self.output_devices: self.output_devices.append(self.app.sideband.config["voice_ringer"]) def update_settings_screen(self, sender=None): + self.voice_settings_screen.ids.voice_trusted_only.active = self.app.sideband.config["voice_trusted_only"] + self.voice_settings_screen.ids.voice_trusted_only.bind(active=self.settings_save_action) + bp = 6; ml = 45; fs = 16; ics = 14 self.update_devices() @@ -257,6 +260,9 @@ class Voice(): self.voice_settings_screen.ids.ringer_devices.add_widget(device_button) self.listed_ringer_devices.append(device) + def settings_save_action(self, sender=None, event=None): + self.app.sideband.config["voice_trusted_only"] = self.voice_settings_screen.ids.voice_trusted_only.active + self.app.sideband.save_configuration() def output_device_action(self, sender=None): self.app.sideband.config["voice_output"] = sender.device @@ -377,7 +383,42 @@ MDScreen: orientation: "vertical" size_hint_y: None height: self.minimum_height - padding: [dp(28), dp(32), dp(28), dp(16)] + padding: [dp(28), dp(48), dp(28), dp(16)] + + MDLabel: + text: "Call Handling" + font_style: "H6" + height: self.texture_size[1] + padding: [dp(0), dp(0), dp(0), dp(12)] + + MDLabel: + id: voice_settings_info + markup: True + text: "You can block calls from all other callers than contacts marked as trusted, by enabling the following option." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + padding: [dp(0), dp(16), dp(0), dp(16)] + + MDBoxLayout: + orientation: "horizontal" + padding: [0,0,dp(24),0] + size_hint_y: None + height: dp(48) + + MDLabel: + text: "Block non-trusted callers" + font_style: "H6" + + MDSwitch: + id: voice_trusted_only + pos_hint: {"center_y": 0.3} + active: False + + MDLabel: + text: "Audio Devices" + font_style: "H6" + padding: [dp(0), dp(96), dp(0), dp(12)] MDLabel: id: voice_settings_info @@ -386,11 +427,12 @@ MDScreen: size_hint_y: None text_size: self.width, None height: self.texture_size[1] - padding: [dp(0), dp(0), dp(0), dp(48)] + padding: [dp(0), dp(64), dp(0), dp(32)] MDLabel: - text: "Output Device" - font_style: "H6" + text: "[b]Output[/b]" + font_size: dp(18) + markup: True MDBoxLayout: id: output_devices @@ -398,7 +440,7 @@ MDScreen: spacing: "12dp" size_hint_y: None height: self.minimum_height - padding: [dp(0), dp(35), dp(0), dp(48)] + padding: [dp(0), dp(24), dp(0), dp(48)] # MDRectangleFlatIconButton: # id: output_default_button @@ -411,8 +453,9 @@ MDScreen: # disabled: False MDLabel: - text: "Input Device" - font_style: "H6" + text: "[b]Input[/b]" + font_size: dp(18) + markup: True MDBoxLayout: id: input_devices @@ -420,11 +463,12 @@ MDScreen: spacing: "12dp" size_hint_y: None height: self.minimum_height - padding: [dp(0), dp(35), dp(0), dp(48)] + padding: [dp(0), dp(24), dp(0), dp(48)] MDLabel: - text: "Ringer Device" - font_style: "H6" + text: "[b]Ringer[/b]" + font_size: dp(18) + markup: True MDBoxLayout: id: ringer_devices @@ -432,6 +476,6 @@ MDScreen: spacing: "12dp" size_hint_y: None height: self.minimum_height - padding: [dp(0), dp(35), dp(0), dp(48)] + padding: [dp(0), dp(24), dp(0), dp(48)] """ \ No newline at end of file From 999054ab3476d20f847e22e52b62e1d606667558 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 17:13:02 +0100 Subject: [PATCH 064/271] Improved map init time --- sbapp/main.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index d9e3390..827ce5c 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -6155,7 +6155,7 @@ class SidebandApp(MDApp): latest_viewable = None if not skip: - for telemetry_entry in telemetry_entries[telemetry_source]: + for telemetry_entry in sorted(telemetry_entries[telemetry_source], key=lambda t: t[0], reverse=True): telemetry_timestamp = telemetry_entry[0] telemetry_data = telemetry_entry[1] t = Telemeter.from_packed(telemetry_data) @@ -6164,6 +6164,10 @@ class SidebandApp(MDApp): if "location" in telemetry and telemetry["location"] != None and telemetry["location"]["latitude"] != None and telemetry["location"]["longitude"] != None: latest_viewable = telemetry break + elif "connection_map" in telemetry: + # TODO: Telemetry entries with connection map sensor types are skipped for now, + # until a proper rendering mechanism is implemented + break if latest_viewable != None: l = latest_viewable["location"] From 1c855aa24ba44be761aa865bbe01b9618b844e4c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 17:20:49 +0100 Subject: [PATCH 065/271] Disable voice call option on Android --- sbapp/main.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sbapp/main.py b/sbapp/main.py index 827ce5c..37d1d3d 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3383,6 +3383,7 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_voice_enabled.active = self.sideband.config["voice_enabled"] self.settings_screen.ids.settings_voice_enabled.bind(active=save_voice_enabled) + if RNS.vendor.platformutils.is_android(): self.settings_screen.ids.settings_voice_enabled.disabled = True self.settings_screen.ids.settings_debug.active = self.sideband.config["debug"] self.settings_screen.ids.settings_debug.bind(active=save_debug) From 7b2745692df4f8276e9b381794bb1c68857227b7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 18:41:22 +0100 Subject: [PATCH 066/271] Updated build spec --- sideband.spec | 1 + 1 file changed, 1 insertion(+) diff --git a/sideband.spec b/sideband.spec index 67f1d3f..260aa4d 100644 --- a/sideband.spec +++ b/sideband.spec @@ -36,6 +36,7 @@ def extra_datas(mydir): a.datas += extra_datas('sbapp') a.datas += extra_datas('RNS') a.datas += extra_datas('LXMF') +a.datas += extra_datas('LXST') exe = EXE( pyz, From fdb4003a175d910911a2984f5eb11988ccb0f2e6 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:21:25 +0100 Subject: [PATCH 067/271] Updated readme --- README.md | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 557b655..9d05edc 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Sideband ========= -Sideband is an extensible LXMF messaging client, situational awareness tracker and remote control and monitoring system for Android, Linux, macOS and Windows. It allows you to communicate with other people or LXMF-compatible systems over Reticulum networks using LoRa, Packet Radio, WiFi, I2P, Encrypted QR Paper Messages, or anything else Reticulum supports. +Sideband is an extensible LXMF messaging and LXST telephony client, situational awareness tracker and remote control and monitoring system for Android, Linux, macOS and Windows. It allows you to communicate with other people or LXMF-compatible systems over Reticulum networks using LoRa, Packet Radio, WiFi, I2P, Encrypted QR Paper Messages, or anything else Reticulum supports. ![Screenshot](https://github.com/markqvist/Sideband/raw/main/docs/screenshots/devices_small.webp) @@ -13,10 +13,11 @@ This also means that Sideband operates differently than what you might be used t Sideband provides many useful and interesting functions, such as: -- **Secure** and **self-sovereign** messaging using the LXMF protocol over Reticulum. +- **Secure** and **self-sovereign** messaging and voice calls using the LXMF and LXST protocols over Reticulum. - **Image** and **file transfers** over all supported mediums. - **Audio messages** that work even over **LoRa** and **radio links**, thanks to [Codec2](https://github.com/drowe67/codec2/) and [Opus](https://github.com/xiph/opus) encoding. - Secure and direct P2P **telemetry and location sharing**. No third parties or servers ever have your data. +- The telemetry system is **completely extensible** via [simple plugins](https://github.com/markqvist/Sideband/tree/main/docs/example_plugins). - Situation display on both online and **locally stored offline maps**. - Geospatial awareness calculations. - Exchanging messages through **encrypted QR-codes on paper**, or through messages embedded directly in **lxm://** links. @@ -39,7 +40,7 @@ Sideband can run on most computing devices, but installation methods vary by dev ## On Android -For your Android devices, you can install Sideband through F-Droid, by adding the [Between the Borders Repo](https://reticulum.betweentheborders.com/fdroid/repo/), or you can download an [APK on the latest release page](https://github.com/markqvist/Sideband/releases/latest). Both sources are signed with the same release keys, and can be used interchangably. +For your Android devices, you can download an [APK on the latest release page](https://github.com/markqvist/Sideband/releases/latest). After the application is installed on your Android device, it is also possible to pull updates directly through the **Repository** section of the application. @@ -47,9 +48,8 @@ After the application is installed on your Android device, it is also possible t On all Linux-based operating systems, Sideband is available as a `pipx`/`pip` package. This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. -**Please note!** The very latest Python release, Python 3.13 is currently **not** compatible with the Kivy framework, that Sideband uses to render its user interface. If your Linux distribution uses Python 3.13 as its default Python installation, you will need to install an earlier version as well. Using [the latest release of Python 3.12](https://www.python.org/downloads/release/python-3127/) is recommended. - -You will first need to install a few dependencies for audio messaging and Codec2 support to work: +#### Basic Installation +You will first need to install a few dependencies for voice calls, audio messaging and Codec2 support to work: ```bash # For Debian (12+), Ubuntu (22.04+) and derivatives @@ -68,10 +68,6 @@ Once those are installed, install the Sideband application itself: ```bash # Finally, install Sideband using pipx: pipx install sbapp - -# If you need to specify a specific Python version, -# use something like the following: -pipx install sbapp --python python3.12 ``` After installation, you can now run Sideband in a number of different ways: @@ -101,6 +97,9 @@ sideband --daemon sideband -v ``` +If you do not already have Reticulum connectivity set up on your computer or local network, you will probably want to edit the Reticulum configuration file at `~/.reticulum/config` and [add any interfaces](https://reticulum.network/manual/interfaces.html) you need for connectivity. + +#### Advanced Installation You can also install Sideband in various alternative ways: ```bash @@ -135,17 +134,17 @@ You can install Sideband on all Raspberry Pi models that support 64-bit operatin Aditionally, the `pycodec2` package needs to be installed manually. I have provided a pre-built version, that you can download and install with a single command, or if you don't want to trust my pre-built version, you can [build and install it from source yourself](https://github.com/gregorias/pycodec2/blob/main/DEV.md). -The install instructions below assume that you are installing Sideband on 64-bit Raspberry Pi OS (based on Debian Bookworm). If you're running something else on your Pi, you might need to modify some commands slightly. To install Sideband on Raspberry Pi, follow these steps: +The install instructions below assume that you are installing Sideband on 64-bit Raspberry Pi OS (based on Debian Bookworm or later). If you're running something else on your Pi, you might need to modify some commands slightly. To install Sideband on Raspberry Pi with full support for voice calls, audio messages and Codec2, follow these steps: ```bash # First of all, install the required dependencies: sudo apt install python3-pip python3-pyaudio python3-dev python3-cryptography build-essential libopusfile0 libsdl2-dev libavcodec-dev libavdevice-dev libavfilter-dev portaudio19-dev codec2 libcodec2-1.0 xclip xsel # If you don't want to compile pycodec2 yourself, -# download the pre-compiled package provided here +# download the pre-compiled package provided here: wget https://raw.githubusercontent.com/markqvist/Sideband/main/docs/utilities/pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl -# Install it: +# And install it: pip install ./pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl --break-system-packages # You can now install Sideband @@ -159,6 +158,8 @@ sudo reboot sideband ``` +If you do not already have Reticulum connectivity set up on your computer or local network, you will probably want to edit the Reticulum configuration file at `~/.reticulum/config` and [add any interfaces](https://reticulum.network/manual/interfaces.html) you need for connectivity. + ## On macOS To install Sideband on macOS, you have two options available: @@ -185,6 +186,8 @@ pip3 install rns --break-system-packages If you do not have Python and `pip` available, [download and install it](https://www.python.org/downloads/) first. +If you do not already have Reticulum connectivity set up on your computer or local network, you will probably want to edit the Reticulum configuration file at `~/.reticulum/config` and [add any interfaces](https://reticulum.network/manual/interfaces.html) you need for connectivity. + #### Source Package Install For more advanced setups, including the ability to run Sideband in headless daemon mode, enable debug logging output, configuration import and export and more, you may want to install it from the source package via `pip` instead. @@ -238,6 +241,8 @@ Simply download the packaged Windows ZIP file from the [latest release page](htt When running Sideband for the first time, a default Reticulum configuration file will be created, if you don't already have one. If you don't have any existing Reticulum connectivity available locally, you may want to edit the file, located at `C:\Users\USERNAME\.reticulum\config` and manually add an interface that provides connectivity to a wider network. If you just want to connect over the Internet, you can add one of the public hubs on the [Reticulum Testnet](https://reticulum.network/connect.html). +#### Installing Reticulum Utilities + Though the ZIP file contains everything necessary to run Sideband, it is also recommended to install the Reticulum command line utilities separately, so that you can use commands like `rnstatus` and `rnsd` from the command line. This will make it easier to manage Reticulum connectivity on your system. If you do not already have Python installed on your system, [download and install it](https://www.python.org/downloads/) first. **Important!** When asked by the installer, make sure to add the Python program to your `PATH` environment variables. If you don't do this, you will not be able to use the `pip` installer, or run any of the installed commands. When Python has been installed, you can open a command prompt and install the Reticulum package via `pip`: @@ -262,6 +267,16 @@ The Sideband application can now be launched by running the command `sideband` i Since this installation method automatically installs the `rns` and `lxmf` packages as well, you will also have access to using all the included RNS and LXMF utilities like `rnstatus`, `rnsd` and `lxmd` on your system. +# Creating Plugins + +Sideband features a flexible and extensible plugin system, that allows you to hook all kinds of control, status reporting, command execution and telemetry collection into the LXMF messaging system. Plugins can be created as either *Telemetry*, *Command* or *Service* plugins, for different use-cases. + +To create plugins for Sideband, you can find a variety of [code examples](https://github.com/markqvist/Sideband/tree/main/docs/example_plugins), that you can use as a basis for writing your own plugins. Sideband includes 20+ built-in sensor types to chose from, for representing all kinds telemetry data. If none of those fit your needs, there is a `Custom` sensor type, that can include any kind of data. + +Command plugins allow you to define any kind of action or command to be run when receiving command messages from other LXMF clients. In the example directory, you will find various command plugin templates, for example for viewing security cameras or webcams through Sideband. + +Service plugins allow you to integrate any kind of service, bridge or other system into Sideband, and have that react to events or state changes in Sideband itself. + # Paper Messaging Example You can try out the paper messaging functionality by using the following QR-code. It is a paper message sent to the LXMF address `6b3362bd2c1dbf87b66a85f79a8d8c75`. To be able to decrypt and read the message, you will need to import the following base32-encoded Reticulum Identity into the app: From 45f5d3e9adb498105d60bdce9fe18136fa33c8fc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:21:37 +0100 Subject: [PATCH 068/271] Added windows location plugin example --- docs/example_plugins/windows_location.py | 88 ++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 docs/example_plugins/windows_location.py diff --git a/docs/example_plugins/windows_location.py b/docs/example_plugins/windows_location.py new file mode 100644 index 0000000..ff0aded --- /dev/null +++ b/docs/example_plugins/windows_location.py @@ -0,0 +1,88 @@ +# Windows Location Provider plugin example, provided by @haplo-dev + +import RNS +import time +import threading +import asyncio +from winsdk.windows.devices import geolocation + +class WindowsLocationPlugin(SidebandTelemetryPlugin): + plugin_name = "windows_location" + + def __init__(self, sideband_core): + self.update_interval = 5.0 + self.should_run = False + + self.latitude = None + self.longitude = None + self.altitude = None + self.speed = None + self.bearing = None + self.accuracy = None + self.last_update = None + + super().__init__(sideband_core) + + def start(self): + RNS.log("Starting Windows Location provider plugin...") + + self.should_run = True + update_thread = threading.Thread(target=self.update_job, daemon=True) + update_thread.start() + + super().start() + + def stop(self): + self.should_run = False + super().stop() + + def update_job(self): + while self.should_run: + RNS.log("Updating location from Windows Geolocation...", RNS.LOG_DEBUG) + try: + asyncio.run(self.get_location()) + except Exception as e: + RNS.log(f"Error getting location: {str(e)}", RNS.LOG_ERROR) + + time.sleep(self.update_interval) + + async def get_location(self): + geolocator = geolocation.Geolocator() + position = await geolocator.get_geoposition_async() + + self.last_update = time.time() + self.latitude = position.coordinate.latitude + self.longitude = position.coordinate.longitude + self.altitude = position.coordinate.altitude + self.accuracy = position.coordinate.accuracy + + # Note: Windows Geolocation doesn't provide speed and bearing directly + # You might need to calculate these from successive position updates + self.speed = None + self.bearing = None + + def has_location(self): + return all([self.latitude, self.longitude, self.altitude, self.accuracy]) is not None + + def update_telemetry(self, telemeter): + if self.is_running() and telemeter is not None: + if self.has_location(): + RNS.log("Updating location from Windows Geolocation", RNS.LOG_DEBUG) + if "location" not in telemeter.sensors: + telemeter.synthesize("location") + + telemeter.sensors["location"].latitude = self.latitude + telemeter.sensors["location"].longitude = self.longitude + telemeter.sensors["location"].altitude = self.altitude + telemeter.sensors["location"].speed = self.speed + telemeter.sensors["location"].bearing = self.bearing + telemeter.sensors["location"].accuracy = self.accuracy + telemeter.sensors["location"].stale_time = 5 + telemeter.sensors["location"].set_update_time(self.last_update) + + else: + RNS.log("No location from Windows Geolocation yet", RNS.LOG_DEBUG) + +# Finally, tell Sideband what class in this +# file is the actual plugin class. +plugin_class = WindowsLocationPlugin \ No newline at end of file From ff8b1d4c28e414c48b937f561f88b9533e0bf750 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:23:16 +0100 Subject: [PATCH 069/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d05edc..e1dd455 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Sideband provides many useful and interesting functions, such as: - **Image** and **file transfers** over all supported mediums. - **Audio messages** that work even over **LoRa** and **radio links**, thanks to [Codec2](https://github.com/drowe67/codec2/) and [Opus](https://github.com/xiph/opus) encoding. - Secure and direct P2P **telemetry and location sharing**. No third parties or servers ever have your data. -- The telemetry system is **completely extensible** via [simple plugins](https://github.com/markqvist/Sideband/tree/main/docs/example_plugins). +- The telemetry system is **completely extensible** via [simple plugins](#creating-plugins). - Situation display on both online and **locally stored offline maps**. - Geospatial awareness calculations. - Exchanging messages through **encrypted QR-codes on paper**, or through messages embedded directly in **lxm://** links. From 41536eb25a4386eae22f96fca3f4fd4cd01d0613 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:30:21 +0100 Subject: [PATCH 070/271] Updated readme --- README.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e1dd455..520f87f 100644 --- a/README.md +++ b/README.md @@ -271,7 +271,19 @@ Since this installation method automatically installs the `rns` and `lxmf` packa Sideband features a flexible and extensible plugin system, that allows you to hook all kinds of control, status reporting, command execution and telemetry collection into the LXMF messaging system. Plugins can be created as either *Telemetry*, *Command* or *Service* plugins, for different use-cases. -To create plugins for Sideband, you can find a variety of [code examples](https://github.com/markqvist/Sideband/tree/main/docs/example_plugins), that you can use as a basis for writing your own plugins. Sideband includes 20+ built-in sensor types to chose from, for representing all kinds telemetry data. If none of those fit your needs, there is a `Custom` sensor type, that can include any kind of data. +To create plugins for Sideband, you can find a variety of [code examples](https://github.com/markqvist/Sideband/tree/main/docs/example_plugins) in this repository, that you can use as a basis for writing your own plugins. The example plugins include: + +- [Custom telemetry](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/telemetry.py) +- [Getting BME280 temperature, humidity and pressure](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/bme280_telemetry.py) +- [Basic commands](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/basic.py) +- [Location telemetry from GPSd on Linux](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/gpsd_location.py) +- [Location telemetry from Windows Location Provider](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/windows_location.py) +- [Getting statistics from your LXMF propagation node](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/lxmd_telemetry.py) +- [Viewing cameras and streams](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/view.py) +- [Fetching an XKCD comic](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/comic.py) +- [Creating a service plugin](https://github.com/markqvist/Sideband/blob/main/docs/example_plugins/service.py) + +For creating telemetry plugins, Sideband includes 20+ built-in sensor types to chose from, for representing all kinds telemetry data. If none of those fit your needs, there is a `Custom` sensor type, that can include any kind of data. Command plugins allow you to define any kind of action or command to be run when receiving command messages from other LXMF clients. In the example directory, you will find various command plugin templates, for example for viewing security cameras or webcams through Sideband. From e4bb1e17eb6280dd8b2db85a8d0981f515bb0988 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:31:59 +0100 Subject: [PATCH 071/271] Updated readme --- README.md | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/README.md b/README.md index 520f87f..b46828a 100644 --- a/README.md +++ b/README.md @@ -324,26 +324,6 @@ You can help support the continued development of open, free and private communi
-# Planned Features - -- Secure and private location and telemetry sharing -- Including images in messages -- Sending file attachments -- Offline and online maps -- Paper messages -- Using Sideband as a Reticulum Transport Instance -- Encryption keys export and import -- Plugin support for commands, services and telemetry -- Sending voice messages (using Codec2 and Opus) -- 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 - # License Unless otherwise noted, this work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License][cc-by-nc-sa]. From f6d23257850d246e3a60edd19f401ecbc61cb9ee Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:51:13 +0100 Subject: [PATCH 072/271] Updated readme --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b46828a..2f07d59 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,10 @@ After installation, you can now run Sideband in a number of different ways: pipx ensurepath # The first time you run Sideband, you will need to do it -# from the terminal: +# from the terminal, for the application launcher item to +# show up. On some distros you may also need to log out +# and back in again, or simply reboot the machine for the +# application entry to show up in your menu. sideband # At the first launch, it will add an application icon From b2c3411c90225dd8eb31db37c2ede440363827df Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 14 Mar 2025 21:51:24 +0100 Subject: [PATCH 073/271] Fixed missing property init --- sbapp/sideband/core.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index e758455..2491e02 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -169,6 +169,7 @@ class SidebandCore(): self.reticulum = None self.webshare_server = None self.voice_running = False + self.telephone = None self.telemeter = None self.telemetry_running = False self.latest_telemetry = None From a0a6b0fd552d807cd17a8817c02ff0810d805a69 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Mar 2025 22:16:54 +0100 Subject: [PATCH 074/271] Handle MQTT client memory leak --- sbapp/sideband/core.py | 38 +++++++++++++++++++++++++++++++++----- sbapp/sideband/mqtt.py | 3 +++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 2491e02..161854e 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -8,6 +8,7 @@ import sqlite3 import random import shlex import re +import gc import RNS.vendor.umsgpack as msgpack import RNS.Interfaces.Interface as Interface @@ -268,6 +269,7 @@ class SidebandCore(): self.webshare_ssl_cert_path = self.app_dir+"/app_storage/ssl_cert.pem" self.mqtt = None + self.mqtt_handle_lock = threading.Lock() self.first_run = True self.saving_configuration = False @@ -2141,6 +2143,7 @@ class SidebandCore(): dbc = db.cursor() dbc.execute("CREATE TABLE IF NOT EXISTS telemetry (id INTEGER PRIMARY KEY, dest_context BLOB, ts INTEGER, data BLOB)") + dbc.execute("CREATE INDEX IF NOT EXISTS idx_telemetry_ts ON telemetry(ts)") db.commit() def _db_upgradetables(self): @@ -3269,12 +3272,37 @@ class SidebandCore(): self.setstate("app.flags.last_telemetry", time.time()) def mqtt_handle_telemetry(self, context_dest, telemetry): - if self.mqtt == None: - self.mqtt = MQTT() + with self.mqtt_handle_lock: + # TODO: Remove debug + if hasattr(self, "last_mqtt_recycle") and time.time() > self.last_mqtt_recycle + 60*4: + # RNS.log("Recycling MQTT handler", RNS.LOG_DEBUG) + self.mqtt.stop() + self.mqtt.client = None + self.mqtt = None + gc.collect() - 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) + if self.mqtt == None: + self.mqtt = MQTT() + self.last_mqtt_recycle = time.time() + + 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) + + # TODO: Remove debug + # if not hasattr(self, "memtr"): + # from pympler import muppy + # from pympler import summary + # import resource + # self.res = resource + # self.ms = summary; self.mp = muppy + # self.memtr = self.ms.summarize(self.mp.get_objects()) + # RNS.log(f"RSS: {RNS.prettysize(self.res.getrusage(self.res.RUSAGE_SELF).ru_maxrss*1000)}") + # else: + # memsum = self.ms.summarize(self.mp.get_objects()) + # memdiff = self.ms.get_diff(self.memtr, memsum) + # self.ms.print_(memdiff) + # RNS.log(f"RSS: {RNS.prettysize(self.res.getrusage(self.res.RUSAGE_SELF).ru_maxrss*1000)}") def update_telemetry(self): try: diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index bed0e6d..df55388 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -49,6 +49,9 @@ class MQTT(): time.sleep(MQTT.SCHEDULER_SLEEP) + try: self.disconnect() + except Exception as e: RNS.log(f"An error occurred while disconnecting MQTT server: {e}", RNS.LOG_ERROR) + RNS.log("Stopped MQTT scheduler", RNS.LOG_DEBUG) def connect_failed(self, client, userdata): From 1054ddf1c414b5bdbab288b2a2bc885f9e6e0b9e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Mar 2025 22:20:51 +0100 Subject: [PATCH 075/271] Updated build spec --- sbapp/buildozer.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index b6b8594..f970683 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 = 20250220 +android.numeric_version = 20250327 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 From 6a56d02afb54f76a43228f02eb33f067b5423003 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 5 Apr 2025 14:39:21 +0200 Subject: [PATCH 076/271] Fixed potential change during iteration --- sbapp/sideband/sense.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index 34c2e14..0a22767 100644 --- a/sbapp/sideband/sense.py +++ b/sbapp/sideband/sense.py @@ -120,9 +120,11 @@ class Telemeter(): def stop_all(self): if not self.from_packed: - for sensor in self.sensors: + sensors = self.sensors.copy() + for sensor in sensors: if not sensor == "time": self.sensors[sensor].stop() + del sensors def read(self, sensor): if not self.from_packed: @@ -137,31 +139,38 @@ class Telemeter(): def read_all(self): readings = {} - for sensor in self.sensors: + sensors = self.sensors.copy() + for sensor in sensors: if self.sensors[sensor].active: if not self.from_packed: readings[sensor] = self.sensors[sensor].data else: readings[sensor] = self.sensors[sensor]._data + del sensors return readings def packed(self): packed = {} packed[Sensor.SID_TIME] = int(time.time()) - for sensor in self.sensors: + sensors = self.sensors.copy() + for sensor in sensors: if self.sensors[sensor].active: packed[self.sensors[sensor].sid] = self.sensors[sensor].pack() + + del sensors return umsgpack.packb(packed) def render(self, relative_to=None): rendered = [] - for sensor in self.sensors: + sensors = self.sensors.copy() + for sensor in sensors: s = self.sensors[sensor] if s.active: r = s.render(relative_to) if r: rendered.append(r) + del sensors return rendered def check_permission(self, permission): From e8461b3f33a1bc3eac63d0a1541db034bbf8a74e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 7 Apr 2025 18:21:35 +0200 Subject: [PATCH 077/271] Cleanup --- 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 df55388..b035f8a 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -44,7 +44,7 @@ class MQTT(): 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) + RNS.log(f"An error occurred while running MQTT scheduler jobs: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) time.sleep(MQTT.SCHEDULER_SLEEP) From a97c6dc9bb3f0c82bc9aea2227e43cd7ae214449 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 8 Apr 2025 18:19:10 +0200 Subject: [PATCH 078/271] Updated versions --- sbapp/main.py | 2 +- setup.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 37d1d3d..f6e92a9 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.5.0" +__version__ = "1.5.1" __variant__ = "" import sys diff --git a/setup.py b/setup.py index 604c0c1..8abfe15 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.3", - "lxmf>=0.6.2", + "rns>=0.9.4", + "lxmf>=0.6.3", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 9749147b346d564b56e55e5a8f25db17b3645e03 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 9 Apr 2025 17:16:30 +0200 Subject: [PATCH 079/271] Use abstract domain sockets for RPC. Use epoll backend for TCP connections on Android. --- sbapp/sideband/core.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 161854e..8533a70 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -575,7 +575,7 @@ class SidebandCore(): RNS.log("Loading Sideband identity...", RNS.LOG_DEBUG) self.identity = RNS.Identity.from_file(self.identity_path) - self.rpc_addr = ("127.0.0.1", 48165) + self.rpc_addr = f"\0sideband/rpc" self.rpc_key = RNS.Identity.full_hash(self.identity.get_private_key()) RNS.log("Loading Sideband configuration... "+str(self.config_path), RNS.LOG_DEBUG) @@ -1790,7 +1790,7 @@ class SidebandCore(): try: with self.rpc_lock: if self.rpc_connection == None: - self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, authkey=self.rpc_key) + self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, family="AF_UNIX", authkey=self.rpc_key) self.rpc_connection.send(request) response = self.rpc_connection.recv() return response @@ -1962,12 +1962,12 @@ class SidebandCore(): def __start_rpc_listener(self): try: RNS.log("Starting RPC listener", RNS.LOG_DEBUG) - self.rpc_listener = multiprocessing.connection.Listener(self.rpc_addr, authkey=self.rpc_key) + self.rpc_listener = multiprocessing.connection.Listener(self.rpc_addr, family="AF_UNIX", authkey=self.rpc_key) thread = threading.Thread(target=self.__rpc_loop) thread.daemon = True thread.start() except Exception as e: - RNS.log("Could not start RPC listener on "+str(self.rpc_addr)+". Terminating now. Clear up anything using the port and try again.", RNS.LOG_ERROR) + RNS.log("Could not start RPC listener on @"+str(self.rpc_addr[1:])+". Terminating now. Clear up anything using the port and try again.", RNS.LOG_ERROR) RNS.panic() def __rpc_loop(self): @@ -4115,13 +4115,13 @@ class SidebandCore(): ifac_size = None interface_config = { - "name": "TCPClientInterface", + "name": "TCP Client", "target_host": tcp_host, "target_port": tcp_port, "kiss_framing": False, "i2p_tunneled": False, } - tcpinterface = RNS.Interfaces.TCPInterface.TCPClientInterface(RNS.Transport, interface_config) + tcpinterface = RNS.Interfaces.BackboneInterface.BackboneClientInterface(RNS.Transport, interface_config) tcpinterface.OUT = True if RNS.Reticulum.transport_enabled(): From b86725c96d1f827cf5bb124a5cecb33aa55a51e6 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 17 Apr 2025 14:09:32 +0200 Subject: [PATCH 080/271] Added console argument --- sbapp/main.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index f6e92a9..fd29f19 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -9,6 +9,7 @@ parser = argparse.ArgumentParser(description="Sideband LXMF Client") parser.add_argument("-v", "--verbose", action='store_true', default=False, help="increase logging verbosity") parser.add_argument("-c", "--config", action='store', default=None, help="specify path of config directory") parser.add_argument("-d", "--daemon", action='store_true', default=False, help="run as a daemon, without user interface") +parser.add_argument("-i", "--interactive", action='store_true', default=False, help="connect interactive console after daemon init") parser.add_argument("--export-settings", action='store', default=None, help="export application settings to file") parser.add_argument("--import-settings", action='store', default=None, help="import application settings from file") parser.add_argument("--version", action="version", version="sideband {version}".format(version=__version__)) @@ -1701,14 +1702,12 @@ class SidebandApp(MDApp): if self.outbound_mode_command: return - def cb(dt): - self.message_send_dispatch(sender) + def cb(dt): self.message_send_dispatch(sender) Clock.schedule_once(cb, 0.20) def message_send_dispatch(self, sender=None): self.messages_view.ids.message_send_button.disabled = True - def cb(dt): - self.messages_view.ids.message_send_button.disabled = False + def cb(dt): self.messages_view.ids.message_send_button.disabled = False Clock.schedule_once(cb, 0.5) if self.root.ids.screen_manager.current == "messages_screen": @@ -6448,8 +6447,14 @@ def run(): sideband.version_str = "v"+__version__+" "+__variant__ sideband.start() - while True: - time.sleep(5) + + if args.interactive: + global sbcore; sbcore = sideband + while not sbcore.getstate("core.started") == True: time.sleep(0.1) + time.sleep(1) + import code; code.interact(local=globals()) + else: + while True: time.sleep(5) else: ExceptionManager.add_handler(SidebandExceptionHandler()) SidebandApp().run() From 9e636de5b17a8d48ccb9f7caff7ba9c0bee2ca44 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 17 Apr 2025 20:35:30 +0200 Subject: [PATCH 081/271] Added basic console functionality --- sbapp/main.py | 11 ++-- sbapp/sideband/console.py | 103 ++++++++++++++++++++++++++++++++++++++ sbapp/sideband/core.py | 16 +++--- 3 files changed, 118 insertions(+), 12 deletions(-) create mode 100644 sbapp/sideband/console.py diff --git a/sbapp/main.py b/sbapp/main.py index fd29f19..2515b42 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2857,7 +2857,7 @@ 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] (Reticulum License)\n - [b]LXMF[/b] (Reticulum 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)" str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Paho MQTT[/b] (EPL2 License)\n - [b]Python[/b] (PSF License)" @@ -6442,6 +6442,7 @@ def run(): config_path=args.config, is_client=False, verbose=(args.verbose or __debug_build__), + quiet=(args.interactive and not args.verbose), is_daemon=True ) @@ -6449,10 +6450,10 @@ def run(): sideband.start() if args.interactive: - global sbcore; sbcore = sideband - while not sbcore.getstate("core.started") == True: time.sleep(0.1) - time.sleep(1) - import code; code.interact(local=globals()) + while not sideband.getstate("core.started") == True: time.sleep(0.1) + from .sideband import console + console.attach(sideband) + else: while True: time.sleep(5) else: diff --git a/sbapp/sideband/console.py b/sbapp/sideband/console.py new file mode 100644 index 0000000..d6b9ec9 --- /dev/null +++ b/sbapp/sideband/console.py @@ -0,0 +1,103 @@ +import os +import RNS +import threading +from prompt_toolkit.application import Application +from prompt_toolkit.document import Document +from prompt_toolkit.key_binding import KeyBindings +from prompt_toolkit.layout.containers import HSplit, Window +from prompt_toolkit.layout.layout import Layout +from prompt_toolkit.styles import Style +from prompt_toolkit.widgets import SearchToolbar, TextArea + +sideband = None +application = None +output_document = Document(text="", cursor_position=0) +output_field = None + +def attach(target_core): + global sideband + sideband = target_core + RNS.logdest = RNS.LOG_CALLBACK + RNS.logcall = receive_output + console() + +def parse(uin): + args = uin.split(" ") + cmd = args[0] + if cmd == "q" or cmd == "quit": quit_action() + elif cmd == "clear": cmd_clear(args) + elif cmd == "raw": cmd_raw(args, uin.replace("raw ", "")) + elif cmd == "log": cmd_log(args) + else: receive_output(f"Unknown command: {cmd}") + +def cmd_clear(args): + output_document = output_document = Document(text="", cursor_position=0) + output_field.buffer.document = output_document + +def cmd_raw(args, expr): + if expr != "" and expr != "raw": + try: receive_output(eval(expr)) + except Exception as e: receive_output(str(e)) + +def cmd_log(args): + try: + if len(args) == 1: receive_output(f"Current loglevel is {RNS.loglevel}") + else: RNS.loglevel = int(args[1]); receive_output(f"Loglevel set to {RNS.loglevel}") + except Exception as e: + receive_output("Invalid loglevel: {e}") + +def set_log(level=None): + if level: RNS.loglevel = level + if RNS.loglevel == 0: receive_output("Logging squelched. Use log command to print output to console.") + +def quit_action(): + receive_output("Shutting down Sideband...") + sideband.should_persist_data() + application.exit() + +def receive_output(msg): + global output_document, output_field + content = f"{output_field.text}\n{msg}" + output_document = output_document = Document(text=content, cursor_position=len(content)) + output_field.buffer.document = output_document + +def console(): + global output_document, output_field, application + search_field = SearchToolbar() + + output_field = TextArea(style="class:output-field", text="Sideband console ready") + input_field = TextArea( + height=1, + prompt="> ", + style="class:input-field", + multiline=False, + wrap_lines=False, + search_field=search_field) + + container = HSplit([ + output_field, + Window(height=1, char="-", style="class:line"), + input_field, + search_field]) + + def accept(buff): parse(input_field.text) + input_field.accept_handler = accept + + kb = KeyBindings() + @kb.add("c-c") + @kb.add("c-q") + def _(event): quit_action() + + style = Style([ + ("line", "#004444"), + ]) + + application = Application( + layout=Layout(container, focused_element=input_field), + key_bindings=kb, + style=style, + mouse_support=True, + full_screen=False) + + set_log() + application.run() \ No newline at end of file diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 8533a70..be15a90 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -148,7 +148,7 @@ class SidebandCore(): 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): + def __init__(self, owner_app, config_path = None, is_service=False, is_client=False, android_app_dir=None, verbose=False, quiet=False, owner_service=None, service_context=None, is_daemon=False, load_config_only=False): self.is_service = is_service self.is_client = is_client self.is_daemon = is_daemon @@ -164,7 +164,8 @@ class SidebandCore(): else: self.is_standalone = False - self.log_verbose = verbose + self.log_verbose = (verbose and not quiet) + self.log_quiet = quiet self.log_deque = deque(maxlen=self.LOG_DEQUE_MAXLEN) self.owner_app = owner_app self.reticulum = None @@ -4023,10 +4024,9 @@ class SidebandCore(): def _reticulum_log_debug(self, debug=False): self.log_verbose = debug - if self.log_verbose: - selected_level = 6 - else: - selected_level = 2 + if self.log_quiet: selected_level = 0 + elif self.log_verbose: selected_level = 6 + else: selected_level = 2 RNS.loglevel = selected_level if self.is_client: @@ -4041,7 +4041,9 @@ class SidebandCore(): return "\n".join(self.log_deque) def __start_jobs_immediate(self): - if self.log_verbose: + if self.log_quiet: + selected_level = 0 + elif self.log_verbose: selected_level = 6 else: selected_level = 2 From a60c0d830e7eadab7097dd577da15390f1819d28 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 29 Apr 2025 11:44:36 +0200 Subject: [PATCH 082/271] Updated readme and gitignore --- .gitignore | 1 + README.md | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 7750d9e..efbd926 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ dist docs/build sideband*.egg-info sbapp*.egg-info +LXST diff --git a/README.md b/README.md index 2f07d59..cfb7fec 100644 --- a/README.md +++ b/README.md @@ -315,16 +315,17 @@ You can help support the continued development of open, free and private communi ``` 84FpY1QbxHcgdseePYNmhTHcrgMX4nFfBYtz2GKYToqHVVhJp8Eaw1Z1EedRnKD19b3B8NiLCGVxzKV17UMmmeEsCrPyA5w ``` -- Ethereum - ``` - 0xFDabC71AC4c0C78C95aDDDe3B4FA19d6273c5E73 - ``` - Bitcoin ``` - 35G9uWVzrpJJibzUwpNUQGQNFzLirhrYAH + bc1p4a6axuvl7n9hpapfj8sv5reqj8kz6uxa67d5en70vzrttj0fmcusgxsfk5 + ``` +- Ethereum + ``` + 0xae89F3B94fC4AD6563F0864a55F9a697a90261ff ``` - Ko-Fi: https://ko-fi.com/markqvist +
# License From 922dd91d7f51a9a8cb41e06f5c228d1b5cb621a5 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 6 May 2025 19:11:39 +0200 Subject: [PATCH 083/271] Added option to specify RNS config path --- sbapp/main.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 2515b42..d1325b2 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -8,6 +8,7 @@ import argparse parser = argparse.ArgumentParser(description="Sideband LXMF Client") parser.add_argument("-v", "--verbose", action='store_true', default=False, help="increase logging verbosity") parser.add_argument("-c", "--config", action='store', default=None, help="specify path of config directory") +parser.add_argument("-r", "--rnsconfig", action='store', default=None, help="specify path of RNS config directory") parser.add_argument("-d", "--daemon", action='store_true', default=False, help="run as a daemon, without user interface") parser.add_argument("-i", "--interactive", action='store_true', default=False, help="connect interactive console after daemon init") parser.add_argument("--export-settings", action='store', default=None, help="export application settings to file") @@ -346,7 +347,7 @@ class SidebandApp(MDApp): if RNS.vendor.platformutils.get_platform() == "android": self.sideband = SidebandCore(self, config_path=self.config_path, is_client=True, android_app_dir=self.app_dir, verbose=__debug_build__) else: - self.sideband = SidebandCore(self, config_path=self.config_path, is_client=False, verbose=(args.verbose or __debug_build__)) + self.sideband = SidebandCore(self, config_path=self.config_path, is_client=False, verbose=(args.verbose or __debug_build__),rns_config_path=args.rnsconfig) self.sideband.version_str = "v"+__version__+" "+__variant__ @@ -6443,7 +6444,8 @@ def run(): is_client=False, verbose=(args.verbose or __debug_build__), quiet=(args.interactive and not args.verbose), - is_daemon=True + is_daemon=True, + rns_config_path=args.rnsconfig, ) sideband.version_str = "v"+__version__+" "+__variant__ From 0e552d4b9d4ab9ed107fef8a2e4bd5a82886a378 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 6 May 2025 19:11:54 +0200 Subject: [PATCH 084/271] Added link mode to object details screen --- sbapp/sideband/core.py | 36 ++++++++++++++++++++++++++++++++++-- sbapp/ui/objectdetails.py | 7 +++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index be15a90..7a17b8a 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -148,7 +148,7 @@ class SidebandCore(): 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, quiet=False, owner_service=None, service_context=None, is_daemon=False, load_config_only=False): + def __init__(self, owner_app, config_path = None, is_service=False, is_client=False, android_app_dir=None, verbose=False, quiet=False, owner_service=None, service_context=None, is_daemon=False, load_config_only=False, rns_config_path=None): self.is_service = is_service self.is_client = is_client self.is_daemon = is_daemon @@ -209,7 +209,7 @@ class SidebandCore(): self.cache_dir = self.app_dir+"/cache" - self.rns_configdir = None + self.rns_configdir = rns_config_path core_path = os.path.abspath(__file__) if "core.pyc" in core_path: @@ -1960,6 +1960,38 @@ class SidebandCore(): RNS.log(ed, RNS.LOG_DEBUG) return None + def _get_destination_lmd(self, destination_hash): + try: + mr = self.message_router + oh = destination_hash + ol = None + if oh in mr.direct_links: + ol = mr.direct_links[oh] + elif oh in mr.backchannel_links: + ol = mr.backchannel_links[oh] + + if ol != None: return ol.get_mode() + + return None + + except Exception as e: + RNS.trace_exception(e) + return None + + def get_destination_lmd(self, destination_hash): + if not RNS.vendor.platformutils.is_android(): + return self._get_destination_lmd(destination_hash) + else: + if self.is_service: + return self._get_destination_lmd(destination_hash) + else: + try: + return self.service_rpc_request({"get_destination_lmd": destination_hash}) + except Exception as e: + ed = "Error while getting destination link mode over RPC: "+str(e) + RNS.log(ed, RNS.LOG_DEBUG) + return None + def __start_rpc_listener(self): try: RNS.log("Starting RPC listener", RNS.LOG_DEBUG) diff --git a/sbapp/ui/objectdetails.py b/sbapp/ui/objectdetails.py index 0de4f3d..e61b36e 100644 --- a/sbapp/ui/objectdetails.py +++ b/sbapp/ui/objectdetails.py @@ -830,12 +830,19 @@ class RVDetails(MDRecycleView): ler = self.delegate.app.sideband.get_destination_establishment_rate(self.delegate.object_hash) mtu = self.delegate.app.sideband.get_destination_mtu(self.delegate.object_hash) or RNS.Reticulum.MTU edr = self.delegate.app.sideband.get_destination_edr(self.delegate.object_hash) + lmd = self.delegate.app.sideband.get_destination_lmd(self.delegate.object_hash) if ler: lers = RNS.prettyspeed(ler, "b") mtus = RNS.prettysize(mtu) edrs = f"{RNS.prettyspeed(edr)}" if edr != None else "" self.entries.append({"icon": "lock-check-outline", "text": f"Link established, LER is [b]{lers}[/b], MTU is [b]{mtus}[/b]", "on_release": pass_job}) if edr: self.entries.append({"icon": "approximately-equal", "text": f"Expected data rate is [b]{edrs}[/b]", "on_release": pass_job}) + if lmd != None: + if lmd in RNS.Link.MODE_DESCRIPTIONS: lmds = RNS.Link.MODE_DESCRIPTIONS[lmd] + else: lmds = "unknown" + if lmds == "AES_128_CBC": lmds = "X25519/AES128" + elif lmds == "AES_256_CBC": lmds = "X25519/AES256" + self.entries.append({"icon": "link-lock", "text": f"Link mode is [b]{lmds}[/b]", "on_release": pass_job}) except Exception as e: RNS.trace_exception(e) From 55bf57d0abf3d21173c47ba527c491dc60957611 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 6 May 2025 19:15:41 +0200 Subject: [PATCH 085/271] Updated version and RNS dependency version --- sbapp/main.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index d1325b2..85f4a7f 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.5.1" +__version__ = "1.6.0" __variant__ = "" import sys diff --git a/setup.py b/setup.py index 8abfe15..32638bb 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.4", + "rns>=0.9.5", "lxmf>=0.6.3", "kivy>=2.3.0", "pillow>=10.2.0", From 09f6d4bd982b0b3580341112cbf7b119edd1d03e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 11 May 2025 22:32:02 +0200 Subject: [PATCH 086/271] Added transfer speed to outgoing message status --- sbapp/ui/messages.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 3a0722c..9e7ae76 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -319,6 +319,19 @@ class Messages(): prgstr = "" sphrase = "Sending" prg = self.app.sideband.get_lxm_progress(msg["hash"]) + if not hasattr(w, "last_prg_update"): + w.last_prg_update = time.time() + w.last_prg = prg + speed = None + else: + now = time.time() + size = msg["lxm"].packed_size + td = now - w.last_prg_update + if td == 0: speed = None + else: + bd = prg*size - w.last_prg*size + speed = (bd/td)*8 + if prg != None: prgstr = ", "+str(round(prg*100, 1))+"% done" if prg <= 0.00: @@ -336,6 +349,7 @@ class Messages(): sphrase = "Link established" elif prg >= 0.05: sphrase = "Sending" + if speed != None: prgstr += f", {RNS.prettyspeed(speed)}" if msg["title"]: titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" @@ -1450,7 +1464,10 @@ Builder.load_string(""" id: heading_text markup: True text: root.heading - adaptive_size: True + size_hint_y: None + height: self.texture_size[1] + # adaptive_size: True + # theme_text_color: 'Custom' # text_color: rgba(255,255,255,100) pos: 0, root.height - (self.height + root.padding[0] + dp(8)) From 2638688bbc820c24520f532d176acd1162695b78 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 12 May 2025 00:08:57 +0200 Subject: [PATCH 087/271] Added ability to exclude objects from telemetry collector responses --- sbapp/main.py | 2 +- sbapp/sideband/core.py | 116 ++++++++++++++++++++++++++++------------- 2 files changed, 82 insertions(+), 36 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 85f4a7f..5b06e44 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -5464,7 +5464,7 @@ class SidebandApp(MDApp): self.telemetry_info_dialog.dismiss() ok_button.bind(on_release=dl_ok) - result = self.sideband.request_latest_telemetry(from_addr=self.sideband.config["telemetry_collector"]) + result = self.sideband.request_latest_telemetry(from_addr=self.sideband.config["telemetry_collector"], is_collector_request=True) if result == "no_address": title_str = "Invalid Address" diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 7a17b8a..6a288a9 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -177,6 +177,7 @@ class SidebandCore(): self.latest_telemetry = None self.latest_packed_telemetry = None self.telemetry_changes = 0 + self.telemetry_response_excluded = [] self.pending_telemetry_send = False self.pending_telemetry_send_try = 0 self.pending_telemetry_send_maxtries = 2 @@ -253,13 +254,15 @@ class SidebandCore(): if not os.path.isdir(self.app_dir+"/app_storage"): os.makedirs(self.app_dir+"/app_storage") - self.config_path = self.app_dir+"/app_storage/sideband_config" - self.identity_path = self.app_dir+"/app_storage/primary_identity" - self.db_path = self.app_dir+"/app_storage/sideband.db" - self.lxmf_storage = self.app_dir+"/app_storage/" - self.log_dir = self.app_dir+"/app_storage/" - self.tmp_dir = self.app_dir+"/app_storage/tmp" - self.exports_dir = self.app_dir+"/exports" + self.config_path = self.app_dir+"/app_storage/sideband_config" + self.identity_path = self.app_dir+"/app_storage/primary_identity" + self.db_path = self.app_dir+"/app_storage/sideband.db" + self.lxmf_storage = self.app_dir+"/app_storage/" + self.log_dir = self.app_dir+"/app_storage/" + self.tmp_dir = self.app_dir+"/app_storage/tmp" + self.exports_dir = self.app_dir+"/exports" + self.telemetry_exclude_path = self.app_dir+"/app_storage/collector_response_excluded" + if RNS.vendor.platformutils.is_android(): self.webshare_dir = "./share/" else: @@ -572,6 +575,31 @@ class SidebandCore(): self.save_configuration() + def __load_telemetry_collector_excluded(self): + if not os.path.isfile(self.telemetry_exclude_path): + try: + file = open(self.telemetry_exclude_path, "wb") + file.write("# To exclude destinations from telemetry\n# collector responses, add them to this\n# file with one destination hash per line\n".encode("utf-8")) + file.close() + except Exception as e: + RNS.log(f"Could not create telemetry collector exclude file at {self.telemetry_exclude_path}", RNS.LOG_ERROR) + + try: + with open(self.telemetry_exclude_path, "rb") as file: + data = file.read().decode("utf-8") + for line in data.splitlines(): + if not line.startswith("#"): + if len(line) >= RNS.Reticulum.TRUNCATED_HASHLENGTH//8*2: + try: + destination_hash = bytes.fromhex(line[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8*2]) + self.telemetry_response_excluded.append(destination_hash) + except Exception as e: + RNS.log(f"Invalid destination hash {line} in telemetry response exclude file: {e}", RNS.LOG_ERROR) + + except Exception as e: + RNS.log(f"Error while loading telemetry collector response excludes: {e}", RNS.LOG_ERROR) + + def __load_config(self): RNS.log("Loading Sideband identity...", RNS.LOG_DEBUG) self.identity = RNS.Identity.from_file(self.identity_path) @@ -870,6 +898,8 @@ class SidebandCore(): self._db_upgradetables() self.__db_indices() + self.__load_telemetry_collector_excluded() + def __reload_config(self): RNS.log("Reloading Sideband configuration... ", RNS.LOG_DEBUG) with open(self.config_path, "rb") as config_file: @@ -1371,13 +1401,13 @@ class SidebandCore(): else: self.setstate(f"telemetry.{RNS.hexrep(message.destination_hash, delimit=False)}.request_sending", False) - def _service_request_latest_telemetry(self, from_addr=None): + def _service_request_latest_telemetry(self, from_addr=None, is_collector_request=False): if not RNS.vendor.platformutils.is_android(): return False else: if self.is_client: try: - return self.service_rpc_request({"request_latest_telemetry": {"from_addr": from_addr}}) + return self.service_rpc_request({"request_latest_telemetry": {"from_addr": from_addr, "is_collector_request": is_collector_request}}) except Exception as e: RNS.log("Error while requesting latest telemetry over RPC: "+str(e), RNS.LOG_DEBUG) @@ -1386,10 +1416,10 @@ class SidebandCore(): else: return False - def request_latest_telemetry(self, from_addr=None, is_livetrack=False): + def request_latest_telemetry(self, from_addr=None, is_livetrack=False, is_collector_request=False): if self.allow_service_dispatch and self.is_client: try: - return self._service_request_latest_telemetry(from_addr) + return self._service_request_latest_telemetry(from_addr, is_collector_request=is_collector_request) except Exception as e: RNS.log("Error requesting latest telemetry: "+str(e), RNS.LOG_ERROR) @@ -1428,7 +1458,7 @@ class SidebandCore(): request_timebase = self.getpersistent(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.timebase") or now - self.telemetry_request_max_history lxm_fields = { LXMF.FIELD_COMMANDS: [ - {Commands.TELEMETRY_REQUEST: request_timebase}, + {Commands.TELEMETRY_REQUEST: [request_timebase, is_collector_request]}, ]} lxm = LXMF.LXMessage(dest, source, "", desired_method=desired_method, fields = lxm_fields, include_ticket=True) @@ -1524,7 +1554,7 @@ class SidebandCore(): else: return False - def send_latest_telemetry(self, to_addr=None, stream=None, is_authorized_telemetry_request=False): + def send_latest_telemetry(self, to_addr=None, stream=None, is_authorized_telemetry_request=False, is_collector_response=False): if self.allow_service_dispatch and self.is_client: try: return self._service_send_latest_telemetry(to_addr, stream, is_authorized_telemetry_request) @@ -1566,7 +1596,7 @@ class SidebandCore(): else: desired_method = LXMF.LXMessage.DIRECT - lxm_fields = self.get_message_fields(to_addr, is_authorized_telemetry_request=is_authorized_telemetry_request, signal_already_sent=True) + lxm_fields = self.get_message_fields(to_addr, is_authorized_telemetry_request=is_authorized_telemetry_request, signal_already_sent=True, is_collector_response=is_collector_response) if lxm_fields == False and stream == None: return "already_sent" @@ -2065,7 +2095,7 @@ class SidebandCore(): connection.send(send_result) elif "request_latest_telemetry" in call: args = call["request_latest_telemetry"] - send_result = self.request_latest_telemetry(args["from_addr"]) + send_result = self.request_latest_telemetry(args["from_addr"], is_collector_request=args["is_collector_request"]) connection.send(send_result) elif "send_latest_telemetry" in call: args = call["send_latest_telemetry"] @@ -3146,6 +3176,7 @@ class SidebandCore(): tpacked = telemetry_entry[2] appearance = telemetry_entry[3] max_timebase = max(max_timebase, ttstamp) + if self._db_save_telemetry(tsource, tpacked, via = context_dest): RNS.log("Saved telemetry stream entry from "+RNS.prettyhexrep(tsource), RNS.LOG_DEBUG) if appearance != None: @@ -3804,7 +3835,7 @@ class SidebandCore(): if now > last_request_timebase+request_interval: try: RNS.log("Initiating telemetry request to collector", RNS.LOG_DEBUG) - self.request_latest_telemetry(from_addr=self.config["telemetry_collector"]) + self.request_latest_telemetry(from_addr=self.config["telemetry_collector"], is_collector_request=True) except Exception as e: RNS.log("An error occurred while requesting a telemetry update from collector. The contained exception was: "+str(e), RNS.LOG_ERROR) @@ -4428,7 +4459,7 @@ class SidebandCore(): except Exception as e: RNS.log("Error while setting last successul telemetry timebase for "+RNS.prettyhexrep(message.destination_hash), RNS.LOG_DEBUG) - def get_message_fields(self, context_dest, telemetry_update=False, is_authorized_telemetry_request=False, signal_already_sent=False): + def get_message_fields(self, context_dest, telemetry_update=False, is_authorized_telemetry_request=False, signal_already_sent=False, is_collector_response=False): fields = {} send_telemetry = (telemetry_update == True) or (self.should_send_telemetry(context_dest) or is_authorized_telemetry_request) send_appearance = self.config["telemetry_send_appearance"] or send_telemetry @@ -4437,7 +4468,10 @@ class SidebandCore(): telemeter = Telemeter.from_packed(self.latest_packed_telemetry) telemetry_timebase = telemeter.read_all()["time"]["utc"] last_success_tb = (self.getpersistent(f"telemetry.{RNS.hexrep(context_dest, delimit=False)}.last_send_success_timebase") or 0) - if telemetry_timebase > last_success_tb: + if is_collector_response and self.lxmf_destination.hash in self.telemetry_response_excluded: + RNS.log("Not embedding own telemetry collector response since own destination hash is excluded", RNS.LOG_DEBUG) + send_telemetry = False + elif telemetry_timebase > last_success_tb: RNS.log("Embedding own telemetry in message since current telemetry is newer than latest successful timebase", RNS.LOG_DEBUG) else: RNS.log("Not embedding own telemetry in message since current telemetry timebase ("+str(telemetry_timebase)+") is not newer than latest successful timebase ("+str(last_success_tb)+")", RNS.LOG_DEBUG) @@ -5200,11 +5234,19 @@ class SidebandCore(): RNS.log("Handling commands from "+RNS.prettyhexrep(context_dest), RNS.LOG_DEBUG) for command in commands: if Commands.TELEMETRY_REQUEST in command: - timebase = int(command[Commands.TELEMETRY_REQUEST]) + if type(command[Commands.TELEMETRY_REQUEST]) == list: + command_timebase = command[Commands.TELEMETRY_REQUEST][0] + enable_collector_request = command[Commands.TELEMETRY_REQUEST][1] + else: + # Handle old request format + command_timebase = command[Commands.TELEMETRY_REQUEST] + enable_collector_request = True + + timebase = int(command_timebase) RNS.log("Handling telemetry request with timebase "+str(timebase), RNS.LOG_DEBUG) - if self.config["telemetry_collector_enabled"]: + if self.config["telemetry_collector_enabled"] and enable_collector_request: RNS.log(f"Collector requests enabled, returning complete telemetry response for all known objects since {timebase}", RNS.LOG_DEBUG) - self.create_telemetry_collector_response(to_addr=context_dest, timebase=timebase, is_authorized_telemetry_request=True) + self.create_telemetry_collector_response(to_addr=context_dest, timebase=timebase, is_authorized_telemetry_request=True, is_collector_response=True) else: RNS.log("Responding with own latest telemetry", RNS.LOG_DEBUG) self.send_latest_telemetry(to_addr=context_dest) @@ -5240,7 +5282,7 @@ class SidebandCore(): except Exception as e: 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): + def create_telemetry_collector_response(self, to_addr, timebase, is_authorized_telemetry_request=False, is_collector_response=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" @@ -5252,20 +5294,23 @@ class SidebandCore(): elements = 0; added = 0 telemetry_stream = [] for source in sources: - if source != to_addr: - for entry in sources[source]: - elements += 1 - timestamp = entry[0]; packed_telemetry = entry[1] - appearance = self._db_get_appearance(source, raw=True) - te = [source, timestamp, packed_telemetry, appearance] - if only_latest: - if not source in added_sources: - added_sources[source] = True + if source in self.telemetry_response_excluded: + RNS.log(f"Excluding {RNS.prettyhexrep(source)} from collector response", RNS.LOG_DEBUG) + else: + if source != to_addr: + for entry in sources[source]: + elements += 1 + timestamp = entry[0]; packed_telemetry = entry[1] + appearance = self._db_get_appearance(source, raw=True) + te = [source, timestamp, packed_telemetry, appearance] + if only_latest: + if not source in added_sources: + added_sources[source] = True + telemetry_stream.append(te) + added += 1 + else: telemetry_stream.append(te) added += 1 - else: - telemetry_stream.append(te) - added += 1 if len(telemetry_stream) == 0: RNS.log(f"No new telemetry for request with timebase {timebase}", RNS.LOG_DEBUG) @@ -5273,7 +5318,8 @@ class SidebandCore(): return self.send_latest_telemetry( to_addr=to_addr, stream=telemetry_stream, - is_authorized_telemetry_request=is_authorized_telemetry_request + is_authorized_telemetry_request=is_authorized_telemetry_request, + is_collector_response=is_collector_response, ) From eb4d31ab354377786f340b8d9f45be15fbcdbea4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 12 May 2025 11:59:08 +0200 Subject: [PATCH 088/271] Updated dependencies --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 32638bb..7603f62 100644 --- a/setup.py +++ b/setup.py @@ -115,7 +115,7 @@ setuptools.setup( }, install_requires=[ "rns>=0.9.5", - "lxmf>=0.6.3", + "lxmf>=0.7.0", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 2f35ecff8036c453ad68f59d4bd98ca019f7c9ab Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 12 May 2025 14:46:23 +0200 Subject: [PATCH 089/271] Fixed missing none check --- sbapp/ui/messages.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 9e7ae76..80f82a5 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -327,7 +327,7 @@ class Messages(): now = time.time() size = msg["lxm"].packed_size td = now - w.last_prg_update - if td == 0: speed = None + if td == 0 or prg == None or w.last_prg == None: speed = None else: bd = prg*size - w.last_prg*size speed = (bd/td)*8 From 4aa290e41eb07b8b0ce466b1073e63c7f7e22685 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 12 May 2025 18:15:58 +0200 Subject: [PATCH 090/271] Updated dependencies --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 7603f62..1685226 100644 --- a/setup.py +++ b/setup.py @@ -123,7 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy<=1.26.4", - "lxst>=0.2.7", + "lxst>=0.3.0", "mistune>=3.0.2", "beautifulsoup4", "pycodec2;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From 98c64acb3bf83e148fd0e9cde21fa9582bfb0562 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 13 May 2025 18:13:01 +0200 Subject: [PATCH 091/271] Updated version and RNS dependency version --- sbapp/main.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 5b06e44..5bcb6cc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.6.0" +__version__ = "1.6.1" __variant__ = "" import sys diff --git a/setup.py b/setup.py index 1685226..4eb362f 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.5", + "rns>=0.9.6", "lxmf>=0.7.0", "kivy>=2.3.0", "pillow>=10.2.0", From 137c0b284ed39c00d4fc03ebebe3c4b4ce20745e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 15 May 2025 01:38:40 +0200 Subject: [PATCH 092/271] Added option to configure shared instance access --- sbapp/main.py | 8 +++++++- sbapp/sideband/core.py | 8 +++++++- sbapp/ui/layouts.py | 28 +++++++++++++++++++++++----- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 5bcb6cc..8abc5bc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3540,6 +3540,7 @@ class SidebandApp(MDApp): def save_connectivity(sender=None, event=None): self.sideband.config["connect_transport"] = self.connectivity_screen.ids.connectivity_enable_transport.active + self.sideband.config["connect_share_instance"] = self.connectivity_screen.ids.connectivity_share_instance.active self.sideband.config["connect_local"] = self.connectivity_screen.ids.connectivity_use_local.active self.sideband.config["connect_local_groupid"] = self.connectivity_screen.ids.connectivity_local_groupid.text self.sideband.config["connect_local_ifac_netname"] = self.connectivity_screen.ids.connectivity_local_ifac_netname.text @@ -3697,6 +3698,10 @@ class SidebandApp(MDApp): self.connectivity_screen.ids.connectivity_enable_transport.active = self.sideband.config["connect_transport"] con_collapse_transport(collapse=not self.sideband.config["connect_transport"]) self.connectivity_screen.ids.connectivity_enable_transport.bind(active=save_connectivity) + + self.connectivity_screen.ids.connectivity_share_instance.active = self.sideband.config["connect_share_instance"] + self.connectivity_screen.ids.connectivity_share_instance.bind(active=save_connectivity) + self.connectivity_screen.ids.connectivity_local_ifmode.text = self.sideband.config["connect_ifmode_local"].capitalize() self.connectivity_screen.ids.connectivity_tcp_ifmode.text = self.sideband.config["connect_ifmode_tcp"].capitalize() self.connectivity_screen.ids.connectivity_i2p_ifmode.text = self.sideband.config["connect_ifmode_i2p"].capitalize() @@ -3776,7 +3781,8 @@ class SidebandApp(MDApp): dialog.dismiss() yes_button.bind(on_release=dl_yes) - rpc_string = "rpc_key = "+RNS.hexrep(self.sideband.reticulum.rpc_key, delimit=False) + rpc_string = "shared_instance_type = tcp\n" + rpc_string += "rpc_key = "+RNS.hexrep(self.sideband.reticulum.rpc_key, delimit=False) Clipboard.copy(rpc_string) dialog.open() diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 6a288a9..dff6a52 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -663,6 +663,8 @@ class SidebandCore(): self.config["config_template"] = None if not "connect_transport" in self.config: self.config["connect_transport"] = False + if not "connect_share_instance" in self.config: + self.config["connect_share_instance"] = False if not "connect_rnode" in self.config: self.config["connect_rnode"] = False if not "connect_rnode_ifac_netname" in self.config: @@ -4114,7 +4116,11 @@ class SidebandCore(): self.setstate("init.loadingstate", "Substantiating Reticulum") try: - self.reticulum = RNS.Reticulum(configdir=self.rns_configdir, loglevel=selected_level, logdest=self._log_handler) + if RNS.vendor.platformutils.is_android() and self.config["connect_share_instance"] == True: + self.reticulum = RNS.Reticulum(configdir=self.rns_configdir, loglevel=selected_level, logdest=self._log_handler, shared_instance_type="tcp") + else: + self.reticulum = RNS.Reticulum(configdir=self.rns_configdir, loglevel=selected_level, logdest=self._log_handler) + if RNS.vendor.platformutils.is_android(): if self.is_service: if os.path.isfile(self.rns_configdir+"/config_template_invalid"): diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index e520c34..48ff811 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -641,15 +641,33 @@ MDScreen: # font_size: dp(24) # # disabled: True - MDLabel: - text: "Shared Instance Access\\n" - id: connectivity_shared_access_label - font_style: "H5" + # MDLabel: + # text: "Shared Instance Access\\n" + # id: connectivity_shared_access_label + # font_style: "H5" + + MDBoxLayout: + orientation: "horizontal" + padding: [0,0,dp(24),0] + size_hint_y: None + height: dp(24) + + MDLabel: + id: connectivity_shared_label + text: "Share Reticulum Instance" + font_style: "H6" + # disabled: True + + MDSwitch: + id: connectivity_share_instance + active: False + pos_hint: {"center_y": 0.3} + # disabled: True MDLabel: id: connectivity_shared_access markup: True - text: "The Reticulum instance launched by Sideband will be available for other programs on this system. By default, this grants connectivity to other local Reticulum-based programs, but no access to management, interface status and path information.\\n\\nIf you want to allow full functionality and ability to manage the running instance, you will need to configure other programs to use the correct RPC key for this instance.\\n\\nThis can be very useful for using other tools related to Reticulum, for example via command-line programs running in Termux. To do this, use the button below to copy the RPC key configuration line, and paste it into the Reticulum configuration file within the Termux environment, or other program.\\n\\nPlease note! [b]It is not necessary[/b] to enable Reticulum Transport for this to work!\\n\\n" + text: "You can make the Reticulum instance launched by Sideband available for other programs on this system. By default, this grants connectivity to other local Reticulum-based programs, but no access to management, interface status and path information.\\n\\nIf you want to allow full functionality and ability to manage the running instance, you will need to configure other programs to use the correct RPC key for this instance.\\n\\nThis can be very useful for using other tools related to Reticulum, for example via command-line programs running in Termux. To do this, use the button below to copy the RPC key configuration line, and paste it into the Reticulum configuration file within the Termux environment, or other program.\\n\\nPlease note! [b]It is not necessary[/b] to enable Reticulum Transport for this to work!\\n\\n" size_hint_y: None text_size: self.width, None height: self.texture_size[1] From 5355f0e91f1a54f14297a2e744838eac5a719a82 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 15 May 2025 15:58:21 +0200 Subject: [PATCH 093/271] Fixed link stats in object details --- sbapp/sideband/core.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index dff6a52..8fa432c 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1896,12 +1896,12 @@ class SidebandCore(): mr = self.message_router oh = destination_hash ol = None - if oh in mr.direct_links: + if oh in mr.direct_links and mr.direct_links[oh].status == RNS.Link.ACTIVE: ol = mr.direct_links[oh] elif oh in mr.backchannel_links: ol = mr.backchannel_links[oh] - if ol != None: + if ol != None and ol.status == RNS.Link.ACTIVE: ler = ol.get_establishment_rate() if ler: return ler @@ -1931,12 +1931,12 @@ class SidebandCore(): mr = self.message_router oh = destination_hash ol = None - if oh in mr.direct_links: + if oh in mr.direct_links and mr.direct_links[oh].status == RNS.Link.ACTIVE: ol = mr.direct_links[oh] elif oh in mr.backchannel_links: ol = mr.backchannel_links[oh] - if ol != None: + if ol != None and ol.status == RNS.Link.ACTIVE: return ol.get_mtu() return None @@ -1964,12 +1964,12 @@ class SidebandCore(): mr = self.message_router oh = destination_hash ol = None - if oh in mr.direct_links: + if oh in mr.direct_links and mr.direct_links[oh].status == RNS.Link.ACTIVE: ol = mr.direct_links[oh] elif oh in mr.backchannel_links: ol = mr.backchannel_links[oh] - if ol != None: + if ol != None and ol.status == RNS.Link.ACTIVE: return ol.get_expected_rate() return None @@ -1997,12 +1997,12 @@ class SidebandCore(): mr = self.message_router oh = destination_hash ol = None - if oh in mr.direct_links: + if oh in mr.direct_links and mr.direct_links[oh].status == RNS.Link.ACTIVE: ol = mr.direct_links[oh] elif oh in mr.backchannel_links: ol = mr.backchannel_links[oh] - if ol != None: return ol.get_mode() + if ol != None and ol.status == RNS.Link.ACTIVE: return ol.get_mode() return None @@ -2072,6 +2072,8 @@ class SidebandCore(): connection.send(self._get_destination_mtu(call["get_destination_mtu"])) elif "get_destination_edr" in call: connection.send(self._get_destination_edr(call["get_destination_edr"])) + elif "get_destination_lmd" in call: + connection.send(self._get_destination_lmd(call["get_destination_lmd"])) elif "send_message" in call: args = call["send_message"] send_result = self.send_message( From 5c5d5f830610456b8e324216c91ddf30253c739a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 16 May 2025 12:36:18 +0200 Subject: [PATCH 094/271] Updated dialog texts --- sbapp/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 8abc5bc..8e4a5cc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -5480,10 +5480,10 @@ class SidebandApp(MDApp): info_str = "No keys known for the destination. Connected reticules have been queried for the keys. Try again when an announce for the destination has arrived." elif result == "in_progress": title_str = "Transfer In Progress" - info_str = "There is already a telemetry request transfer in progress for this peer." + info_str = "There is already a telemetry request transfer in progress to the collector." elif result == "sent": title_str = "Request Sent" - info_str = "A telemetry request was sent to the peer. The peer should send any available telemetry shortly." + info_str = "A telemetry request was sent to the collector. The collector should send any available telemetry shortly." elif result == "not_sent": title_str = "Not Sent" info_str = "A telemetry request could not be sent." From 668dd48cee135622a6d146cafa7ce42349d432a6 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 16 May 2025 12:50:38 +0200 Subject: [PATCH 095/271] Updated dependencies --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 4eb362f..022ba5e 100644 --- a/setup.py +++ b/setup.py @@ -115,7 +115,7 @@ setuptools.setup( }, install_requires=[ "rns>=0.9.6", - "lxmf>=0.7.0", + "lxmf>=0.7.1", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 3c03070b6ed1125d8360cfa98e877e11b20cf561 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 17 May 2025 10:26:29 +0200 Subject: [PATCH 096/271] Added funding --- FUNDING.yml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 FUNDING.yml diff --git a/FUNDING.yml b/FUNDING.yml new file mode 100644 index 0000000..d125d55 --- /dev/null +++ b/FUNDING.yml @@ -0,0 +1,3 @@ +liberapay: Reticulum +ko_fi: markqvist +custom: "https://unsigned.io/donate" From aaed27d4ac65aefd2e583f2f417e6fcadadf2301 Mon Sep 17 00:00:00 2001 From: markqvist Date: Sat, 17 May 2025 20:37:55 +0200 Subject: [PATCH 097/271] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index cfb7fec..4bc11d3 100644 --- a/README.md +++ b/README.md @@ -323,6 +323,8 @@ You can help support the continued development of open, free and private communi ``` 0xae89F3B94fC4AD6563F0864a55F9a697a90261ff ``` +- Liberapay: https://liberapay.com/Reticulum/ + - Ko-Fi: https://ko-fi.com/markqvist From cd7562390c3d898985b84d1656b9c0462dccaaff Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 18 May 2025 18:03:25 +0200 Subject: [PATCH 098/271] Fixed incorrect widget ID. Closes #79. --- sbapp/ui/layouts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 48ff811..2f27bb7 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -653,7 +653,7 @@ MDScreen: height: dp(24) MDLabel: - id: connectivity_shared_label + id: connectivity_shared_access_label text: "Share Reticulum Instance" font_style: "H6" # disabled: True From e6ef41815cb9e830bf80ecfaa2895bb4a16639c7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 13 Jul 2025 14:58:16 +0200 Subject: [PATCH 099/271] Updated dependencies --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 022ba5e..3d967c2 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=0.9.6", - "lxmf>=0.7.1", + "rns>=1.0.0", + "lxmf>=0.8.0", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From aee675d38b4c6ec13dcbd9afb66ad9e88ae67257 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 13 Jul 2025 14:58:24 +0200 Subject: [PATCH 100/271] Fixed missing widget hide --- sbapp/main.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 8e4a5cc..69658a0 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.6.1" +__version__ = "1.7.0" __variant__ = "" import sys @@ -3498,6 +3498,7 @@ class SidebandApp(MDApp): self.widget_hide(self.connectivity_screen.ids.connectivity_serial_label) self.widget_hide(self.connectivity_screen.ids.connectivity_use_serial) self.widget_hide(self.connectivity_screen.ids.connectivity_serial_fields) + self.widget_hide(self.connectivity_screen.ids.connectivity_share_instance) self.widget_hide(self.connectivity_screen.ids.connectivity_shared_access) self.widget_hide(self.connectivity_screen.ids.connectivity_shared_access_label) self.widget_hide(self.connectivity_screen.ids.connectivity_shared_access_fields) From 0d2f7b25a371aa079b7e0581bb2e38e9b87e63cb Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 14 Jul 2025 00:11:21 +0200 Subject: [PATCH 101/271] Added service restart --- sbapp/main.py | 76 +++++++++++++++++++++++++++++-- sbapp/services/sidebandservice.py | 3 ++ sbapp/ui/layouts.py | 17 +++++++ 3 files changed, 93 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 69658a0..a238ad4 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -461,6 +461,67 @@ class SidebandApp(MDApp): argument = self.app_dir self.android_service.start(mActivity, argument) + def stop_service(self): + RNS.log("Stopping service...") + self.sideband.setstate("wants.service_stop", True) + while self.sideband.service_available(): time.sleep(0.2) + RNS.log("Service stopped") + + def restart_service_action(self, sender): + if hasattr(self, "service_restarting") and self.service_restarting == True: + toast(f"Service restart already in progress") + else: + toast(f"Restarting RNS service...") + if hasattr(self, "connectivity_screen") and self.connectivity_screen != None: + self.connectivity_screen.ids.button_service_restart.disabled = True + def job(): + if self.restart_service(): + def tj(delta_time): + toast(f"Service restarted successfully!") + if hasattr(self, "connectivity_screen") and self.connectivity_screen != None: + self.connectivity_screen.ids.button_service_restart.disabled = False + Clock.schedule_once(tj, 0.1) + else: + def tj(delta_time): + toast(f"Service restart failed") + if hasattr(self, "connectivity_screen") and self.connectivity_screen != None: + self.connectivity_screen.ids.button_service_restart.disabled = False + Clock.schedule_once(tj, 0.1) + + threading.Thread(target=job, daemon=True).start() + + def restart_service(self): + if hasattr(self, "service_restarting") and self.service_restarting == True: + return False + else: + self.service_restarting = True + self.stop_service() + RNS.log("Waiting for service shutdown", RNS.LOG_DEBUG) + while self.sideband.service_rpc_request({"getstate": "service.heartbeat"}): + time.sleep(1) + time.sleep(4) + + self.final_load_completed = False + self.sideband.service_stopped = True + + RNS.log("Starting service...", RNS.LOG_DEBUG) + self.start_service() + RNS.log("Waiting for service restart...", RNS.LOG_DEBUG) + restart_timeout = time.time() + 45 + while not self.sideband.service_rpc_request({"getstate": "service.heartbeat"}): + self.sideband.rpc_connection = None + time.sleep(1) + if time.time() > restart_timeout: + service_restarting = False + return False + + RNS.log("Service restarted", RNS.LOG_DEBUG) + self.sideband.service_stopped = False + self.final_load_completed = True + self.service_restarting = False + + return True + def start_final(self): # Start local core instance self.sideband.start() @@ -1098,19 +1159,28 @@ class SidebandApp(MDApp): description = rnode_errors["description"] self.sideband.setpersistent("runtime.errors.rnode", None) yes_button = MDRectangleFlatButton( - text="OK", + text="Ignore", + font_size=dp(18), + ) + restart_button = MDRectangleFlatButton( + text="Restart RNS", font_size=dp(18), ) self.hw_error_dialog = MDDialog( title="Hardware Error", text="While communicating with an RNode, Reticulum reported the following error:\n\n[i]"+str(description)+"[/i]", - buttons=[ yes_button ], + buttons=[ yes_button, restart_button ], # elevation=0, ) def dl_yes(s): self.hw_error_dialog.dismiss() self.hw_error_dialog.is_open = False + def dl_restart(s): + self.hw_error_dialog.dismiss() + self.hw_error_dialog.is_open = False + self.restart_service_action(None) yes_button.bind(on_release=dl_yes) + restart_button.bind(on_release=dl_restart) self.hw_error_dialog.open() self.hw_error_dialog.is_open = True @@ -3659,7 +3729,7 @@ class SidebandApp(MDApp): else: info = "By default, Sideband will try to discover and connect to any available Reticulum networks via active WiFi and/or Ethernet interfaces. If any Reticulum Transport Instances are found, Sideband will use these to connect to wider Reticulum networks. You can disable this behaviour if you don't want it.\n\n" info += "You can also connect to a network via a remote or local Reticulum instance using TCP or I2P. [b]Please Note![/b] Connecting via I2P requires that you already have I2P running on your device, and that the SAM API is enabled.\n\n" - info += "For changes to connectivity to take effect, you must shut down and restart Sideband.\n" + info += "For changes to connectivity to take effect, you must either restart the RNS service, or completely shut down and restart Sideband.\n" self.connectivity_screen.ids.connectivity_info.text = info self.connectivity_screen.ids.connectivity_use_local.active = self.sideband.config["connect_local"] diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index e718a6f..814c2b6 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -481,6 +481,9 @@ class SidebandService(): self.sideband.cleanup() self.release_locks() + # TODO: Check if this works in all cases + self.android_service.stopSelf() + def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 2f27bb7..fc4d9e0 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -360,6 +360,23 @@ MDScreen: text_size: self.width, None height: self.texture_size[1] + MDBoxLayout: + id: connectivity_shared_access_fields + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [0, 0, 0, dp(32)] + + MDRectangleFlatIconButton: + id: button_service_restart + icon: "restart" + text: "Restart RNS Service" + 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.app.restart_service_action(self) + MDBoxLayout: orientation: "horizontal" padding: [0,0,dp(24),0] From 73601ebe1e040b90d9f3431d97a8fe7b3a2615fb Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 14 Jul 2025 16:06:50 +0200 Subject: [PATCH 102/271] Added in-app BLE scanning and pairing --- sbapp/main.py | 122 ++++++++++++++++++++++++++++++++++++++++++++ sbapp/ui/layouts.py | 86 +++++++++++++++++++++++++++---- 2 files changed, 197 insertions(+), 11 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index a238ad4..5787300 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -277,6 +277,9 @@ else: from kivymd.utils.set_bars_colors import set_bars_colors android_api_version = autoclass('android.os.Build$VERSION').SDK_INT + from android.broadcast import BroadcastReceiver + BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter') + else: from .sideband.core import SidebandCore import sbapp.plyer as plyer @@ -408,6 +411,9 @@ class SidebandApp(MDApp): self.repository_url = None self.rnode_flasher_url = None + self.bt_adapter = None + self.discovered_bt_devices = {} + self.bt_bonded_devices = [] ################################################# # Application Startup # @@ -1008,6 +1014,65 @@ class SidebandApp(MDApp): self.check_bluetooth_permissions() + def bluetooth_update_bonded_devices(self, sender=None): + if self.bt_adapter == None: self.bt_adapter = BluetoothAdapter.getDefaultAdapter() + self.bt_bonded_devices = [] + for device in self.bt_adapter.getBondedDevices(): + device_addr = device.getAddress() + self.bt_bonded_devices.append(device_addr) + + RNS.log(f"Updated bonded devices: {self.bt_bonded_devices}", RNS.LOG_DEBUG) + + def bluetooth_scan_action(self, sender=None): + toast("Starting Bluetooth scan...") + self.start_bluetooth_scan() + + def start_bluetooth_scan(self): + self.check_bluetooth_permissions() + if not self.sideband.getpersistent("permissions.bluetooth"): + self.request_bluetooth_permissions() + else: + RNS.log("Starting bluetooth scan", RNS.LOG_DEBUG) + self.discovered_bt_devices = {} + + BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') + self.bt_found_action = BluetoothDevice.ACTION_FOUND + self.broadcast_receiver = BroadcastReceiver(self.on_broadcast, actions=[self.bt_found_action]) + self.broadcast_receiver.start() + + self.bt_adapter = BluetoothAdapter.getDefaultAdapter() + self.bluetooth_update_bonded_devices() + self.bt_adapter.startDiscovery() + + def stop_bluetooth_scan(self): + RNS.log("Stopping bluetooth scan", RNS.LOG_DEBUG) + self.check_bluetooth_permissions() + if not self.sideband.getpersistent("permissions.bluetooth"): + self.request_bluetooth_permissions() + else: + self.bt_adapter = BluetoothAdapter.getDefaultAdapter() + self.bt_adapter.cancelDiscovery() + + def on_broadcast(self, context, intent): + BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') + action = intent.getAction() + extras = intent.getExtras() + + if str(action) == "android.bluetooth.device.action.FOUND": + if extras: + try: + device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE", BluetoothDevice) + dev_name = device.getName() + dev_addr = device.getAddress() + if dev_name.startswith("RNode "): + dev_rssi = extras.getShort("android.bluetooth.device.extra.RSSI", -9999) + discovered_device = {"name": dev_name, "address": dev_addr, "rssi": dev_rssi, "discovered": time.time()} + self.discovered_bt_devices[dev_addr] = discovered_device + RNS.log(f"Discovered RNode: {discovered_device}", RNS.LOG_DEBUG) + + except Exception as e: + RNS.log(f"Error while mapping discovered device: {e}", RNS.LOG_ERROR) + def on_new_intent(self, intent): intent_action = intent.getAction() action = None @@ -4250,6 +4315,63 @@ class SidebandApp(MDApp): self.sideband.save_configuration() + def hardware_rnode_scan_job(self): + time.sleep(1.25) + added_devices = [] + scan_timeout = time.time()+16 + while time.time() < scan_timeout: + RNS.log("Scanning...", RNS.LOG_DEBUG) + for device_addr in self.discovered_bt_devices: + if device_addr not in added_devices and not device_addr in self.bt_bonded_devices: + new_device = self.discovered_bt_devices[device_addr] + added_devices.append(device_addr) + RNS.log(f"Adding device: {new_device}") + def add_factory(add_device): + def add_job(dt): + pair_addr = add_device["address"] + btn_text = "Pair "+add_device["name"] + def run_pair(sender): self.hardware_rnode_pair_device_action(pair_addr) + # device_button = MDRectangleFlatButton(text=btn_text,font_size=dp(16)) + device_button = MDRectangleFlatButton(text=btn_text, font_size=dp(16), padding=[dp(0), dp(14), dp(0), dp(14)], size_hint=[1.0, None]) + device_button.bind(on_release=run_pair) + self.hardware_rnode_screen.ids.rnode_scan_results.add_widget(device_button) + return add_job + + Clock.schedule_once(add_factory(new_device), 0.1) + + time.sleep(2) + + def job(dt): + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Pair New Device" + Clock.schedule_once(job, 0.2) + + if len(added_devices) == 0: + def job(dt): toast("No unpaired RNodes discovered") + Clock.schedule_once(job, 0.2) + + def hardware_rnode_pair_device_action(self, pair_addr): + RNS.log(f"Pair action for {pair_addr}", RNS.LOG_DEBUG) + self.stop_bluetooth_scan() + BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket') + if self.bt_adapter == None: self.bt_adapter = BluetoothAdapter.getDefaultAdapter() + addr_bytes = bytes.fromhex(pair_addr.replace(":", "")) + remote_device = self.bt_adapter.getRemoteDevice(addr_bytes) + RNS.log(f"Remote device: {remote_device}", RNS.LOG_DEBUG) + remote_device.createBond() + RNS.log("Create bond call returned", RNS.LOG_DEBUG) + + def hardware_rnode_bt_scan_action(self, sender=None): + self.discovered_bt_devices = {} + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Scanning..." + rw = [] + for child in self.hardware_rnode_screen.ids.rnode_scan_results.children: rw.append(child) + for w in rw: self.hardware_rnode_screen.ids.rnode_scan_results.remove_widget(w) + + Clock.schedule_once(self.bluetooth_scan_action, 0.5) + threading.Thread(target=self.hardware_rnode_scan_job, daemon=True).start() + def hardware_rnode_bt_on_action(self, sender=None): self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index fc4d9e0..08f0b5d 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -2400,7 +2400,7 @@ MDScreen: spacing: "24dp" size_hint_y: None height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(35)] + padding: [dp(0), dp(0), dp(0), dp(48)] MDRectangleFlatIconButton: id: rnode_mote_export @@ -2423,7 +2423,7 @@ MDScreen: on_release: root.app.hardware_rnode_import(self) MDLabel: - text: "Radio Options" + text: "Radio Options\\n" font_style: "H6" # MDTextField: @@ -2522,8 +2522,8 @@ MDScreen: MDBoxLayout: orientation: "horizontal" size_hint_y: None - padding: [0,0,dp(24),dp(0)] - height: dp(48) + padding: [0,dp(14),dp(24),dp(48)] + height: dp(86) MDLabel: text: "Control RNode Display" @@ -2534,6 +2534,18 @@ MDScreen: pos_hint: {"center_y": 0.3} active: False + MDLabel: + text: "Bluetooth Settings\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "If you enable connection via Bluetooth, Sideband will attempt to connect to any available and paired RNodes over Bluetooth. If your RNode uses BLE (ESP32-S3 and nRF devices) instead of classic Bluetooth, enable the [i]Device requires BLE[/i] option as well." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + MDBoxLayout: orientation: "horizontal" size_hint_y: None @@ -2567,7 +2579,65 @@ MDScreen: MDLabel: id: hardware_rnode_info markup: True - text: "If you enable connection via Bluetooth, Sideband will attempt to connect to any available and paired RNodes over Bluetooth.\\n\\nYou must first pair the RNode with your device for this to work. If your RNode does not have a physical pairing button, you can enable Bluetooth and put it into pairing mode by first connecting it via a USB cable, and using the buttons below. When plugging in the RNode over USB, you must grant Sideband permission to the USB device for this to work.\\n\\nYou can also change Bluetooth settings using the \\"rnodeconf\\" utility from a computer.\\n\\nBy default, Sideband will connect to the first available RNode that is paired. If you want to always use a specific RNode, you can enter its name in the Preferred RNode Device Name field below, for example \\"RNode A8EB\\".\\n" + text: "You must first pair the RNode with your device for this to work. To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode.You can then pair the device using the Bluetooth settings of your device, or by pressing the pairing button below.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(12)] + + MDRectangleFlatIconButton: + id: hardware_rnode_bt_scan_button + icon: "bluetooth-connect" + text: "Pair New Device" + 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.app.hardware_rnode_bt_scan_action(self) + + MDBoxLayout: + id: rnode_scan_results + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(12)] + + MDLabel: + id: hardware_rnode_info + markup: True + text: "By default, Sideband will connect to the first available RNode that is paired. If you want to always use a specific RNode, you can enter its name in the Preferred RNode Device Name field below, for example \\"RNode A8EB\\"." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_bt_device + hint_text: "Preferred RNode Device Name" + text: "" + font_size: dp(24) + + MDLabel: + text: "\\n\\nDevice Bluetooth Control\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "\\n\\nIf your RNode does not have a physical pairing button, you can enable Bluetooth and put it into pairing mode by first connecting it via a USB cable, and using the buttons below. When plugging in the RNode over USB, you must grant Sideband permission to the USB device for this to work.\\n\\nYou can also change Bluetooth settings using the \\"rnodeconf\\" utility from a computer.\\n" size_hint_y: None text_size: self.width, None height: self.texture_size[1] @@ -2610,12 +2680,6 @@ MDScreen: size_hint: [1.0, None] on_release: root.app.hardware_rnode_bt_pair_action(self) disabled: False - - MDTextField: - id: hardware_rnode_bt_device - hint_text: "Preferred RNode Device Name" - text: "" - font_size: dp(24) """ layout_hardware_serial_screen = """ From f0ec8fde4236a2fc4261759c706501b223940768 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 14 Jul 2025 20:37:58 +0200 Subject: [PATCH 103/271] Updated bluetooth scanning text --- sbapp/main.py | 3 ++- sbapp/ui/layouts.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 5787300..aa13885 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1061,7 +1061,8 @@ class SidebandApp(MDApp): if str(action) == "android.bluetooth.device.action.FOUND": if extras: try: - device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE", BluetoothDevice) + if android_api_version < 33: device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE") + else: device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE", BluetoothDevice) dev_name = device.getName() dev_addr = device.getAddress() if dev_name.startswith("RNode "): diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 08f0b5d..a29b580 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -2579,7 +2579,7 @@ MDScreen: MDLabel: id: hardware_rnode_info markup: True - text: "You must first pair the RNode with your device for this to work. To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode.You can then pair the device using the Bluetooth settings of your device, or by pressing the pairing button below.\\n" + text: "You must first pair the RNode with your device for this to work. To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode.You can then pair the device using the Bluetooth settings of your device, or by pressing the pairing button below. The in-app scanning and pairing is supported on Android 12+. If it doesn't work, use the Bluetooth settings of your device to scan and pair.\\n" size_hint_y: None text_size: self.width, None height: self.texture_size[1] From 354fb08297835eab04ac69d15081a18baf0583ac Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 14 Jul 2025 21:35:58 +0200 Subject: [PATCH 104/271] Cleanup --- sbapp/main.py | 1 + sbapp/ui/layouts.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index aa13885..46e7d0b 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3642,6 +3642,7 @@ class SidebandApp(MDApp): self.widget_hide(self.connectivity_screen.ids.connectivity_enable_transport) self.widget_hide(self.connectivity_screen.ids.connectivity_transport_info) self.widget_hide(self.connectivity_screen.ids.connectivity_transport_fields) + self.widget_hide(self.connectivity_screen.ids.connectivity_service_restart_fields) def con_collapse_local(collapse=True): # self.widget_hide(self.connectivity_screen.ids.connectivity_local_fields, collapse) diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index a29b580..f144eb5 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -361,7 +361,7 @@ MDScreen: height: self.texture_size[1] MDBoxLayout: - id: connectivity_shared_access_fields + id: connectivity_service_restart_fields orientation: "vertical" size_hint_y: None height: self.minimum_height From 26e115765f0c7eefb552b30add1d22230f2c96d1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Oct 2025 12:28:13 +0100 Subject: [PATCH 105/271] Updated dependencies --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 3d967c2..f766588 100644 --- a/setup.py +++ b/setup.py @@ -122,11 +122,11 @@ setuptools.setup( "materialyoucolor>=2.0.7", "ffpyplayer", "sh", - "numpy<=1.26.4", + "numpy>=2.3.4", "lxst>=0.3.0", "mistune>=3.0.2", "beautifulsoup4", - "pycodec2;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", + "pycodec2>=4.1.0;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", "pyaudio;sys.platform=='linux'", "pyobjus;sys.platform=='darwin'", "pyogg;sys.platform=='Windows' and sys.platform!='win32'", From 846e7d7687222809c9260b8c1886089f1daf9a6a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Oct 2025 18:10:43 +0100 Subject: [PATCH 106/271] Updated makefile --- sbapp/Makefile | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index 11bdb19..93a10fb 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -93,11 +93,14 @@ console: (adb logcat | grep "python\|sidebandservice") getrns: - (cp -rv ../../Reticulum/RNS ./;rm ./RNS/Utilities/RNS) + (cp -r ../../Reticulum/RNS ./) + -(rm ./RNS/Utilities/RNS) -(rm ./RNS/__pycache__ -r) - (cp -rv ../../LXMF/LXMF ./;rm ./LXMF/Utilities/LXMF) + (cp -r ../../LXMF/LXMF ./) + -(rm ./LXMF/Utilities/LXMF) -(rm ./LXMF/__pycache__ -r) - (cp -rv ../../LXST/LXST ./;rm ./LXST/Utilities/LXST) + (cp -r ../../LXST/LXST ./) + -(rm ./LXST/Utilities/LXST) -(rm ./LXST/__pycache__ -r) -(rm ./LXST/Utilities/__pycache__ -r) From 6a133842db59000616c2fe54a84ecf396aa3c428 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 28 Oct 2025 02:22:25 +0100 Subject: [PATCH 107/271] Updated build recipes --- recipes/able_recipe/__init__.py | 37 + recipes/able_recipe/setup.py | 9 + recipes/codec2/__init__.py | 1 + recipes/cython/__init__.py | 14 + recipes/ffpyplayer/__init__.py | 1480 +---------------- recipes/ffpyplayer/setup.py.patch | 4 +- recipes/hostpython3/__init__.py | 175 ++ .../patches/pyconfig_detection.patch | 13 + recipes/jpeg/Application.mk | 4 + recipes/jpeg/__init__.py | 58 + recipes/jpeg/build-static.patch | 85 + recipes/jpeg/remove-version.patch | 12 + recipes/numpy/__init__.py | 75 - .../add_libm_explicitly_to_build.patch | 20 - recipes/numpy/patches/ranlib.patch | 11 - .../numpy/patches/remove-default-paths.patch | 28 - recipes/pycodec2/__init__.py | 2 +- recipes/pyjnius/__init__.py | 44 + .../genericndkbuild_jnienv_getter.patch | 24 + recipes/pyjnius/sdl3_jnienv_getter.patch | 24 + recipes/pyjnius/use_cython.patch | 13 + recipes/python3/__init__.py | 445 +++++ .../cpython-311-ctypes-find-library.patch | 19 + ...py3.7.1_fix-ctypes-util-find-library.patch | 15 + .../patches/py3.7.1_fix-zlib-version.patch | 12 + .../patches/py3.7.1_fix_cortex_a8.patch | 14 + recipes/python3/patches/py3.8.1.patch | 42 + .../patches/py3.8.1_fix_cortex_a8.patch | 15 + .../python3/patches/pyconfig_detection.patch | 13 + .../patches/reproducible-buildinfo.diff | 13 + recipes/sqlite3/Android.mk | 11 + recipes/sqlite3/__init__.py | 36 + 32 files changed, 1154 insertions(+), 1614 deletions(-) create mode 100644 recipes/able_recipe/__init__.py create mode 100644 recipes/able_recipe/setup.py create mode 100644 recipes/cython/__init__.py create mode 100644 recipes/hostpython3/__init__.py create mode 100644 recipes/hostpython3/patches/pyconfig_detection.patch create mode 100644 recipes/jpeg/Application.mk create mode 100644 recipes/jpeg/__init__.py create mode 100644 recipes/jpeg/build-static.patch create mode 100644 recipes/jpeg/remove-version.patch delete mode 100644 recipes/numpy/__init__.py delete mode 100644 recipes/numpy/patches/add_libm_explicitly_to_build.patch delete mode 100644 recipes/numpy/patches/ranlib.patch delete mode 100644 recipes/numpy/patches/remove-default-paths.patch create mode 100644 recipes/pyjnius/__init__.py create mode 100644 recipes/pyjnius/genericndkbuild_jnienv_getter.patch create mode 100644 recipes/pyjnius/sdl3_jnienv_getter.patch create mode 100644 recipes/pyjnius/use_cython.patch create mode 100644 recipes/python3/__init__.py create mode 100644 recipes/python3/patches/cpython-311-ctypes-find-library.patch create mode 100644 recipes/python3/patches/py3.7.1_fix-ctypes-util-find-library.patch create mode 100644 recipes/python3/patches/py3.7.1_fix-zlib-version.patch create mode 100644 recipes/python3/patches/py3.7.1_fix_cortex_a8.patch create mode 100644 recipes/python3/patches/py3.8.1.patch create mode 100644 recipes/python3/patches/py3.8.1_fix_cortex_a8.patch create mode 100644 recipes/python3/patches/pyconfig_detection.patch create mode 100644 recipes/python3/patches/reproducible-buildinfo.diff create mode 100644 recipes/sqlite3/Android.mk create mode 100644 recipes/sqlite3/__init__.py diff --git a/recipes/able_recipe/__init__.py b/recipes/able_recipe/__init__.py new file mode 100644 index 0000000..3040fd3 --- /dev/null +++ b/recipes/able_recipe/__init__.py @@ -0,0 +1,37 @@ +""" +Android Bluetooth Low Energy +""" +from pythonforandroid.recipe import PythonRecipe +from pythonforandroid.toolchain import current_directory, info, shprint +import sh +from os.path import join + + +class AbleRecipe(PythonRecipe): + name = 'able_recipe' + depends = ['python3', 'setuptools', 'android'] + call_hostpython_via_targetpython = False + install_in_hostpython = True + + def prepare_build_dir(self, arch): + build_dir = self.get_build_dir(arch) + assert build_dir.endswith(self.name) + shprint(sh.rm, '-rf', build_dir) + shprint(sh.mkdir, build_dir) + + srcs = ('../../libs/able/able', 'setup.py') + + for filename in srcs: + print(f"Copy {join(self.get_recipe_dir(), filename)} to {build_dir}") + shprint(sh.cp, '-a', join(self.get_recipe_dir(), filename), + build_dir) + + def postbuild_arch(self, arch): + super(AbleRecipe, self).postbuild_arch(arch) + info('Copying able java class to classes build dir') + with current_directory(self.get_build_dir(arch.arch)): + shprint(sh.cp, '-a', join('able', 'src', 'org'), + self.ctx.javaclass_dir) + + +recipe = AbleRecipe() diff --git a/recipes/able_recipe/setup.py b/recipes/able_recipe/setup.py new file mode 100644 index 0000000..c2ca462 --- /dev/null +++ b/recipes/able_recipe/setup.py @@ -0,0 +1,9 @@ +from setuptools import setup + +setup( + name='able', + version='0.0.0', + packages=['able', 'able.android'], + description='Bluetooth Low Energy for Android', + license='MIT', +) diff --git a/recipes/codec2/__init__.py b/recipes/codec2/__init__.py index 81aa527..f8712df 100644 --- a/recipes/codec2/__init__.py +++ b/recipes/codec2/__init__.py @@ -2,6 +2,7 @@ from os.path import join from pythonforandroid.recipe import Recipe from pythonforandroid.toolchain import current_directory, shprint import sh +import os # For debugging, clean with # buildozer android p4a -- clean_recipe_build codec2 --local-recipes ~/Information/Source/Sideband/recipes diff --git a/recipes/cython/__init__.py b/recipes/cython/__init__.py new file mode 100644 index 0000000..1256edf --- /dev/null +++ b/recipes/cython/__init__.py @@ -0,0 +1,14 @@ +from pythonforandroid.recipe import CompiledComponentsPythonRecipe + + +class CythonRecipe(CompiledComponentsPythonRecipe): + + version = '3.1.6' + url = 'https://github.com/cython/cython/archive/{version}.tar.gz' + site_packages_name = 'cython' + depends = ['setuptools'] + call_hostpython_via_targetpython = False + install_in_hostpython = True + + +recipe = CythonRecipe() \ No newline at end of file diff --git a/recipes/ffpyplayer/__init__.py b/recipes/ffpyplayer/__init__.py index 03960b7..53a9d7f 100644 --- a/recipes/ffpyplayer/__init__.py +++ b/recipes/ffpyplayer/__init__.py @@ -1,1483 +1,9 @@ +from pythonforandroid.recipe import PyProjectRecipe, Recipe from os.path import join -from os.path import basename, dirname, exists, isdir, isfile, join, realpath, split -import glob - -import hashlib -from re import match - -import sh -import shutil -import fnmatch -import zipfile -import urllib.request -from urllib.request import urlretrieve -from os import listdir, unlink, environ, curdir, walk -from sys import stdout -from wheel.wheelfile import WheelFile -from wheel.cli.tags import tags as wheel_tags -import time -try: - from urlparse import urlparse -except ImportError: - from urllib.parse import urlparse - -import packaging.version - -from pythonforandroid.logger import ( - logger, info, warning, debug, shprint, info_main, error) -from pythonforandroid.util import ( - current_directory, ensure_dir, BuildInterruptingException, rmdir, move, - touch) -from pythonforandroid.util import load_source as import_recipe - - -url_opener = urllib.request.build_opener() -url_orig_headers = url_opener.addheaders -urllib.request.install_opener(url_opener) - - -class RecipeMeta(type): - def __new__(cls, name, bases, dct): - if name != 'Recipe': - if 'url' in dct: - dct['_url'] = dct.pop('url') - if 'version' in dct: - dct['_version'] = dct.pop('version') - - return super().__new__(cls, name, bases, dct) - - -class Recipe(metaclass=RecipeMeta): - _url = None - '''The address from which the recipe may be downloaded. This is not - essential, it may be omitted if the source is available some other - way, such as via the :class:`IncludedFilesBehaviour` mixin. - - If the url includes the version, you may (and probably should) - replace this with ``{version}``, which will automatically be - replaced by the :attr:`version` string during download. - - .. note:: Methods marked (internal) are used internally and you - probably don't need to call them, but they are available - if you want. - ''' - - _version = None - '''A string giving the version of the software the recipe describes, - e.g. ``2.0.3`` or ``master``.''' - - md5sum = None - '''The md5sum of the source from the :attr:`url`. Non-essential, but - you should try to include this, it is used to check that the download - finished correctly. - ''' - - sha512sum = None - '''The sha512sum of the source from the :attr:`url`. Non-essential, but - you should try to include this, it is used to check that the download - finished correctly. - ''' - - blake2bsum = None - '''The blake2bsum of the source from the :attr:`url`. Non-essential, but - you should try to include this, it is used to check that the download - finished correctly. - ''' - - depends = [] - '''A list containing the names of any recipes that this recipe depends on. - ''' - - conflicts = [] - '''A list containing the names of any recipes that are known to be - incompatible with this one.''' - - opt_depends = [] - '''A list of optional dependencies, that must be built before this - recipe if they are built at all, but whose presence is not essential.''' - - patches = [] - '''A list of patches to apply to the source. Values can be either a string - referring to the patch file relative to the recipe dir, or a tuple of the - string patch file and a callable, which will receive the kwargs `arch` and - `recipe`, which should return True if the patch should be applied.''' - - python_depends = [] - '''A list of pure-Python packages that this package requires. These - packages will NOT be available at build time, but will be added to the - list of pure-Python packages to install via pip. If you need these packages - at build time, you must create a recipe.''' - - archs = ['armeabi'] # Not currently implemented properly - - built_libraries = {} - """Each recipe that builds a system library (e.g.:libffi, openssl, etc...) - should contain a dict holding the relevant information of the library. The - keys should be the generated libraries and the values the relative path of - the library inside his build folder. This dict will be used to perform - different operations: - - copy the library into the right location, depending on if it's shared - or static) - - check if we have to rebuild the library - - Here an example of how it would look like for `libffi` recipe: - - - `built_libraries = {'libffi.so': '.libs'}` - - .. note:: in case that the built library resides in recipe's build - directory, you can set the following values for the relative - path: `'.', None or ''` - """ - - need_stl_shared = False - '''Some libraries or python packages may need the c++_shared in APK. - We can automatically do this for any recipe if we set this property to - `True`''' - - stl_lib_name = 'c++_shared' - ''' - The default STL shared lib to use: `c++_shared`. - - .. note:: Android NDK version > 17 only supports 'c++_shared', because - starting from NDK r18 the `gnustl_shared` lib has been deprecated. - ''' - - def get_stl_library(self, arch): - return join( - arch.ndk_lib_dir, - 'lib{name}.so'.format(name=self.stl_lib_name), - ) - - def install_stl_lib(self, arch): - if not self.ctx.has_lib( - arch.arch, 'lib{name}.so'.format(name=self.stl_lib_name) - ): - self.install_libs(arch, self.get_stl_library(arch)) - - @property - def version(self): - key = 'VERSION_' + self.name - return environ.get(key, self._version) - - @property - def url(self): - key = 'URL_' + self.name - return environ.get(key, self._url) - - @property - def versioned_url(self): - '''A property returning the url of the recipe with ``{version}`` - replaced by the :attr:`url`. If accessing the url, you should use this - property, *not* access the url directly.''' - if self.url is None: - return None - return self.url.format(version=self.version) - - def download_file(self, url, target, cwd=None): - """ - (internal) Download an ``url`` to a ``target``. - """ - if not url: - return - - info('Downloading {} from {}'.format(self.name, url)) - - if cwd: - target = join(cwd, target) - - parsed_url = urlparse(url) - if parsed_url.scheme in ('http', 'https'): - def report_hook(index, blksize, size): - if size <= 0: - progression = '{0} bytes'.format(index * blksize) - else: - progression = '{0:.2f}%'.format( - index * blksize * 100. / float(size)) - if "CI" not in environ: - stdout.write('- Download {}\r'.format(progression)) - stdout.flush() - - if exists(target): - unlink(target) - - # Download item with multiple attempts (for bad connections): - attempts = 0 - seconds = 1 - while True: - try: - # jqueryui.com returns a 403 w/ the default user agent - # Mozilla/5.0 doesnt handle redirection for liblzma - url_opener.addheaders = [('User-agent', 'Wget/1.0')] - urlretrieve(url, target, report_hook) - except OSError as e: - attempts += 1 - if attempts >= 5: - raise - stdout.write('Download failed: {}; retrying in {} second(s)...'.format(e, seconds)) - time.sleep(seconds) - seconds *= 2 - continue - finally: - url_opener.addheaders = url_orig_headers - break - return target - elif parsed_url.scheme in ('git', 'git+file', 'git+ssh', 'git+http', 'git+https'): - if not isdir(target): - if url.startswith('git+'): - url = url[4:] - # if 'version' is specified, do a shallow clone - if self.version: - ensure_dir(target) - with current_directory(target): - shprint(sh.git, 'init') - shprint(sh.git, 'remote', 'add', 'origin', url) - else: - shprint(sh.git, 'clone', '--recursive', url, target) - with current_directory(target): - if self.version: - shprint(sh.git, 'fetch', '--tags', '--depth', '1') - shprint(sh.git, 'checkout', self.version) - branch = sh.git('branch', '--show-current') - if branch: - shprint(sh.git, 'pull') - shprint(sh.git, 'pull', '--recurse-submodules') - shprint(sh.git, 'submodule', 'update', '--recursive', '--init', '--depth', '1') - return target - - def apply_patch(self, filename, arch, build_dir=None): - """ - Apply a patch from the current recipe directory into the current - build directory. - - .. versionchanged:: 0.6.0 - Add ability to apply patch from any dir via kwarg `build_dir`''' - """ - info("Applying patch {}".format(filename)) - build_dir = build_dir if build_dir else self.get_build_dir(arch) - filename = join(self.get_recipe_dir(), filename) - shprint(sh.patch, "-t", "-d", build_dir, "-p1", - "-i", filename, _tail=10) - - def copy_file(self, filename, dest): - info("Copy {} to {}".format(filename, dest)) - filename = join(self.get_recipe_dir(), filename) - dest = join(self.build_dir, dest) - shutil.copy(filename, dest) - - def append_file(self, filename, dest): - info("Append {} to {}".format(filename, dest)) - filename = join(self.get_recipe_dir(), filename) - dest = join(self.build_dir, dest) - with open(filename, "rb") as fd: - data = fd.read() - with open(dest, "ab") as fd: - fd.write(data) - - @property - def name(self): - '''The name of the recipe, the same as the folder containing it.''' - modname = self.__class__.__module__ - return modname.split(".", 2)[-1] - - @property - def filtered_archs(self): - '''Return archs of self.ctx that are valid build archs - for the Recipe.''' - result = [] - for arch in self.ctx.archs: - if not self.archs or (arch.arch in self.archs): - result.append(arch) - return result - - def check_recipe_choices(self): - '''Checks what recipes are being built to see which of the alternative - and optional dependencies are being used, - and returns a list of these.''' - recipes = [] - built_recipes = self.ctx.recipe_build_order - for recipe in self.depends: - if isinstance(recipe, (tuple, list)): - for alternative in recipe: - if alternative in built_recipes: - recipes.append(alternative) - break - for recipe in self.opt_depends: - if recipe in built_recipes: - recipes.append(recipe) - return sorted(recipes) - - def get_opt_depends_in_list(self, recipes): - '''Given a list of recipe names, returns those that are also in - self.opt_depends. - ''' - return [recipe for recipe in recipes if recipe in self.opt_depends] - - def get_build_container_dir(self, arch): - '''Given the arch name, returns the directory where it will be - built. - - This returns a different directory depending on what - alternative or optional dependencies are being built. - ''' - dir_name = self.get_dir_name() - return join(self.ctx.build_dir, 'other_builds', - dir_name, '{}__ndk_target_{}'.format(arch, self.ctx.ndk_api)) - - def get_dir_name(self): - choices = self.check_recipe_choices() - dir_name = '-'.join([self.name] + choices) - return dir_name - - def get_build_dir(self, arch): - '''Given the arch name, returns the directory where the - downloaded/copied package will be built.''' - - return join(self.get_build_container_dir(arch), self.name) - - def get_recipe_dir(self): - """ - Returns the local recipe directory or defaults to the core recipe - directory. - """ - if self.ctx.local_recipes is not None: - local_recipe_dir = join(self.ctx.local_recipes, self.name) - if exists(local_recipe_dir): - return local_recipe_dir - return join(self.ctx.root_dir, 'recipes', self.name) - - # Public Recipe API to be subclassed if needed - - def download_if_necessary(self): - info_main('Downloading {}'.format(self.name)) - user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower())) - if user_dir is not None: - info('P4A_{}_DIR is set, skipping download for {}'.format( - self.name, self.name)) - return - self.download() - - def download(self): - if self.url is None: - info('Skipping {} download as no URL is set'.format(self.name)) - return - - url = self.versioned_url - expected_digests = {} - for alg in set(hashlib.algorithms_guaranteed) | set(('md5', 'sha512', 'blake2b')): - expected_digest = getattr(self, alg + 'sum') if hasattr(self, alg + 'sum') else None - ma = match(u'^(.+)#' + alg + u'=([0-9a-f]{32,})$', url) - if ma: # fragmented URL? - if expected_digest: - raise ValueError( - ('Received {}sum from both the {} recipe ' - 'and its url').format(alg, self.name)) - url = ma.group(1) - expected_digest = ma.group(2) - if expected_digest: - expected_digests[alg] = expected_digest - - ensure_dir(join(self.ctx.packages_path, self.name)) - - with current_directory(join(self.ctx.packages_path, self.name)): - filename = shprint(sh.basename, url).stdout[:-1].decode('utf-8') - - do_download = True - marker_filename = '.mark-{}'.format(filename) - if exists(filename) and isfile(filename): - if not exists(marker_filename): - shprint(sh.rm, filename) - else: - for alg, expected_digest in expected_digests.items(): - current_digest = algsum(alg, filename) - if current_digest != expected_digest: - debug('* Generated {}sum: {}'.format(alg, - current_digest)) - debug('* Expected {}sum: {}'.format(alg, - expected_digest)) - raise ValueError( - ('Generated {0}sum does not match expected {0}sum ' - 'for {1} recipe').format(alg, self.name)) - do_download = False - - # If we got this far, we will download - if do_download: - debug('Downloading {} from {}'.format(self.name, url)) - - shprint(sh.rm, '-f', marker_filename) - self.download_file(self.versioned_url, filename) - touch(marker_filename) - - if exists(filename) and isfile(filename): - for alg, expected_digest in expected_digests.items(): - current_digest = algsum(alg, filename) - if current_digest != expected_digest: - debug('* Generated {}sum: {}'.format(alg, - current_digest)) - debug('* Expected {}sum: {}'.format(alg, - expected_digest)) - raise ValueError( - ('Generated {0}sum does not match expected {0}sum ' - 'for {1} recipe').format(alg, self.name)) - else: - info('{} download already cached, skipping'.format(self.name)) - - def unpack(self, arch): - info_main('Unpacking {} for {}'.format(self.name, arch)) - - build_dir = self.get_build_container_dir(arch) - - user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower())) - if user_dir is not None: - info('P4A_{}_DIR exists, symlinking instead'.format( - self.name.lower())) - if exists(self.get_build_dir(arch)): - return - rmdir(build_dir) - ensure_dir(build_dir) - shprint(sh.cp, '-a', user_dir, self.get_build_dir(arch)) - return - - if self.url is None: - info('Skipping {} unpack as no URL is set'.format(self.name)) - return - - filename = shprint( - sh.basename, self.versioned_url).stdout[:-1].decode('utf-8') - ma = match(u'^(.+)#[a-z0-9_]{3,}=([0-9a-f]{32,})$', filename) - if ma: # fragmented URL? - filename = ma.group(1) - - with current_directory(build_dir): - directory_name = self.get_build_dir(arch) - - if not exists(directory_name) or not isdir(directory_name): - extraction_filename = join( - self.ctx.packages_path, self.name, filename) - if isfile(extraction_filename): - if extraction_filename.endswith(('.zip', '.whl')): - try: - sh.unzip(extraction_filename) - except (sh.ErrorReturnCode_1, sh.ErrorReturnCode_2): - # return code 1 means unzipping had - # warnings but did complete, - # apparently happens sometimes with - # github zips - pass - fileh = zipfile.ZipFile(extraction_filename, 'r') - root_directory = fileh.filelist[0].filename.split('/')[0] - if root_directory != basename(directory_name): - move(root_directory, directory_name) - elif extraction_filename.endswith( - ('.tar.gz', '.tgz', '.tar.bz2', '.tbz2', '.tar.xz', '.txz')): - sh.tar('xf', extraction_filename) - root_directory = sh.tar('tf', extraction_filename).stdout.decode( - 'utf-8').split('\n')[0].split('/')[0] - if root_directory != basename(directory_name): - move(root_directory, directory_name) - else: - raise Exception( - 'Could not extract {} download, it must be .zip, ' - '.tar.gz or .tar.bz2 or .tar.xz'.format(extraction_filename)) - elif isdir(extraction_filename): - ensure_dir(directory_name) - for entry in listdir(extraction_filename): - # Previously we filtered out the .git folder, but during the build process for some recipes - # (e.g. when version is parsed by `setuptools_scm`) that may be needed. - shprint(sh.cp, '-Rv', - join(extraction_filename, entry), - directory_name) - else: - raise Exception( - 'Given path is neither a file nor a directory: {}' - .format(extraction_filename)) - - else: - info('{} is already unpacked, skipping'.format(self.name)) - - def get_recipe_env(self, arch=None, with_flags_in_cc=True): - """Return the env specialized for the recipe - """ - if arch is None: - arch = self.filtered_archs[0] - env = arch.get_env(with_flags_in_cc=with_flags_in_cc) - return env - - def prebuild_arch(self, arch): - '''Run any pre-build tasks for the Recipe. By default, this checks if - any prebuild_archname methods exist for the archname of the current - architecture, and runs them if so.''' - prebuild = "prebuild_{}".format(arch.arch.replace('-', '_')) - if hasattr(self, prebuild): - getattr(self, prebuild)() - else: - info('{} has no {}, skipping'.format(self.name, prebuild)) - - def is_patched(self, arch): - build_dir = self.get_build_dir(arch.arch) - return exists(join(build_dir, '.patched')) - - def apply_patches(self, arch, build_dir=None): - '''Apply any patches for the Recipe. - - .. versionchanged:: 0.6.0 - Add ability to apply patches from any dir via kwarg `build_dir`''' - if self.patches: - info_main('Applying patches for {}[{}]' - .format(self.name, arch.arch)) - - if self.is_patched(arch): - info_main('{} already patched, skipping'.format(self.name)) - return - - build_dir = build_dir if build_dir else self.get_build_dir(arch.arch) - for patch in self.patches: - if isinstance(patch, (tuple, list)): - patch, patch_check = patch - if not patch_check(arch=arch, recipe=self): - continue - - self.apply_patch( - patch.format(version=self.version, arch=arch.arch), - arch.arch, build_dir=build_dir) - - touch(join(build_dir, '.patched')) - - def should_build(self, arch): - '''Should perform any necessary test and return True only if it needs - building again. Per default we implement a library test, in case that - we detect so. - - ''' - if self.built_libraries: - return not all( - exists(lib) for lib in self.get_libraries(arch.arch) - ) - return True - - def build_arch(self, arch): - '''Run any build tasks for the Recipe. By default, this checks if - any build_archname methods exist for the archname of the current - architecture, and runs them if so.''' - build = "build_{}".format(arch.arch) - if hasattr(self, build): - getattr(self, build)() - - def install_libraries(self, arch): - '''This method is always called after `build_arch`. In case that we - detect a library recipe, defined by the class attribute - `built_libraries`, we will copy all defined libraries into the - right location. - ''' - if not self.built_libraries: - return - shared_libs = [ - lib for lib in self.get_libraries(arch) if lib.endswith(".so") - ] - self.install_libs(arch, *shared_libs) - - def postbuild_arch(self, arch): - '''Run any post-build tasks for the Recipe. By default, this checks if - any postbuild_archname methods exist for the archname of the - current architecture, and runs them if so. - ''' - postbuild = "postbuild_{}".format(arch.arch) - if hasattr(self, postbuild): - getattr(self, postbuild)() - - if self.need_stl_shared: - self.install_stl_lib(arch) - - def prepare_build_dir(self, arch): - '''Copies the recipe data into a build dir for the given arch. By - default, this unpacks a downloaded recipe. You should override - it (or use a Recipe subclass with different behaviour) if you - want to do something else. - ''' - self.unpack(arch) - - def clean_build(self, arch=None): - '''Deletes all the build information of the recipe. - - If arch is not None, only this arch dir is deleted. Otherwise - (the default) all builds for all archs are deleted. - - By default, this just deletes the main build dir. If the - recipe has e.g. object files biglinked, or .so files stored - elsewhere, you should override this method. - - This method is intended for testing purposes, it may have - strange results. Rebuild everything if this seems to happen. - - ''' - if arch is None: - base_dir = join(self.ctx.build_dir, 'other_builds', self.name) - else: - base_dir = self.get_build_container_dir(arch) - dirs = glob.glob(base_dir + '-*') - if exists(base_dir): - dirs.append(base_dir) - if not dirs: - warning('Attempted to clean build for {} but found no existing ' - 'build dirs'.format(self.name)) - - for directory in dirs: - rmdir(directory) - - # Delete any Python distributions to ensure the recipe build - # doesn't persist in site-packages - rmdir(self.ctx.python_installs_dir) - - def install_libs(self, arch, *libs): - libs_dir = self.ctx.get_libs_dir(arch.arch) - if not libs: - warning('install_libs called with no libraries to install!') - return - args = libs + (libs_dir,) - shprint(sh.cp, *args) - - def has_libs(self, arch, *libs): - return all(map(lambda lib: self.ctx.has_lib(arch.arch, lib), libs)) - - def get_libraries(self, arch_name, in_context=False): - """Return the full path of the library depending on the architecture. - Per default, the build library path it will be returned, unless - `get_libraries` has been called with kwarg `in_context` set to - True. - - .. note:: this method should be used for library recipes only - """ - recipe_libs = set() - if not self.built_libraries: - return recipe_libs - for lib, rel_path in self.built_libraries.items(): - if not in_context: - abs_path = join(self.get_build_dir(arch_name), rel_path, lib) - if rel_path in {".", "", None}: - abs_path = join(self.get_build_dir(arch_name), lib) - else: - abs_path = join(self.ctx.get_libs_dir(arch_name), lib) - recipe_libs.add(abs_path) - return recipe_libs - - @classmethod - def recipe_dirs(cls, ctx): - recipe_dirs = [] - if ctx.local_recipes is not None: - recipe_dirs.append(realpath(ctx.local_recipes)) - if ctx.storage_dir: - recipe_dirs.append(join(ctx.storage_dir, 'recipes')) - recipe_dirs.append(join(ctx.root_dir, "recipes")) - return recipe_dirs - - @classmethod - def list_recipes(cls, ctx): - forbidden_dirs = ('__pycache__', ) - for recipes_dir in cls.recipe_dirs(ctx): - if recipes_dir and exists(recipes_dir): - for name in listdir(recipes_dir): - if name in forbidden_dirs: - continue - fn = join(recipes_dir, name) - if isdir(fn): - yield name - - @classmethod - def get_recipe(cls, name, ctx): - '''Returns the Recipe with the given name, if it exists.''' - name = name.lower() - if not hasattr(cls, "recipes"): - cls.recipes = {} - if name in cls.recipes: - return cls.recipes[name] - - recipe_file = None - for recipes_dir in cls.recipe_dirs(ctx): - if not exists(recipes_dir): - continue - # Find matching folder (may differ in case): - for subfolder in listdir(recipes_dir): - if subfolder.lower() == name: - recipe_file = join(recipes_dir, subfolder, '__init__.py') - if exists(recipe_file): - name = subfolder # adapt to actual spelling - break - recipe_file = None - if recipe_file is not None: - break - - else: - raise ValueError('Recipe does not exist: {}'.format(name)) - - mod = import_recipe('pythonforandroid.recipes.{}'.format(name), recipe_file) - if len(logger.handlers) > 1: - logger.removeHandler(logger.handlers[1]) - recipe = mod.recipe - recipe.ctx = ctx - cls.recipes[name.lower()] = recipe - return recipe - - -class IncludedFilesBehaviour(object): - '''Recipe mixin class that will automatically unpack files included in - the recipe directory.''' - src_filename = None - - def prepare_build_dir(self, arch): - if self.src_filename is None: - raise BuildInterruptingException( - 'IncludedFilesBehaviour failed: no src_filename specified') - rmdir(self.get_build_dir(arch)) - shprint(sh.cp, '-a', join(self.get_recipe_dir(), self.src_filename), - self.get_build_dir(arch)) - - -class BootstrapNDKRecipe(Recipe): - '''A recipe class for recipes built in an Android project jni dir with - an Android.mk. These are not cached separatly, but built in the - bootstrap's own building directory. - - To build an NDK project which is not part of the bootstrap, see - :class:`~pythonforandroid.recipe.NDKRecipe`. - - To link with python, call the method :meth:`get_recipe_env` - with the kwarg *with_python=True*. - ''' - - dir_name = None # The name of the recipe build folder in the jni dir - - def get_build_container_dir(self, arch): - return self.get_jni_dir() - - def get_build_dir(self, arch): - if self.dir_name is None: - raise ValueError('{} recipe doesn\'t define a dir_name, but ' - 'this is necessary'.format(self.name)) - return join(self.get_build_container_dir(arch), self.dir_name) - - def get_jni_dir(self): - return join(self.ctx.bootstrap.build_dir, 'jni') - - def get_recipe_env(self, arch=None, with_flags_in_cc=True, with_python=False): - env = super().get_recipe_env(arch, with_flags_in_cc) - if not with_python: - return env - - env['PYTHON_INCLUDE_ROOT'] = self.ctx.python_recipe.include_root(arch.arch) - env['PYTHON_LINK_ROOT'] = self.ctx.python_recipe.link_root(arch.arch) - env['EXTRA_LDLIBS'] = ' -lpython{}'.format( - self.ctx.python_recipe.link_version) - return env - - -class NDKRecipe(Recipe): - '''A recipe class for any NDK project not included in the bootstrap.''' - - generated_libraries = [] - - def should_build(self, arch): - lib_dir = self.get_lib_dir(arch) - - for lib in self.generated_libraries: - if not exists(join(lib_dir, lib)): - return True - - return False - - def get_lib_dir(self, arch): - return join(self.get_build_dir(arch.arch), 'obj', 'local', arch.arch) - - def get_jni_dir(self, arch): - return join(self.get_build_dir(arch.arch), 'jni') - - def build_arch(self, arch, *extra_args): - super().build_arch(arch) - - env = self.get_recipe_env(arch) - with current_directory(self.get_build_dir(arch.arch)): - shprint( - sh.Command(join(self.ctx.ndk_dir, "ndk-build")), - 'V=1', - 'NDK_DEBUG=' + ("1" if self.ctx.build_as_debuggable else "0"), - 'APP_PLATFORM=android-' + str(self.ctx.ndk_api), - 'APP_ABI=' + arch.arch, - *extra_args, _env=env - ) - - -class PythonRecipe(Recipe): - site_packages_name = None - '''The name of the module's folder when installed in the Python - site-packages (e.g. for pyjnius it is 'jnius')''' - - call_hostpython_via_targetpython = True - '''If True, tries to install the module using the hostpython binary - copied to the target (normally arm) python build dir. However, this - will fail if the module tries to import e.g. _io.so. Set this to False - to call hostpython from its own build dir, installing the module in - the right place via arguments to setup.py. However, this may not set - the environment correctly and so False is not the default.''' - - install_in_hostpython = False - '''If True, additionally installs the module in the hostpython build - dir. This will make it available to other recipes if - call_hostpython_via_targetpython is False. - ''' - - install_in_targetpython = True - '''If True, installs the module in the targetpython installation dir. - This is almost always what you want to do.''' - - setup_extra_args = [] - '''List of extra arguments to pass to setup.py''' - - depends = ['python3'] - ''' - .. note:: it's important to keep this depends as a class attribute outside - `__init__` because sometimes we only initialize the class, so the - `__init__` call won't be called and the deps would be missing - (which breaks the dependency graph computation) - - .. warning:: don't forget to call `super().__init__()` in any recipe's - `__init__`, or otherwise it may not be ensured that it depends - on python2 or python3 which can break the dependency graph - ''' - - hostpython_prerequisites = [] - '''List of hostpython packages required to build a recipe''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - if 'python3' not in self.depends: - # We ensure here that the recipe depends on python even it overrode - # `depends`. We only do this if it doesn't already depend on any - # python, since some recipes intentionally don't depend on/work - # with all python variants - depends = self.depends - depends.append('python3') - depends = list(set(depends)) - self.depends = depends - - def clean_build(self, arch=None): - super().clean_build(arch=arch) - name = self.folder_name - python_install_dirs = glob.glob(join(self.ctx.python_installs_dir, '*')) - for python_install in python_install_dirs: - site_packages_dir = glob.glob(join(python_install, 'lib', 'python*', - 'site-packages')) - if site_packages_dir: - build_dir = join(site_packages_dir[0], name) - if exists(build_dir): - info('Deleted {}'.format(build_dir)) - rmdir(build_dir) - - @property - def real_hostpython_location(self): - host_name = 'host{}'.format(self.ctx.python_recipe.name) - if host_name == 'hostpython3': - python_recipe = Recipe.get_recipe(host_name, self.ctx) - return python_recipe.python_exe - else: - python_recipe = self.ctx.python_recipe - return 'python{}'.format(python_recipe.version) - - @property - def hostpython_location(self): - if not self.call_hostpython_via_targetpython: - return self.real_hostpython_location - return self.ctx.hostpython - - @property - def folder_name(self): - '''The name of the build folders containing this recipe.''' - name = self.site_packages_name - if name is None: - name = self.name - return name - - def get_recipe_env(self, arch=None, with_flags_in_cc=True): - env = super().get_recipe_env(arch, with_flags_in_cc) - env['PYTHONNOUSERSITE'] = '1' - # Set the LANG, this isn't usually important but is a better default - # as it occasionally matters how Python e.g. reads files - env['LANG'] = "en_GB.UTF-8" - # Binaries made by packages installed by pip - env["PATH"] = join(self.hostpython_site_dir, "bin") + ":" + env["PATH"] - - if not self.call_hostpython_via_targetpython: - env['CFLAGS'] += ' -I{}'.format( - self.ctx.python_recipe.include_root(arch.arch) - ) - env['LDFLAGS'] += ' -L{} -lpython{}'.format( - self.ctx.python_recipe.link_root(arch.arch), - self.ctx.python_recipe.link_version, - ) - - hppath = [] - hppath.append(join(dirname(self.hostpython_location), 'Lib')) - hppath.append(join(hppath[0], 'site-packages')) - builddir = join(dirname(self.hostpython_location), 'build') - if exists(builddir): - hppath += [join(builddir, d) for d in listdir(builddir) - if isdir(join(builddir, d))] - if len(hppath) > 0: - if 'PYTHONPATH' in env: - env['PYTHONPATH'] = ':'.join(hppath + [env['PYTHONPATH']]) - else: - env['PYTHONPATH'] = ':'.join(hppath) - return env - - def should_build(self, arch): - name = self.folder_name - if self.ctx.has_package(name, arch): - info('Python package already exists in site-packages') - return False - info('{} apparently isn\'t already in site-packages'.format(name)) - return True - - def build_arch(self, arch): - '''Install the Python module by calling setup.py install with - the target Python dir.''' - self.install_hostpython_prerequisites() - super().build_arch(arch) - self.install_python_package(arch) - - def install_python_package(self, arch, name=None, env=None, is_dir=True): - '''Automate the installation of a Python package (or a cython - package where the cython components are pre-built).''' - # arch = self.filtered_archs[0] # old kivy-ios way - if name is None: - name = self.name - if env is None: - env = self.get_recipe_env(arch) - - info('Installing {} into site-packages'.format(self.name)) - - hostpython = sh.Command(self.hostpython_location) - hpenv = env.copy() - with current_directory(self.get_build_dir(arch.arch)): - shprint(hostpython, 'setup.py', 'install', '-O2', - '--root={}'.format(self.ctx.get_python_install_dir(arch.arch)), - '--install-lib=.', - _env=hpenv, *self.setup_extra_args) - - # If asked, also install in the hostpython build dir - if self.install_in_hostpython: - self.install_hostpython_package(arch) - - def get_hostrecipe_env(self, arch): - env = environ.copy() - env['PYTHONPATH'] = self.hostpython_site_dir - return env - - @property - def hostpython_site_dir(self): - return join(dirname(self.real_hostpython_location), 'Lib', 'site-packages') - - def install_hostpython_package(self, arch): - env = self.get_hostrecipe_env(arch) - real_hostpython = sh.Command(self.real_hostpython_location) - shprint(real_hostpython, 'setup.py', 'install', '-O2', - '--root={}'.format(dirname(self.real_hostpython_location)), - '--install-lib=Lib/site-packages', - _env=env, *self.setup_extra_args) - - @property - def python_major_minor_version(self): - parsed_version = packaging.version.parse(self.ctx.python_recipe.version) - return f"{parsed_version.major}.{parsed_version.minor}" - - def install_hostpython_prerequisites(self, packages=None, force_upgrade=True): - if not packages: - packages = self.hostpython_prerequisites - - if len(packages) == 0: - return - - pip_options = [ - "install", - *packages, - "--target", self.hostpython_site_dir, "--python-version", - self.ctx.python_recipe.version, - # Don't use sources, instead wheels - "--only-binary=:all:", - ] - if force_upgrade: - pip_options.append("--upgrade") - # Use system's pip - shprint(sh.pip, *pip_options) - - def restore_hostpython_prerequisites(self, packages): - _packages = [] - for package in packages: - original_version = Recipe.get_recipe(package, self.ctx).version - _packages.append(package + "==" + original_version) - self.install_hostpython_prerequisites(packages=_packages) - - -class CompiledComponentsPythonRecipe(PythonRecipe): - pre_build_ext = False - - build_cmd = 'build_ext' - - def build_arch(self, arch): - '''Build any cython components, then install the Python module by - calling setup.py install with the target Python dir. - ''' - Recipe.build_arch(self, arch) - self.install_hostpython_prerequisites() - self.build_compiled_components(arch) - self.install_python_package(arch) - - def build_compiled_components(self, arch): - info('Building compiled components in {}'.format(self.name)) - - env = self.get_recipe_env(arch) - hostpython = sh.Command(self.hostpython_location) - with current_directory(self.get_build_dir(arch.arch)): - if self.install_in_hostpython: - shprint(hostpython, 'setup.py', 'clean', '--all', _env=env) - shprint(hostpython, 'setup.py', self.build_cmd, '-v', - _env=env, *self.setup_extra_args) - build_dir = glob.glob('build/lib.*')[0] - shprint(sh.find, build_dir, '-name', '"*.o"', '-exec', - env['STRIP'], '{}', ';', _env=env) - - def install_hostpython_package(self, arch): - env = self.get_hostrecipe_env(arch) - self.rebuild_compiled_components(arch, env) - super().install_hostpython_package(arch) - - def rebuild_compiled_components(self, arch, env): - info('Rebuilding compiled components in {}'.format(self.name)) - - hostpython = sh.Command(self.real_hostpython_location) - shprint(hostpython, 'setup.py', 'clean', '--all', _env=env) - shprint(hostpython, 'setup.py', self.build_cmd, '-v', _env=env, - *self.setup_extra_args) - - -class CppCompiledComponentsPythonRecipe(CompiledComponentsPythonRecipe): - """ Extensions that require the cxx-stl """ - call_hostpython_via_targetpython = False - need_stl_shared = True - - -class CythonRecipe(PythonRecipe): - pre_build_ext = False - cythonize = True - cython_args = [] - call_hostpython_via_targetpython = False - - def build_arch(self, arch): - '''Build any cython components, then install the Python module by - calling setup.py install with the target Python dir. - ''' - Recipe.build_arch(self, arch) - self.build_cython_components(arch) - self.install_python_package(arch) - - def build_cython_components(self, arch): - info('Cythonizing anything necessary in {}'.format(self.name)) - - env = self.get_recipe_env(arch) - - with current_directory(self.get_build_dir(arch.arch)): - hostpython = sh.Command(self.ctx.hostpython) - shprint(hostpython, '-c', 'import sys; print(sys.path)', _env=env) - debug('cwd is {}'.format(realpath(curdir))) - info('Trying first build of {} to get cython files: this is ' - 'expected to fail'.format(self.name)) - - manually_cythonise = False - try: - shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env, - *self.setup_extra_args) - except sh.ErrorReturnCode_1: - print() - info('{} first build failed (as expected)'.format(self.name)) - manually_cythonise = True - - if manually_cythonise: - self.cythonize_build(env=env) - shprint(hostpython, 'setup.py', 'build_ext', '-v', _env=env, - _tail=20, _critical=True, *self.setup_extra_args) - else: - info('First build appeared to complete correctly, skipping manual' - 'cythonising.') - - if not self.ctx.with_debug_symbols: - self.strip_object_files(arch, env) - - def strip_object_files(self, arch, env, build_dir=None): - if build_dir is None: - build_dir = self.get_build_dir(arch.arch) - with current_directory(build_dir): - info('Stripping object files') - shprint(sh.find, '.', '-iname', '*.so', '-exec', - '/usr/bin/echo', '{}', ';', _env=env) - shprint(sh.find, '.', '-iname', '*.so', '-exec', - env['STRIP'].split(' ')[0], '--strip-unneeded', - # '/usr/bin/strip', '--strip-unneeded', - '{}', ';', _env=env) - - def cythonize_file(self, env, build_dir, filename): - short_filename = filename - if filename.startswith(build_dir): - short_filename = filename[len(build_dir) + 1:] - info(u"Cythonize {}".format(short_filename)) - cyenv = env.copy() - if 'CYTHONPATH' in cyenv: - cyenv['PYTHONPATH'] = cyenv['CYTHONPATH'] - elif 'PYTHONPATH' in cyenv: - del cyenv['PYTHONPATH'] - if 'PYTHONNOUSERSITE' in cyenv: - cyenv.pop('PYTHONNOUSERSITE') - python_command = sh.Command("python{}".format( - self.ctx.python_recipe.major_minor_version_string.split(".")[0] - )) - shprint(python_command, "-c" - "import sys; from Cython.Compiler.Main import setuptools_main; sys.exit(setuptools_main());", - filename, *self.cython_args, _env=cyenv) - - def cythonize_build(self, env, build_dir="."): - if not self.cythonize: - info('Running cython cancelled per recipe setting') - return - info('Running cython where appropriate') - for root, dirnames, filenames in walk("."): - for filename in fnmatch.filter(filenames, "*.pyx"): - self.cythonize_file(env, build_dir, join(root, filename)) - - def get_recipe_env(self, arch, with_flags_in_cc=True): - env = super().get_recipe_env(arch, with_flags_in_cc) - env['LDFLAGS'] = env['LDFLAGS'] + ' -L{} '.format( - self.ctx.get_libs_dir(arch.arch) + - ' -L{} '.format(self.ctx.libs_dir) + - ' -L{}'.format(join(self.ctx.bootstrap.build_dir, 'obj', 'local', - arch.arch))) - - env['LDSHARED'] = env['CC'] + ' -shared' - # shprint(sh.whereis, env['LDSHARED'], _env=env) - env['LIBLINK'] = 'NOTNONE' - if self.ctx.copy_libs: - env['COPYLIBS'] = '1' - - # Every recipe uses its own liblink path, object files are - # collected and biglinked later - liblink_path = join(self.get_build_container_dir(arch.arch), - 'objects_{}'.format(self.name)) - env['LIBLINK_PATH'] = liblink_path - ensure_dir(liblink_path) - - return env - - -class PyProjectRecipe(PythonRecipe): - '''Recipe for projects which containes `pyproject.toml`''' - - # Extra args to pass to `python -m build ...` - extra_build_args = [] - call_hostpython_via_targetpython = False - - def get_recipe_env(self, arch, **kwargs): - # Custom hostpython - self.ctx.python_recipe.python_exe = join( - self.ctx.python_recipe.get_build_dir(arch), "android-build", "python3") - env = super().get_recipe_env(arch, **kwargs) - build_dir = self.get_build_dir(arch) - ensure_dir(build_dir) - build_opts = join(build_dir, "build-opts.cfg") - - with open(build_opts, "w") as file: - file.write("[bdist_wheel]\nplat-name={}".format( - self.get_wheel_platform_tag(arch) - )) - file.close() - - env["DIST_EXTRA_CONFIG"] = build_opts - return env - - def get_wheel_platform_tag(self, arch): - return "android_" + { - "armeabi-v7a": "arm", - "arm64-v8a": "aarch64", - "x86_64": "x86_64", - "x86": "i686", - }[arch.arch] - - def install_wheel(self, arch, built_wheels): - _wheel = built_wheels[0] - built_wheel_dir = dirname(_wheel) - # Fix wheel platform tag - wheel_tag = wheel_tags( - _wheel, - platform_tags=self.get_wheel_platform_tag(arch), - remove=True, - ) - selected_wheel = join(built_wheel_dir, wheel_tag) - - _dev_wheel_dir = environ.get("P4A_WHEEL_DIR", False) - if _dev_wheel_dir: - ensure_dir(_dev_wheel_dir) - shprint(sh.cp, selected_wheel, _dev_wheel_dir) - - info(f"Installing built wheel: {wheel_tag}") - destination = self.ctx.get_python_install_dir(arch.arch) - with WheelFile(selected_wheel) as wf: - for zinfo in wf.filelist: - wf.extract(zinfo, destination) - wf.close() - - def build_arch(self, arch): - self.install_hostpython_prerequisites( - packages=["build[virtualenv]", "pip"] + self.hostpython_prerequisites - ) - build_dir = self.get_build_dir(arch.arch) - env = self.get_recipe_env(arch, with_flags_in_cc=True) - # make build dir separatly - sub_build_dir = join(build_dir, "p4a_android_build") - ensure_dir(sub_build_dir) - # copy hostpython to built python to ensure correct selection of libs and includes - shprint(sh.cp, self.real_hostpython_location, self.ctx.python_recipe.python_exe) - - build_args = [ - "-m", - "build", - "--wheel", - "--config-setting", - "builddir={}".format(sub_build_dir), - ] + self.extra_build_args - - built_wheels = [] - with current_directory(build_dir): - shprint( - sh.Command(self.ctx.python_recipe.python_exe), *build_args, _env=env - ) - built_wheels = [realpath(whl) for whl in glob.glob("dist/*.whl")] - self.install_wheel(arch, built_wheels) - - -class MesonRecipe(PyProjectRecipe): - '''Recipe for projects which uses meson as build system''' - - meson_version = "1.4.0" - ninja_version = "1.11.1.1" - - def sanitize_flags(self, *flag_strings): - return " ".join(flag_strings).strip().split(" ") - - def get_recipe_meson_options(self, arch): - env = self.get_recipe_env(arch, with_flags_in_cc=True) - return { - "binaries": { - "c": arch.get_clang_exe(with_target=True), - "cpp": arch.get_clang_exe(with_target=True, plus_plus=True), - "ar": self.ctx.ndk.llvm_ar, - "strip": self.ctx.ndk.llvm_strip, - }, - "built-in options": { - "c_args": self.sanitize_flags(env["CFLAGS"], env["CPPFLAGS"]), - "cpp_args": self.sanitize_flags(env["CXXFLAGS"], env["CPPFLAGS"]), - "c_link_args": self.sanitize_flags(env["LDFLAGS"]), - "cpp_link_args": self.sanitize_flags(env["LDFLAGS"]), - }, - "properties": { - "needs_exe_wrapper": True, - "sys_root": self.ctx.ndk.sysroot - }, - "host_machine": { - "cpu_family": { - "arm64-v8a": "aarch64", - "armeabi-v7a": "arm", - "x86_64": "x86_64", - "x86": "x86" - }[arch.arch], - "cpu": { - "arm64-v8a": "aarch64", - "armeabi-v7a": "armv7", - "x86_64": "x86_64", - "x86": "i686" - }[arch.arch], - "endian": "little", - "system": "android", - } - } - - def write_build_options(self, arch): - """Writes python dict to meson config file""" - option_data = "" - build_options = self.get_recipe_meson_options(arch) - for key in build_options.keys(): - data_chunk = "[{}]".format(key) - for subkey in build_options[key].keys(): - value = build_options[key][subkey] - if isinstance(value, int): - value = str(value) - elif isinstance(value, str): - value = "'{}'".format(value) - elif isinstance(value, bool): - value = "true" if value else "false" - elif isinstance(value, list): - value = "['" + "', '".join(value) + "']" - data_chunk += "\n" + subkey + " = " + value - option_data += data_chunk + "\n\n" - return option_data - - def ensure_args(self, *args): - for arg in args: - if arg not in self.extra_build_args: - self.extra_build_args.append(arg) - - def build_arch(self, arch): - cross_file = join("/tmp", "android.meson.cross") - info("Writing cross file at: {}".format(cross_file)) - # write cross config file - with open(cross_file, "w") as file: - file.write(self.write_build_options(arch)) - file.close() - # set cross file - self.ensure_args('-Csetup-args=--cross-file', '-Csetup-args={}'.format(cross_file)) - # ensure ninja and meson - for dep in [ - "ninja=={}".format(self.ninja_version), - "meson=={}".format(self.meson_version), - ]: - if dep not in self.hostpython_prerequisites: - self.hostpython_prerequisites.append(dep) - super().build_arch(arch) - - -class RustCompiledComponentsRecipe(PyProjectRecipe): - # Rust toolchain codes - # https://doc.rust-lang.org/nightly/rustc/platform-support.html - RUST_ARCH_CODES = { - "arm64-v8a": "aarch64-linux-android", - "armeabi-v7a": "armv7-linux-androideabi", - "x86_64": "x86_64-linux-android", - "x86": "i686-linux-android", - } - - call_hostpython_via_targetpython = False - - def get_recipe_env(self, arch, **kwargs): - env = super().get_recipe_env(arch, **kwargs) - - # Set rust build target - build_target = self.RUST_ARCH_CODES[arch.arch] - cargo_linker_name = "CARGO_TARGET_{}_LINKER".format( - build_target.upper().replace("-", "_") - ) - env["CARGO_BUILD_TARGET"] = build_target - env[cargo_linker_name] = join( - self.ctx.ndk.llvm_prebuilt_dir, - "bin", - "{}{}-clang".format( - # NDK's Clang format - build_target.replace("7", "7a") - if build_target.startswith("armv7") - else build_target, - self.ctx.ndk_api, - ), - ) - realpython_dir = self.ctx.python_recipe.get_build_dir(arch.arch) - - env["RUSTFLAGS"] = "-Clink-args=-L{} -L{}".format( - self.ctx.get_libs_dir(arch.arch), join(realpython_dir, "android-build") - ) - - env["PYO3_CROSS_LIB_DIR"] = realpath(glob.glob(join( - realpython_dir, "android-build", "build", - "lib.linux-*-{}/".format(self.python_major_minor_version), - ))[0]) - - info_main("Ensuring rust build toolchain") - shprint(sh.rustup, "target", "add", build_target) - - # Add host python to PATH - env["PATH"] = ("{hostpython_dir}:{old_path}").format( - hostpython_dir=Recipe.get_recipe( - "hostpython3", self.ctx - ).get_path_to_python(), - old_path=env["PATH"], - ) - return env - - def check_host_deps(self): - if not hasattr(sh, "rustup"): - error( - "`rustup` was not found on host system." - "Please install it using :" - "\n`curl https://sh.rustup.rs -sSf | sh`\n" - ) - exit(1) - - def build_arch(self, arch): - self.check_host_deps() - super().build_arch(arch) - - -class TargetPythonRecipe(Recipe): - '''Class for target python recipes. Sets ctx.python_recipe to point to - itself, so as to know later what kind of Python was built or used.''' - - def __init__(self, *args, **kwargs): - self._ctx = None - super().__init__(*args, **kwargs) - - def prebuild_arch(self, arch): - super().prebuild_arch(arch) - self.ctx.python_recipe = self - - def include_root(self, arch): - '''The root directory from which to include headers.''' - raise NotImplementedError('Not implemented in TargetPythonRecipe') - - def link_root(self): - raise NotImplementedError('Not implemented in TargetPythonRecipe') - - @property - def major_minor_version_string(self): - parsed_version = packaging.version.parse(self.version) - return f"{parsed_version.major}.{parsed_version.minor}" - - def create_python_bundle(self, dirn, arch): - """ - Create a packaged python bundle in the target directory, by - copying all the modules and standard library to the right - place. - """ - raise NotImplementedError('{} does not implement create_python_bundle'.format(self)) - - def reduce_object_file_names(self, dirn): - """Recursively renames all files named XXX.cpython-...-linux-gnu.so" - to "XXX.so", i.e. removing the erroneous architecture name - coming from the local system. - """ - py_so_files = shprint(sh.find, dirn, '-iname', '*.so') - filens = py_so_files.stdout.decode('utf-8').split('\n')[:-1] - for filen in filens: - file_dirname, file_basename = split(filen) - parts = file_basename.split('.') - if len(parts) <= 2: - continue - # PySide6 libraries end with .abi3.so - if parts[1] == "abi3": - continue - move(filen, join(file_dirname, parts[0] + '.so')) - - -def algsum(alg, filen): - '''Calculate the digest of a file. - ''' - with open(filen, 'rb') as fileh: - digest = getattr(hashlib, alg)(fileh.read()) - - return digest.hexdigest() - class FFPyPlayerRecipe(PyProjectRecipe): - version = 'v4.5.1' + version = 'v4.5.2' url = 'https://github.com/matham/ffpyplayer/archive/{version}.zip' depends = ['python3', 'sdl2', 'ffmpeg'] patches = ["setup.py.patch"] @@ -1506,7 +32,7 @@ class FFPyPlayerRecipe(PyProjectRecipe): env['LIBLINK'] = 'NOTNONE' # ffmpeg recipe enables GPL components only if ffpyplayer_codecs recipe used. - # Therefor we need to disable libpostproc if skipped. + # Therefore we need to disable libpostproc if skipped. if 'ffpyplayer_codecs' not in self.ctx.recipe_build_order: env["CONFIG_POSTPROC"] = '0' diff --git a/recipes/ffpyplayer/setup.py.patch b/recipes/ffpyplayer/setup.py.patch index 6a7d42f..35f4b69 100644 --- a/recipes/ffpyplayer/setup.py.patch +++ b/recipes/ffpyplayer/setup.py.patch @@ -1,5 +1,5 @@ ---- ffpyplayer/setup.py 2024-06-02 11:10:49.691183467 +0530 -+++ ffpyplayer.mod/setup.py 2024-06-02 11:20:16.220966873 +0530 +--- ffpyplayer/setup.py 2024-06-02 11:10:49.691183467 +0530 ++++ ffpyplayer.mod/setup.py 2024-06-02 11:20:16.220966873 +0530 @@ -27,12 +27,6 @@ # This sets whether or not Cython gets added to setup_requires. declare_cython = False diff --git a/recipes/hostpython3/__init__.py b/recipes/hostpython3/__init__.py new file mode 100644 index 0000000..b449a30 --- /dev/null +++ b/recipes/hostpython3/__init__.py @@ -0,0 +1,175 @@ +import sh +import os + +from multiprocessing import cpu_count +from pathlib import Path +from os.path import join + +from packaging.version import Version +from pythonforandroid.logger import shprint +from pythonforandroid.recipe import Recipe +from pythonforandroid.util import ( + BuildInterruptingException, + current_directory, + ensure_dir, +) +from pythonforandroid.prerequisites import OpenSSLPrerequisite + +HOSTPYTHON_VERSION_UNSET_MESSAGE = ( + 'The hostpython recipe must have set version' +) + +SETUP_DIST_NOT_FIND_MESSAGE = ( + 'Could not find Setup.dist or Setup in Python build' +) + + +class HostPython3Recipe(Recipe): + ''' + The hostpython3's recipe. + + .. versionchanged:: 2019.10.06.post0 + Refactored from deleted class ``python.HostPythonRecipe`` into here. + + .. versionchanged:: 0.6.0 + Refactored into the new class + :class:`~pythonforandroid.python.HostPythonRecipe` + ''' + + version = '3.11.5' + name = 'hostpython3' + + build_subdir = 'native-build' + '''Specify the sub build directory for the hostpython3 recipe. Defaults + to ``native-build``.''' + + url = 'https://www.python.org/ftp/python/{version}/Python-{version}.tgz' + '''The default url to download our host python recipe. This url will + change depending on the python version set in attribute :attr:`version`.''' + + patches = ['patches/pyconfig_detection.patch'] + + @property + def _exe_name(self): + ''' + Returns the name of the python executable depending on the version. + ''' + if not self.version: + raise BuildInterruptingException(HOSTPYTHON_VERSION_UNSET_MESSAGE) + return f'python{self.version.split(".")[0]}' + + @property + def python_exe(self): + '''Returns the full path of the hostpython executable.''' + return join(self.get_path_to_python(), self._exe_name) + + def get_recipe_env(self, arch=None): + env = os.environ.copy() + openssl_prereq = OpenSSLPrerequisite() + if env.get("PKG_CONFIG_PATH", ""): + env["PKG_CONFIG_PATH"] = os.pathsep.join( + [openssl_prereq.pkg_config_location, env["PKG_CONFIG_PATH"]] + ) + else: + env["PKG_CONFIG_PATH"] = openssl_prereq.pkg_config_location + return env + + def should_build(self, arch): + if Path(self.python_exe).exists(): + # no need to build, but we must set hostpython for our Context + self.ctx.hostpython = self.python_exe + return False + return True + + def get_build_container_dir(self, arch=None): + choices = self.check_recipe_choices() + dir_name = '-'.join([self.name] + choices) + return join(self.ctx.build_dir, 'other_builds', dir_name, 'desktop') + + def get_build_dir(self, arch=None): + ''' + .. note:: Unlike other recipes, the hostpython build dir doesn't + depend on the target arch + ''' + return join(self.get_build_container_dir(), self.name) + + def get_path_to_python(self): + return join(self.get_build_dir(), self.build_subdir) + + @property + def site_root(self): + return join(self.get_path_to_python(), "root") + + @property + def site_bin(self): + return join(self.site_root, self.site_dir, "bin") + + @property + def local_bin(self): + return join(self.site_root, "usr/local/bin/") + + @property + def site_dir(self): + p_version = Version(self.version) + return join( + self.site_root, + f"usr/local/lib/python{p_version.major}.{p_version.minor}/site-packages/" + ) + + def build_arch(self, arch): + env = self.get_recipe_env(arch) + + recipe_build_dir = self.get_build_dir(arch.arch) + + # Create a subdirectory to actually perform the build + build_dir = join(recipe_build_dir, self.build_subdir) + ensure_dir(build_dir) + + # Configure the build + build_configured = False + with current_directory(build_dir): + if not Path('config.status').exists(): + shprint(sh.Command(join(recipe_build_dir, 'configure')), _env=env) + build_configured = True + + with current_directory(recipe_build_dir): + # Create the Setup file. This copying from Setup.dist is + # the normal and expected procedure before Python 3.8, but + # after this the file with default options is already named "Setup" + setup_dist_location = join('Modules', 'Setup.dist') + if Path(setup_dist_location).exists(): + shprint(sh.cp, setup_dist_location, + join(build_dir, 'Modules', 'Setup')) + else: + # Check the expected file does exist + setup_location = join('Modules', 'Setup') + if not Path(setup_location).exists(): + raise BuildInterruptingException( + SETUP_DIST_NOT_FIND_MESSAGE + ) + + shprint(sh.make, '-j', str(cpu_count()), '-C', build_dir, _env=env) + + # make a copy of the python executable giving it the name we want, + # because we got different python's executable names depending on + # the fs being case-insensitive (Mac OS X, Cygwin...) or + # case-sensitive (linux)...so this way we will have an unique name + # for our hostpython, regarding the used fs + for exe_name in ['python.exe', 'python']: + exe = join(self.get_path_to_python(), exe_name) + if Path(exe).is_file(): + shprint(sh.cp, exe, self.python_exe) + break + + ensure_dir(self.site_root) + self.ctx.hostpython = self.python_exe + if build_configured: + print("RUNNING ENSUREPIP:"+self.site_root) + shprint( + sh.Command(self.python_exe), "-m", "ensurepip", "--root", self.site_root, "-U", + _env={"HOME": "/tmp"} + ) + print("RAN ENSUREPIP") + + +recipe = HostPython3Recipe() \ No newline at end of file diff --git a/recipes/hostpython3/patches/pyconfig_detection.patch b/recipes/hostpython3/patches/pyconfig_detection.patch new file mode 100644 index 0000000..a19b468 --- /dev/null +++ b/recipes/hostpython3/patches/pyconfig_detection.patch @@ -0,0 +1,13 @@ +diff -Nru Python-3.8.2/Lib/site.py Python-3.8.2-new/Lib/site.py +--- Python-3.8.2/Lib/site.py 2020-04-28 12:48:38.000000000 -0700 ++++ Python-3.8.2-new/Lib/site.py 2020-04-28 12:52:46.000000000 -0700 +@@ -487,7 +487,8 @@ + if key == 'include-system-site-packages': + system_site = value.lower() + elif key == 'home': +- sys._home = value ++ # this is breaking pyconfig.h path detection with venv ++ print('Ignoring "sys._home = value" override', file=sys.stderr) + + sys.prefix = sys.exec_prefix = site_prefix + \ No newline at end of file diff --git a/recipes/jpeg/Application.mk b/recipes/jpeg/Application.mk new file mode 100644 index 0000000..5942a03 --- /dev/null +++ b/recipes/jpeg/Application.mk @@ -0,0 +1,4 @@ +APP_OPTIM := release +APP_ABI := all # or armeabi +APP_MODULES := libjpeg +APP_ALLOW_MISSING_DEPS := true diff --git a/recipes/jpeg/__init__.py b/recipes/jpeg/__init__.py new file mode 100644 index 0000000..33a9ba4 --- /dev/null +++ b/recipes/jpeg/__init__.py @@ -0,0 +1,58 @@ +from pythonforandroid.recipe import Recipe +from pythonforandroid.logger import shprint +from pythonforandroid.util import current_directory +from os.path import join +import sh + + +class JpegRecipe(Recipe): + ''' + .. versionchanged:: 0.6.0 + rewrote recipe to be build with clang and updated libraries to latest + version of the official git repo. + ''' + name = 'jpeg' + version = '2.0.1' + url = 'https://github.com/libjpeg-turbo/libjpeg-turbo/archive/{version}.tar.gz' # noqa + built_libraries = {'libjpeg.a': '.', 'libturbojpeg.a': '.'} + # we will require this below patch to build the shared library + # patches = ['remove-version.patch'] + + def build_arch(self, arch): + build_dir = self.get_build_dir(arch.arch) + + # TODO: Fix simd/neon + with current_directory(build_dir): + env = self.get_recipe_env(arch) + toolchain_file = join(self.ctx.ndk_dir, + 'build/cmake/android.toolchain.cmake') + + shprint(sh.rm, '-rf', 'CMakeCache.txt', 'CMakeFiles/') + shprint(sh.cmake, '-G', 'Unix Makefiles', + '-DCMAKE_SYSTEM_NAME=Android', + '-DCMAKE_POSITION_INDEPENDENT_CODE=1', + '-DCMAKE_ANDROID_ARCH_ABI={arch}'.format(arch=arch.arch), + '-DCMAKE_ANDROID_NDK=' + self.ctx.ndk_dir, + '-DCMAKE_C_COMPILER={cc}'.format(cc=arch.get_clang_exe()), + '-DCMAKE_CXX_COMPILER={cc_plus}'.format( + cc_plus=arch.get_clang_exe(plus_plus=True)), + '-DCMAKE_BUILD_TYPE=Release', + '-DCMAKE_INSTALL_PREFIX=./install', + '-DCMAKE_TOOLCHAIN_FILE=' + toolchain_file, + + '-DANDROID_ABI={arch}'.format(arch=arch.arch), + '-DANDROID_ARM_NEON=ON', + '-DENABLE_NEON=ON', + # '-DREQUIRE_SIMD=1', + + # Force disable shared, with the static ones is enough + '-DENABLE_SHARED=0', + '-DENABLE_STATIC=1', + + # Fix cmake compatibility issue + '-DCMAKE_POLICY_VERSION_MINIMUM=3.5', + _env=env) + shprint(sh.make, _env=env) + + +recipe = JpegRecipe() diff --git a/recipes/jpeg/build-static.patch b/recipes/jpeg/build-static.patch new file mode 100644 index 0000000..0aa9c70 --- /dev/null +++ b/recipes/jpeg/build-static.patch @@ -0,0 +1,85 @@ +diff -Naur jpeg/Android.mk b/Android.mk +--- jpeg/Android.mk 2015-12-14 11:37:25.900190235 -0600 ++++ b/Android.mk 2015-12-14 11:41:27.532182210 -0600 +@@ -54,8 +54,7 @@ + + LOCAL_SRC_FILES:= $(libjpeg_SOURCES_DIST) + +-LOCAL_SHARED_LIBRARIES := libcutils +-LOCAL_STATIC_LIBRARIES := libsimd ++LOCAL_STATIC_LIBRARIES := libsimd libcutils + + LOCAL_C_INCLUDES := $(LOCAL_PATH) + +@@ -68,7 +67,7 @@ + + LOCAL_MODULE := libjpeg + +-include $(BUILD_SHARED_LIBRARY) ++include $(BUILD_STATIC_LIBRARY) + + ###################################################### + ### cjpeg ### +@@ -82,7 +81,7 @@ + + LOCAL_SRC_FILES:= $(cjpeg_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/android +@@ -110,7 +109,7 @@ + + LOCAL_SRC_FILES:= $(djpeg_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/android +@@ -137,7 +136,7 @@ + + LOCAL_SRC_FILES:= $(jpegtran_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/android +@@ -163,7 +162,7 @@ + + LOCAL_SRC_FILES:= $(tjunittest_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) + +@@ -189,7 +188,7 @@ + + LOCAL_SRC_FILES:= $(tjbench_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) + +@@ -215,7 +214,7 @@ + + LOCAL_SRC_FILES:= $(rdjpgcom_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) + +@@ -240,7 +239,7 @@ + + LOCAL_SRC_FILES:= $(wrjpgcom_SOURCES) + +-LOCAL_SHARED_LIBRARIES := libjpeg ++LOCAL_STATIC_LIBRARIES := libjpeg + + LOCAL_C_INCLUDES := $(LOCAL_PATH) + diff --git a/recipes/jpeg/remove-version.patch b/recipes/jpeg/remove-version.patch new file mode 100644 index 0000000..311aa33 --- /dev/null +++ b/recipes/jpeg/remove-version.patch @@ -0,0 +1,12 @@ +--- jpeg/CMakeLists.txt.orig 2018-11-12 20:20:28.000000000 +0100 ++++ jpeg/CMakeLists.txt 2018-12-14 12:43:45.338704504 +0100 +@@ -573,6 +573,9 @@ + add_library(turbojpeg SHARED ${TURBOJPEG_SOURCES}) + set_property(TARGET turbojpeg PROPERTY COMPILE_FLAGS + "-DBMP_SUPPORTED -DPPM_SUPPORTED") ++ set_property(TARGET jpeg PROPERTY NO_SONAME 1) ++ set_property(TARGET turbojpeg PROPERTY NO_SONAME 1) ++ set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "") + if(WIN32) + set_target_properties(turbojpeg PROPERTIES DEFINE_SYMBOL DLLDEFINE) + endif() diff --git a/recipes/numpy/__init__.py b/recipes/numpy/__init__.py deleted file mode 100644 index 55a0279..0000000 --- a/recipes/numpy/__init__.py +++ /dev/null @@ -1,75 +0,0 @@ -from pythonforandroid.recipe import CompiledComponentsPythonRecipe -from pythonforandroid.logger import shprint, info -from pythonforandroid.util import current_directory -from multiprocessing import cpu_count -from os.path import join -import glob -import sh -import shutil - - -class NumpyRecipe(CompiledComponentsPythonRecipe): - - version = '1.22.3' - url = 'https://pypi.python.org/packages/source/n/numpy/numpy-{version}.zip' - site_packages_name = 'numpy' - depends = ['setuptools', 'cython'] - install_in_hostpython = True - call_hostpython_via_targetpython = False - - patches = [ - join("patches", "remove-default-paths.patch"), - join("patches", "add_libm_explicitly_to_build.patch"), - join("patches", "ranlib.patch"), - ] - - def get_recipe_env(self, arch=None, with_flags_in_cc=True): - env = super().get_recipe_env(arch, with_flags_in_cc) - - # _PYTHON_HOST_PLATFORM declares that we're cross-compiling - # and avoids issues when building on macOS for Android targets. - env["_PYTHON_HOST_PLATFORM"] = arch.command_prefix - - # NPY_DISABLE_SVML=1 allows numpy to build for non-AVX512 CPUs - # See: https://github.com/numpy/numpy/issues/21196 - env["NPY_DISABLE_SVML"] = "1" - - return env - - def _build_compiled_components(self, arch): - info('Building compiled components in {}'.format(self.name)) - - env = self.get_recipe_env(arch) - with current_directory(self.get_build_dir(arch.arch)): - hostpython = sh.Command(self.hostpython_location) - shprint(hostpython, 'setup.py', self.build_cmd, '-v', - _env=env, *self.setup_extra_args) - build_dir = glob.glob('build/lib.*')[0] - shprint(sh.find, build_dir, '-name', '"*.o"', '-exec', - env['STRIP'], '{}', ';', _env=env) - - def _rebuild_compiled_components(self, arch, env): - info('Rebuilding compiled components in {}'.format(self.name)) - - hostpython = sh.Command(self.real_hostpython_location) - shprint(hostpython, 'setup.py', 'clean', '--all', '--force', _env=env) - shprint(hostpython, 'setup.py', self.build_cmd, '-v', _env=env, - *self.setup_extra_args) - - def build_compiled_components(self, arch): - self.setup_extra_args = ['-j', str(cpu_count())] - self._build_compiled_components(arch) - self.setup_extra_args = [] - - def rebuild_compiled_components(self, arch, env): - self.setup_extra_args = ['-j', str(cpu_count())] - self._rebuild_compiled_components(arch, env) - self.setup_extra_args = [] - - def get_hostrecipe_env(self, arch): - env = super().get_hostrecipe_env(arch) - env['RANLIB'] = shutil.which('ranlib') - return env - - -recipe = NumpyRecipe() diff --git a/recipes/numpy/patches/add_libm_explicitly_to_build.patch b/recipes/numpy/patches/add_libm_explicitly_to_build.patch deleted file mode 100644 index f9ba9e9..0000000 --- a/recipes/numpy/patches/add_libm_explicitly_to_build.patch +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/numpy/linalg/setup.py b/numpy/linalg/setup.py -index 66c07c9..d34bd93 100644 ---- a/numpy/linalg/setup.py -+++ b/numpy/linalg/setup.py -@@ -46,6 +46,7 @@ def configuration(parent_package='', top_path=None): - sources=['lapack_litemodule.c', get_lapack_lite_sources], - depends=['lapack_lite/f2c.h'], - extra_info=lapack_info, -+ libraries=['m'], - ) - - # umath_linalg module -@@ -54,7 +54,7 @@ def configuration(parent_package='', top_path=None): - sources=['umath_linalg.c.src', get_lapack_lite_sources], - depends=['lapack_lite/f2c.h'], - extra_info=lapack_info, -- libraries=['npymath'], -+ libraries=['npymath', 'm'], - ) - return config diff --git a/recipes/numpy/patches/ranlib.patch b/recipes/numpy/patches/ranlib.patch deleted file mode 100644 index c0b5dad..0000000 --- a/recipes/numpy/patches/ranlib.patch +++ /dev/null @@ -1,11 +0,0 @@ -diff -Naur numpy.orig/numpy/distutils/unixccompiler.py numpy/numpy/distutils/unixccompiler.py ---- numpy.orig/numpy/distutils/unixccompiler.py 2022-05-28 10:22:10.000000000 +0200 -+++ numpy/numpy/distutils/unixccompiler.py 2022-05-28 10:22:24.000000000 +0200 -@@ -124,6 +124,7 @@ - # platform intelligence here to skip ranlib if it's not - # needed -- or maybe Python's configure script took care of - # it for us, hence the check for leading colon. -+ self.ranlib = [os.environ.get('RANLIB')] - if self.ranlib: - display = '%s:@ %s' % (os.path.basename(self.ranlib[0]), - output_filename) diff --git a/recipes/numpy/patches/remove-default-paths.patch b/recipes/numpy/patches/remove-default-paths.patch deleted file mode 100644 index 3581f0f..0000000 --- a/recipes/numpy/patches/remove-default-paths.patch +++ /dev/null @@ -1,28 +0,0 @@ -diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py -index fc7018a..7b514bc 100644 ---- a/numpy/distutils/system_info.py -+++ b/numpy/distutils/system_info.py -@@ -340,10 +340,10 @@ if os.path.join(sys.prefix, 'lib') not in default_lib_dirs: - default_include_dirs.append(os.path.join(sys.prefix, 'include')) - default_src_dirs.append(os.path.join(sys.prefix, 'src')) - --default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)] --default_runtime_dirs = [_m for _m in default_runtime_dirs if os.path.isdir(_m)] --default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)] --default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)] -+default_lib_dirs = [] #[_m for _m in default_lib_dirs if os.path.isdir(_m)] -+default_runtime_dirs =[] # [_m for _m in default_runtime_dirs if os.path.isdir(_m)] -+default_include_dirs =[] # [_m for _m in default_include_dirs if os.path.isdir(_m)] -+default_src_dirs =[] # [_m for _m in default_src_dirs if os.path.isdir(_m)] - - so_ext = get_shared_lib_extension() - -@@ -814,7 +814,7 @@ class system_info(object): - path = self.get_paths(self.section, key) - if path == ['']: - path = [] -- return path -+ return [] - - def get_include_dirs(self, key='include_dirs'): - return self.get_paths(self.section, key) diff --git a/recipes/pycodec2/__init__.py b/recipes/pycodec2/__init__.py index 6ad05bd..5b71a80 100644 --- a/recipes/pycodec2/__init__.py +++ b/recipes/pycodec2/__init__.py @@ -5,7 +5,7 @@ import sh # class PyCodec2Recipe(IncludedFilesBehaviour, CythonRecipe): class PyCodec2Recipe(CythonRecipe): - url = "https://github.com/markqvist/pycodec2/archive/refs/heads/main.zip" + url = "https://github.com/markqvist/pycodec2/archive/438ee4f2f3ee30635a34caddf520cfaccdbbc646.zip" # src_filename = "../../../pycodec2" depends = ["setuptools", "numpy", "Cython", "codec2"] call_hostpython_via_targetpython = False diff --git a/recipes/pyjnius/__init__.py b/recipes/pyjnius/__init__.py new file mode 100644 index 0000000..86d8803 --- /dev/null +++ b/recipes/pyjnius/__init__.py @@ -0,0 +1,44 @@ +from pythonforandroid.recipe import PyProjectRecipe +from pythonforandroid.toolchain import shprint, current_directory, info +from pythonforandroid.patching import will_build +import sh +from os.path import join + + +class PyjniusRecipe(PyProjectRecipe): + version = '1.7.0' + url = 'https://github.com/kivy/pyjnius/archive/{version}.zip' + name = 'pyjnius' + depends = [('genericndkbuild', 'sdl2', 'sdl3'), 'six'] + site_packages_name = 'jnius' + hostpython_prerequisites = ["Cython<3.2"] + patches = [ + "use_cython.patch", + ('genericndkbuild_jnienv_getter.patch', will_build('genericndkbuild')), + ('sdl3_jnienv_getter.patch', will_build('sdl3')), + ] + + def get_recipe_env(self, arch, **kwargs): + env = super().get_recipe_env(arch, **kwargs) + + # Taken from CythonRecipe + env['LDFLAGS'] = env['LDFLAGS'] + ' -L{} '.format( + self.ctx.get_libs_dir(arch.arch) + + ' -L{} '.format(self.ctx.libs_dir) + + ' -L{}'.format(join(self.ctx.bootstrap.build_dir, 'obj', 'local', + arch.arch))) + env['LDSHARED'] = env['CC'] + ' -shared' + env['LIBLINK'] = 'NOTNONE' + + # NDKPLATFORM is our switch for detecting Android platform, so can't be None + env['NDKPLATFORM'] = "NOTNONE" + return env + + def postbuild_arch(self, arch): + super().postbuild_arch(arch) + info('Copying pyjnius java class to classes build dir') + with current_directory(self.get_build_dir(arch.arch)): + shprint(sh.cp, '-a', join('jnius', 'src', 'org'), self.ctx.javaclass_dir) + + +recipe = PyjniusRecipe() diff --git a/recipes/pyjnius/genericndkbuild_jnienv_getter.patch b/recipes/pyjnius/genericndkbuild_jnienv_getter.patch new file mode 100644 index 0000000..fcd5387 --- /dev/null +++ b/recipes/pyjnius/genericndkbuild_jnienv_getter.patch @@ -0,0 +1,24 @@ +diff -Naur pyjnius.orig/jnius/env.py pyjnius/jnius/env.py +--- pyjnius.orig/jnius/env.py 2022-05-28 11:16:02.000000000 +0200 ++++ pyjnius/jnius/env.py 2022-05-28 11:18:30.000000000 +0200 +@@ -268,7 +268,7 @@ + + class AndroidJavaLocation(UnixJavaLocation): + def get_libraries(self): +- return ['SDL2', 'log'] ++ return ['main', 'log'] + + def get_include_dirs(self): + # When cross-compiling for Android, we should not use the include dirs +diff -Naur pyjnius.orig/jnius/jnius_jvm_android.pxi pyjnius/jnius/jnius_jvm_android.pxi +--- pyjnius.orig/jnius/jnius_jvm_android.pxi 2022-05-28 11:16:02.000000000 +0200 ++++ pyjnius/jnius/jnius_jvm_android.pxi 2022-05-28 11:17:17.000000000 +0200 +@@ -1,6 +1,6 @@ + # on android, rely on SDL to get the JNI env +-cdef extern JNIEnv *SDL_AndroidGetJNIEnv() ++cdef extern JNIEnv *WebView_AndroidGetJNIEnv() + + + cdef JNIEnv *get_platform_jnienv() except NULL: +- return SDL_AndroidGetJNIEnv() ++ return WebView_AndroidGetJNIEnv() diff --git a/recipes/pyjnius/sdl3_jnienv_getter.patch b/recipes/pyjnius/sdl3_jnienv_getter.patch new file mode 100644 index 0000000..d91da76 --- /dev/null +++ b/recipes/pyjnius/sdl3_jnienv_getter.patch @@ -0,0 +1,24 @@ +diff -Naur pyjnius.orig/jnius/env.py pyjnius/jnius/env.py +--- pyjnius.orig/jnius/env.py 2022-05-28 11:16:02.000000000 +0200 ++++ pyjnius/jnius/env.py 2022-05-28 11:18:30.000000000 +0200 +@@ -268,7 +268,7 @@ + + class AndroidJavaLocation(UnixJavaLocation): + def get_libraries(self): +- return ['SDL2', 'log'] ++ return ['SDL3', 'log'] + + def get_include_dirs(self): + # When cross-compiling for Android, we should not use the include dirs +diff -Naur pyjnius.orig/jnius/jnius_jvm_android.pxi pyjnius/jnius/jnius_jvm_android.pxi +--- pyjnius.orig/jnius/jnius_jvm_android.pxi 2022-05-28 11:16:02.000000000 +0200 ++++ pyjnius/jnius/jnius_jvm_android.pxi 2022-05-28 11:17:17.000000000 +0200 +@@ -1,6 +1,6 @@ + # on android, rely on SDL to get the JNI env +-cdef extern JNIEnv *SDL_AndroidGetJNIEnv() ++cdef extern JNIEnv *SDL_GetAndroidJNIEnv() + + + cdef JNIEnv *get_platform_jnienv() except NULL: +- return SDL_AndroidGetJNIEnv() ++ return SDL_GetAndroidJNIEnv() diff --git a/recipes/pyjnius/use_cython.patch b/recipes/pyjnius/use_cython.patch new file mode 100644 index 0000000..59265e9 --- /dev/null +++ b/recipes/pyjnius/use_cython.patch @@ -0,0 +1,13 @@ +--- pyjnius-1.6.1/setup.py 2023-11-05 21:07:43.000000000 +0530 ++++ pyjnius-1.6.1.mod/setup.py 2025-03-01 14:47:11.964847337 +0530 +@@ -59,10 +59,6 @@ + if NDKPLATFORM is not None and getenv('LIBLINK'): + PLATFORM = 'android' + +-# detect platform +-if PLATFORM == 'android': +- PYX_FILES = [fn[:-3] + 'c' for fn in PYX_FILES] +- + JAVA=get_java_setup(PLATFORM) + + assert JAVA.is_jdk(), "You need a JDK, we only found a JRE. Try setting JAVA_HOME" diff --git a/recipes/python3/__init__.py b/recipes/python3/__init__.py new file mode 100644 index 0000000..2a2e07d --- /dev/null +++ b/recipes/python3/__init__.py @@ -0,0 +1,445 @@ +import glob +import sh +import subprocess + +from os import environ, utime +from os.path import dirname, exists, join +from pathlib import Path +import shutil + +from pythonforandroid.logger import info, warning, shprint +from pythonforandroid.patching import version_starts_with +from pythonforandroid.recipe import Recipe, TargetPythonRecipe +from pythonforandroid.util import ( + current_directory, + ensure_dir, + walk_valid_filens, + BuildInterruptingException, +) + +NDK_API_LOWER_THAN_SUPPORTED_MESSAGE = ( + 'Target ndk-api is {ndk_api}, ' + 'but the python3 recipe supports only {min_ndk_api}+' +) + + +class Python3Recipe(TargetPythonRecipe): + ''' + The python3's recipe + ^^^^^^^^^^^^^^^^^^^^ + + The python 3 recipe can be built with some extra python modules, but to do + so, we need some libraries. By default, we ship the python3 recipe with + some common libraries, defined in ``depends``. We also support some optional + libraries, which are less common that the ones defined in ``depends``, so + we added them as optional dependencies (``opt_depends``). + + Below you have a relationship between the python modules and the recipe + libraries:: + + - _ctypes: you must add the recipe for ``libffi``. + - _sqlite3: you must add the recipe for ``sqlite3``. + - _ssl: you must add the recipe for ``openssl``. + - _bz2: you must add the recipe for ``libbz2`` (optional). + - _lzma: you must add the recipe for ``liblzma`` (optional). + + .. note:: This recipe can be built only against API 21+. + + .. versionchanged:: 2019.10.06.post0 + - Refactored from deleted class ``python.GuestPythonRecipe`` into here + - Added optional dependencies: :mod:`~pythonforandroid.recipes.libbz2` + and :mod:`~pythonforandroid.recipes.liblzma` + + .. versionchanged:: 0.6.0 + Refactored into class + :class:`~pythonforandroid.python.GuestPythonRecipe` + ''' + + version = '3.11.5' + url = 'https://www.python.org/ftp/python/{version}/Python-{version}.tgz' + name = 'python3' + + patches = [ + 'patches/pyconfig_detection.patch', + 'patches/reproducible-buildinfo.diff', + + # Python 3.7.1 + ('patches/py3.7.1_fix-ctypes-util-find-library.patch', version_starts_with("3.7")), + ('patches/py3.7.1_fix-zlib-version.patch', version_starts_with("3.7")), + + # Python 3.8.1 & 3.9.X + ('patches/py3.8.1.patch', version_starts_with("3.8")), + ('patches/py3.8.1.patch', version_starts_with("3.9")), + ('patches/py3.8.1.patch', version_starts_with("3.10")), + ('patches/cpython-311-ctypes-find-library.patch', version_starts_with("3.11")), + ] + + if shutil.which('lld') is not None: + patches += [ + ("patches/py3.7.1_fix_cortex_a8.patch", version_starts_with("3.7")), + ("patches/py3.8.1_fix_cortex_a8.patch", version_starts_with("3.8")), + ("patches/py3.8.1_fix_cortex_a8.patch", version_starts_with("3.9")), + ("patches/py3.8.1_fix_cortex_a8.patch", version_starts_with("3.10")), + ("patches/py3.8.1_fix_cortex_a8.patch", version_starts_with("3.11")), + ] + + depends = ['hostpython3', 'sqlite3', 'openssl', 'libffi'] + # those optional depends allow us to build python compression modules: + # - _bz2.so + # - _lzma.so + opt_depends = ['libbz2', 'liblzma'] + '''The optional libraries which we would like to get our python linked''' + + configure_args = ( + '--host={android_host}', + '--build={android_build}', + '--enable-shared', + '--enable-ipv6', + 'ac_cv_file__dev_ptmx=yes', + 'ac_cv_file__dev_ptc=no', + '--without-ensurepip', + 'ac_cv_little_endian_double=yes', + 'ac_cv_header_sys_eventfd_h=no', + '--prefix={prefix}', + '--exec-prefix={exec_prefix}', + '--enable-loadable-sqlite-extensions' + ) + + if version_starts_with("3.11"): + configure_args += ('--with-build-python={python_host_bin}',) + + '''The configure arguments needed to build the python recipe. Those are + used in method :meth:`build_arch` (if not overwritten like python3's + recipe does). + ''' + + MIN_NDK_API = 21 + '''Sets the minimal ndk api number needed to use the recipe. + + .. warning:: This recipe can be built only against API 21+, so it means + that any class which inherits from class:`GuestPythonRecipe` will have + this limitation. + ''' + + stdlib_dir_blacklist = { + '__pycache__', + 'test', + 'tests', + 'lib2to3', + 'ensurepip', + 'idlelib', + 'tkinter', + } + '''The directories that we want to omit for our python bundle''' + + stdlib_filen_blacklist = [ + '*.py', + '*.exe', + '*.whl', + ] + '''The file extensions that we want to blacklist for our python bundle''' + + site_packages_dir_blacklist = { + '__pycache__', + 'tests' + } + '''The directories from site packages dir that we don't want to be included + in our python bundle.''' + + site_packages_filen_blacklist = [ + '*.py' + ] + '''The file extensions from site packages dir that we don't want to be + included in our python bundle.''' + + compiled_extension = '.pyc' + '''the default extension for compiled python files. + + .. note:: the default extension for compiled python files has been .pyo for + python 2.x-3.4 but as of Python 3.5, the .pyo filename extension is no + longer used and has been removed in favour of extension .pyc + ''' + + def __init__(self, *args, **kwargs): + self._ctx = None + super().__init__(*args, **kwargs) + + @property + def _libpython(self): + '''return the python's library name (with extension)''' + return 'libpython{link_version}.so'.format( + link_version=self.link_version + ) + + @property + def link_version(self): + '''return the python's library link version e.g. 3.7m, 3.8''' + major, minor = self.major_minor_version_string.split('.') + flags = '' + if major == '3' and int(minor) < 8: + flags += 'm' + return '{major}.{minor}{flags}'.format( + major=major, + minor=minor, + flags=flags + ) + + def include_root(self, arch_name): + return join(self.get_build_dir(arch_name), 'Include') + + def link_root(self, arch_name): + return join(self.get_build_dir(arch_name), 'android-build') + + def should_build(self, arch): + return not Path(self.link_root(arch.arch), self._libpython).is_file() + + def prebuild_arch(self, arch): + super().prebuild_arch(arch) + self.ctx.python_recipe = self + + def get_recipe_env(self, arch=None, with_flags_in_cc=True): + env = super().get_recipe_env(arch) + env['HOSTARCH'] = arch.command_prefix + + env['CC'] = arch.get_clang_exe(with_target=True) + + env['PATH'] = ( + '{hostpython_dir}:{old_path}').format( + hostpython_dir=self.get_recipe( + 'host' + self.name, self.ctx).get_path_to_python(), + old_path=env['PATH']) + + env['CFLAGS'] = ' '.join( + [ + '-fPIC', + '-DANDROID' + ] + ) + + env['LDFLAGS'] = env.get('LDFLAGS', '') + if shutil.which('lld') is not None: + # Note: The -L. is to fix a bug in python 3.7. + # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=234409 + env['LDFLAGS'] += ' -L. -fuse-ld=lld' + else: + warning('lld not found, linking without it. ' + 'Consider installing lld if linker errors occur.') + + return env + + def set_libs_flags(self, env, arch): + '''Takes care to properly link libraries with python depending on our + requirements and the attribute :attr:`opt_depends`. + ''' + def add_flags(include_flags, link_dirs, link_libs): + env['CPPFLAGS'] = env.get('CPPFLAGS', '') + include_flags + env['LDFLAGS'] = env.get('LDFLAGS', '') + link_dirs + env['LIBS'] = env.get('LIBS', '') + link_libs + + if 'sqlite3' in self.ctx.recipe_build_order: + info('Activating flags for sqlite3') + recipe = Recipe.get_recipe('sqlite3', self.ctx) + add_flags(' -I' + recipe.get_build_dir(arch.arch), + ' -L' + recipe.get_lib_dir(arch), ' -lsqlite3') + + if 'libffi' in self.ctx.recipe_build_order: + info('Activating flags for libffi') + recipe = Recipe.get_recipe('libffi', self.ctx) + # In order to force the correct linkage for our libffi library, we + # set the following variable to point where is our libffi.pc file, + # because the python build system uses pkg-config to configure it. + env['PKG_CONFIG_PATH'] = recipe.get_build_dir(arch.arch) + add_flags(' -I' + ' -I'.join(recipe.get_include_dirs(arch)), + ' -L' + join(recipe.get_build_dir(arch.arch), '.libs'), + ' -lffi') + + if 'openssl' in self.ctx.recipe_build_order: + info('Activating flags for openssl') + recipe = Recipe.get_recipe('openssl', self.ctx) + self.configure_args += \ + ('--with-openssl=' + recipe.get_build_dir(arch.arch),) + add_flags(recipe.include_flags(arch), + recipe.link_dirs_flags(arch), recipe.link_libs_flags()) + + for library_name in {'libbz2', 'liblzma'}: + if library_name in self.ctx.recipe_build_order: + info(f'Activating flags for {library_name}') + recipe = Recipe.get_recipe(library_name, self.ctx) + add_flags(recipe.get_library_includes(arch), + recipe.get_library_ldflags(arch), + recipe.get_library_libs_flag()) + + # python build system contains hardcoded zlib version which prevents + # the build of zlib module, here we search for android's zlib version + # and sets the right flags, so python can be build with android's zlib + info("Activating flags for android's zlib") + zlib_lib_path = arch.ndk_lib_dir_versioned + zlib_includes = self.ctx.ndk.sysroot_include_dir + zlib_h = join(zlib_includes, 'zlib.h') + try: + with open(zlib_h) as fileh: + zlib_data = fileh.read() + except IOError: + raise BuildInterruptingException( + "Could not determine android's zlib version, no zlib.h ({}) in" + " the NDK dir includes".format(zlib_h) + ) + for line in zlib_data.split('\n'): + if line.startswith('#define ZLIB_VERSION '): + break + else: + raise BuildInterruptingException( + 'Could not parse zlib.h...so we cannot find zlib version,' + 'required by python build,' + ) + env['ZLIB_VERSION'] = line.replace('#define ZLIB_VERSION ', '') + add_flags(' -I' + zlib_includes, ' -L' + zlib_lib_path, ' -lz') + + return env + + def build_arch(self, arch): + if self.ctx.ndk_api < self.MIN_NDK_API: + raise BuildInterruptingException( + NDK_API_LOWER_THAN_SUPPORTED_MESSAGE.format( + ndk_api=self.ctx.ndk_api, min_ndk_api=self.MIN_NDK_API + ), + ) + + recipe_build_dir = self.get_build_dir(arch.arch) + + # Create a subdirectory to actually perform the build + build_dir = join(recipe_build_dir, 'android-build') + ensure_dir(build_dir) + + # TODO: Get these dynamically, like bpo-30386 does + sys_prefix = '/usr/local' + sys_exec_prefix = '/usr/local' + + env = self.get_recipe_env(arch) + env = self.set_libs_flags(env, arch) + + android_build = sh.Command( + join(recipe_build_dir, + 'config.guess'))().strip() + + with current_directory(build_dir): + if not exists('config.status'): + shprint( + sh.Command(join(recipe_build_dir, 'configure')), + *(' '.join(self.configure_args).format( + android_host=env['HOSTARCH'], + android_build=android_build, + python_host_bin=join(self.get_recipe( + 'host' + self.name, self.ctx + ).get_path_to_python(), "python3"), + prefix=sys_prefix, + exec_prefix=sys_exec_prefix)).split(' '), + _env=env) + + # Python build does not seem to play well with make -j option from Python 3.11 and onwards + # Before losing some time, please check issue + # https://github.com/python/cpython/issues/101295 , as the root cause looks similar + shprint( + sh.make, + 'all', + 'INSTSONAME={lib_name}'.format(lib_name=self._libpython), + _env=env + ) + + # TODO: Look into passing the path to pyconfig.h in a + # better way, although this is probably acceptable + sh.cp('pyconfig.h', join(recipe_build_dir, 'Include')) + + def compile_python_files(self, dir): + ''' + Compile the python files (recursively) for the python files inside + a given folder. + + .. note:: python2 compiles the files into extension .pyo, but in + python3, and as of Python 3.5, the .pyo filename extension is no + longer used...uses .pyc (https://www.python.org/dev/peps/pep-0488) + ''' + args = [self.ctx.hostpython] + args += ['-OO', '-m', 'compileall', '-b', '-f', dir] + subprocess.call(args) + + def create_python_bundle(self, dirn, arch): + """ + Create a packaged python bundle in the target directory, by + copying all the modules and standard library to the right + place. + """ + # Todo: find a better way to find the build libs folder + modules_build_dir = join( + self.get_build_dir(arch.arch), + 'android-build', + 'build', + 'lib.linux{}-{}-{}'.format( + '2' if self.version[0] == '2' else '', + arch.command_prefix.split('-')[0], + self.major_minor_version_string + )) + + # Compile to *.pyc the python modules + self.compile_python_files(modules_build_dir) + # Compile to *.pyc the standard python library + self.compile_python_files(join(self.get_build_dir(arch.arch), 'Lib')) + # Compile to *.pyc the other python packages (site-packages) + self.compile_python_files(self.ctx.get_python_install_dir(arch.arch)) + + # Bundle compiled python modules to a folder + modules_dir = join(dirn, 'modules') + c_ext = self.compiled_extension + ensure_dir(modules_dir) + module_filens = (glob.glob(join(modules_build_dir, '*.so')) + + glob.glob(join(modules_build_dir, '*' + c_ext))) + info("Copy {} files into the bundle".format(len(module_filens))) + for filen in module_filens: + info(" - copy {}".format(filen)) + shutil.copy2(filen, modules_dir) + + # zip up the standard library + stdlib_zip = join(dirn, 'stdlib.zip') + with current_directory(join(self.get_build_dir(arch.arch), 'Lib')): + stdlib_filens = list(walk_valid_filens( + '.', self.stdlib_dir_blacklist, self.stdlib_filen_blacklist)) + if 'SOURCE_DATE_EPOCH' in environ: + # for reproducible builds + stdlib_filens.sort() + timestamp = int(environ['SOURCE_DATE_EPOCH']) + for filen in stdlib_filens: + utime(filen, (timestamp, timestamp)) + info("Zip {} files into the bundle".format(len(stdlib_filens))) + shprint(sh.zip, '-X', stdlib_zip, *stdlib_filens) + + # copy the site-packages into place + ensure_dir(join(dirn, 'site-packages')) + ensure_dir(self.ctx.get_python_install_dir(arch.arch)) + # TODO: Improve the API around walking and copying the files + with current_directory(self.ctx.get_python_install_dir(arch.arch)): + filens = list(walk_valid_filens( + '.', self.site_packages_dir_blacklist, + self.site_packages_filen_blacklist)) + info("Copy {} files into the site-packages".format(len(filens))) + for filen in filens: + info(" - copy {}".format(filen)) + ensure_dir(join(dirn, 'site-packages', dirname(filen))) + shutil.copy2(filen, join(dirn, 'site-packages', filen)) + + # copy the python .so files into place + python_build_dir = join(self.get_build_dir(arch.arch), + 'android-build') + python_lib_name = 'libpython' + self.link_version + shprint( + sh.cp, + join(python_build_dir, python_lib_name + '.so'), + join(self.ctx.bootstrap.dist_dir, 'libs', arch.arch) + ) + + info('Renaming .so files to reflect cross-compile') + self.reduce_object_file_names(join(dirn, 'site-packages')) + + return join(dirn, 'site-packages') + + +recipe = Python3Recipe() \ No newline at end of file diff --git a/recipes/python3/patches/cpython-311-ctypes-find-library.patch b/recipes/python3/patches/cpython-311-ctypes-find-library.patch new file mode 100644 index 0000000..7864d57 --- /dev/null +++ b/recipes/python3/patches/cpython-311-ctypes-find-library.patch @@ -0,0 +1,19 @@ +--- Python-3.11.5/Lib/ctypes/util.py 2023-08-24 17:39:18.000000000 +0530 ++++ Python-3.11.5.mod/Lib/ctypes/util.py 2023-11-18 22:12:17.356160615 +0530 +@@ -4,7 +4,15 @@ + import sys + + # find_library(name) returns the pathname of a library, or None. +-if os.name == "nt": ++ ++# This patch overrides the find_library to look in the right places on ++# Android ++if True: ++ from android._ctypes_library_finder import find_library as _find_lib ++ def find_library(name): ++ return _find_lib(name) ++ ++elif os.name == "nt": + + def _get_build_version(): + """Return the version of MSVC that was used to build Python. diff --git a/recipes/python3/patches/py3.7.1_fix-ctypes-util-find-library.patch b/recipes/python3/patches/py3.7.1_fix-ctypes-util-find-library.patch new file mode 100644 index 0000000..494270d --- /dev/null +++ b/recipes/python3/patches/py3.7.1_fix-ctypes-util-find-library.patch @@ -0,0 +1,15 @@ +diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py +--- a/Lib/ctypes/util.py ++++ b/Lib/ctypes/util.py +@@ -67,4 +67,11 @@ + return fname + return None + ++# This patch overrides the find_library to look in the right places on ++# Android ++if True: ++ from android._ctypes_library_finder import find_library as _find_lib ++ def find_library(name): ++ return _find_lib(name) ++ + elif os.name == "posix" and sys.platform == "darwin": diff --git a/recipes/python3/patches/py3.7.1_fix-zlib-version.patch b/recipes/python3/patches/py3.7.1_fix-zlib-version.patch new file mode 100644 index 0000000..0dbffae --- /dev/null +++ b/recipes/python3/patches/py3.7.1_fix-zlib-version.patch @@ -0,0 +1,12 @@ +--- Python-3.7.1/setup.py.orig 2018-10-20 08:04:19.000000000 +0200 ++++ Python-3.7.1/setup.py 2019-02-17 00:24:30.715904412 +0100 +@@ -1410,7 +1410,8 @@ class PyBuildExt(build_ext): + if zlib_inc is not None: + zlib_h = zlib_inc[0] + '/zlib.h' + version = '"0.0.0"' +- version_req = '"1.1.3"' ++ version_req = '"{}"'.format( ++ os.environ.get('ZLIB_VERSION', '1.1.3')) + if host_platform == 'darwin' and is_macosx_sdk_path(zlib_h): + zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:]) + with open(zlib_h) as fp: diff --git a/recipes/python3/patches/py3.7.1_fix_cortex_a8.patch b/recipes/python3/patches/py3.7.1_fix_cortex_a8.patch new file mode 100644 index 0000000..5ddc3c4 --- /dev/null +++ b/recipes/python3/patches/py3.7.1_fix_cortex_a8.patch @@ -0,0 +1,14 @@ +This patch removes --fix-cortex-a8 from the linker flags in order to support linking +with lld, as lld does not support this flag (https://github.com/android-ndk/ndk/issues/766). +diff --git a/configure b/configure +--- a/configure ++++ b/configure +@@ -5671,7 +5671,7 @@ $as_echo_n "checking for the Android arm ABI... " >&6; } + $as_echo "$_arm_arch" >&6; } + if test "$_arm_arch" = 7; then + BASECFLAGS="${BASECFLAGS} -mfloat-abi=softfp -mfpu=vfpv3-d16" +- LDFLAGS="${LDFLAGS} -march=armv7-a -Wl,--fix-cortex-a8" ++ LDFLAGS="${LDFLAGS} -march=armv7-a" + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not Android" >&5 \ No newline at end of file diff --git a/recipes/python3/patches/py3.8.1.patch b/recipes/python3/patches/py3.8.1.patch new file mode 100644 index 0000000..6018805 --- /dev/null +++ b/recipes/python3/patches/py3.8.1.patch @@ -0,0 +1,42 @@ +diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py +index 97973bc..053c231 100644 +--- a/Lib/ctypes/util.py ++++ b/Lib/ctypes/util.py +@@ -67,6 +67,13 @@ if os.name == "nt": + return fname + return None + ++# This patch overrides the find_library to look in the right places on ++# Android ++if True: ++ from android._ctypes_library_finder import find_library as _find_lib ++ def find_library(name): ++ return _find_lib(name) ++ + elif os.name == "posix" and sys.platform == "darwin": + from ctypes.macholib.dyld import dyld_find as _dyld_find + def find_library(name): +diff --git a/configure b/configure +index 0914e24..dd00812 100755 +--- a/configure ++++ b/configure +@@ -18673,4 +18673,3 @@ if test "$Py_OPT" = 'false' -a "$Py_DEBUG" != 'true'; then + echo "" >&6 + echo "" >&6 + fi +- +diff --git a/setup.py b/setup.py +index 20d7f35..af15cc2 100644 +--- a/setup.py ++++ b/setup.py +@@ -1501,7 +1501,9 @@ class PyBuildExt(build_ext): + if zlib_inc is not None: + zlib_h = zlib_inc[0] + '/zlib.h' + version = '"0.0.0"' +- version_req = '"1.1.3"' ++ # version_req = '"1.1.3"' ++ version_req = '"{}"'.format( ++ os.environ.get('ZLIB_VERSION', '1.1.3')) + if MACOS and is_macosx_sdk_path(zlib_h): + zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:]) + with open(zlib_h) as fp: diff --git a/recipes/python3/patches/py3.8.1_fix_cortex_a8.patch b/recipes/python3/patches/py3.8.1_fix_cortex_a8.patch new file mode 100644 index 0000000..92a41b5 --- /dev/null +++ b/recipes/python3/patches/py3.8.1_fix_cortex_a8.patch @@ -0,0 +1,15 @@ +This patch removes --fix-cortex-a8 from the linker flags in order to support linking +with lld, as lld does not support this flag (https://github.com/android-ndk/ndk/issues/766). +diff --git a/configure b/configure +index 0914e24..7517168 100755 +--- a/configure ++++ b/configure +@@ -5642,7 +5642,7 @@ $as_echo_n "checking for the Android arm ABI... " >&6; } + $as_echo "$_arm_arch" >&6; } + if test "$_arm_arch" = 7; then + BASECFLAGS="${BASECFLAGS} -mfloat-abi=softfp -mfpu=vfpv3-d16" +- LDFLAGS="${LDFLAGS} -march=armv7-a -Wl,--fix-cortex-a8" ++ LDFLAGS="${LDFLAGS} -march=armv7-a" + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not Android" >&5 diff --git a/recipes/python3/patches/pyconfig_detection.patch b/recipes/python3/patches/pyconfig_detection.patch new file mode 100644 index 0000000..087ab58 --- /dev/null +++ b/recipes/python3/patches/pyconfig_detection.patch @@ -0,0 +1,13 @@ +diff -Nru Python-3.8.2/Lib/site.py Python-3.8.2-new/Lib/site.py +--- Python-3.8.2/Lib/site.py 2020-04-28 12:48:38.000000000 -0700 ++++ Python-3.8.2-new/Lib/site.py 2020-04-28 12:52:46.000000000 -0700 +@@ -487,7 +487,8 @@ + if key == 'include-system-site-packages': + system_site = value.lower() + elif key == 'home': +- sys._home = value ++ # this is breaking pyconfig.h path detection with venv ++ print('Ignoring "sys._home = value" override') + + sys.prefix = sys.exec_prefix = site_prefix + diff --git a/recipes/python3/patches/reproducible-buildinfo.diff b/recipes/python3/patches/reproducible-buildinfo.diff new file mode 100644 index 0000000..807d180 --- /dev/null +++ b/recipes/python3/patches/reproducible-buildinfo.diff @@ -0,0 +1,13 @@ +# DP: Build getbuildinfo.o with DATE/TIME values when defined + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -785,6 +785,8 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ + -DGITVERSION="\"`LC_ALL=C $(GITVERSION)`\"" \ + -DGITTAG="\"`LC_ALL=C $(GITTAG)`\"" \ + -DGITBRANCH="\"`LC_ALL=C $(GITBRANCH)`\"" \ ++ $(if $(BUILD_DATE),-DDATE='"$(BUILD_DATE)"') \ ++ $(if $(BUILD_TIME),-DTIME='"$(BUILD_TIME)"') \ + -o $@ $(srcdir)/Modules/getbuildinfo.c + + Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile diff --git a/recipes/sqlite3/Android.mk b/recipes/sqlite3/Android.mk new file mode 100644 index 0000000..05d13cd --- /dev/null +++ b/recipes/sqlite3/Android.mk @@ -0,0 +1,11 @@ +LOCAL_PATH := $(call my-dir)/.. + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := sqlite3.c + +LOCAL_MODULE := sqlite3 + +LOCAL_CFLAGS := -DSQLITE_ENABLE_FTS4 -D_FILE_OFFSET_BITS=32 -DSQLITE_ENABLE_JSON1 + +include $(BUILD_SHARED_LIBRARY) \ No newline at end of file diff --git a/recipes/sqlite3/__init__.py b/recipes/sqlite3/__init__.py new file mode 100644 index 0000000..2970302 --- /dev/null +++ b/recipes/sqlite3/__init__.py @@ -0,0 +1,36 @@ +from os.path import join +import shutil + +from pythonforandroid.recipe import NDKRecipe +from pythonforandroid.util import ensure_dir + + +class Sqlite3Recipe(NDKRecipe): + version = '3.35.5' + # Don't forget to change the URL when changing the version + url = 'https://www.sqlite.org/2021/sqlite-amalgamation-3350500.zip' + generated_libraries = ['sqlite3'] + + def should_build(self, arch): + return not self.has_libs(arch, 'libsqlite3.so') + + def prebuild_arch(self, arch): + super().prebuild_arch(arch) + # Copy the Android make file + ensure_dir(join(self.get_build_dir(arch.arch), 'jni')) + shutil.copyfile(join(self.get_recipe_dir(), 'Android.mk'), + join(self.get_build_dir(arch.arch), 'jni/Android.mk')) + + def build_arch(self, arch, *extra_args): + super().build_arch(arch) + # Copy the shared library + shutil.copyfile(join(self.get_build_dir(arch.arch), 'libs', arch.arch, 'libsqlite3.so'), + join(self.ctx.get_libs_dir(arch.arch), 'libsqlite3.so')) + + def get_recipe_env(self, arch): + env = super().get_recipe_env(arch) + env['NDK_PROJECT_PATH'] = self.get_build_dir(arch.arch) + return env + + +recipe = Sqlite3Recipe() \ No newline at end of file From 4b3e3d9e4e6caa84eed6176200466fc0543e55b9 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 28 Oct 2025 02:23:56 +0100 Subject: [PATCH 108/271] Updated gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index efbd926..d5b5e7e 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,7 @@ docs/build sideband*.egg-info sbapp*.egg-info LXST +environment +archived_build_tools +able +.gradle From 88010b76fcdc5d4a839bcd475efc2cf6a336a397 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 28 Oct 2025 02:24:11 +0100 Subject: [PATCH 109/271] Updated build configuration --- sbapp/Makefile | 30 +++++++++++++++--------------- sbapp/buildozer.spec | 9 +++++---- sbapp/main.py | 2 +- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index 93a10fb..943ac9d 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -19,34 +19,34 @@ pacthfiles: patchsdl injectxml patchpycodec2 patchsdl: # Pach USB HID behaviour - cp patches/HIDDeviceUSB.java .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/bootstrap_builds/sdl2/jni/SDL/android-project/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java - cp patches/HIDDeviceUSB.java .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/src/main/java/org/libsdl/app/HIDDeviceUSB.java - cp patches/HIDDeviceUSB.java .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/jni/SDL/android-project/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java + cp patches/HIDDeviceUSB.java .buildozer/android/platform/build-arm64-v8a/build/bootstrap_builds/sdl2/jni/SDL/android-project/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java + cp patches/HIDDeviceUSB.java .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/java/org/libsdl/app/HIDDeviceUSB.java + cp patches/HIDDeviceUSB.java .buildozer/android/platform/build-arm64-v8a/dists/sideband/jni/SDL/android-project/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java # Pach service loader cp patches/PythonService.java .buildozer/android/platform/python-for-android/pythonforandroid/bootstraps/common/build/src/main/java/org/kivy/android/PythonService.java - cp patches/PythonService.java .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/bootstrap_builds/sdl2/src/main/java/org/kivy/android/PythonService.java - cp patches/PythonService.java .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/src/main/java/org/kivy/android/PythonService.java + cp patches/PythonService.java .buildozer/android/platform/build-arm64-v8a/build/bootstrap_builds/sdl2/src/main/java/org/kivy/android/PythonService.java + cp patches/PythonService.java .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/java/org/kivy/android/PythonService.java patchpycodec2: - patchelf --replace-needed libcodec2.so.1.2 libcodec2.so .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/_python_bundle__arm64-v8a/_python_bundle/site-packages/pycodec2/pycodec2.so - patchelf --replace-needed libcodec2.so.1.2 libcodec2.so .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/_python_bundle__armeabi-v7a/_python_bundle/site-packages/pycodec2/pycodec2.so + patchelf --replace-needed libcodec2.so.1.2 libcodec2.so .buildozer/android/platform/build-arm64-v8a/dists/sideband/_python_bundle__arm64-v8a/_python_bundle/site-packages/pycodec2/pycodec2.so + # patchelf --replace-needed libcodec2.so.1.2 libcodec2.so .buildozer/android/platform/build-arm64-v8a/dists/sideband/_python_bundle__armeabi-v7a/_python_bundle/site-packages/pycodec2/pycodec2.so injectxml: # mkdir /home/markqvist/.local/lib/python3.11/site-packages/pythonforandroid/bootstraps/sdl2/build/src/main/xml # Inject XML on arm64-v8a - mkdir -p .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/src/main/res/xml - mkdir -p .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/templates - cp patches/device_filter.xml .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/src/main/res/xml/ - cp patches/file_paths.xml .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/src/main/res/xml/ - cp patches/AndroidManifest.tmpl.xml .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/templates/ - cp patches/p4a_build.py .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/build.py + mkdir -p .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/res/xml + mkdir -p .buildozer/android/platform/build-arm64-v8a/dists/sideband/templates + cp patches/device_filter.xml .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/res/xml/ + cp patches/file_paths.xml .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/res/xml/ + cp patches/AndroidManifest.tmpl.xml .buildozer/android/platform/build-arm64-v8a/dists/sideband/templates/ + cp patches/p4a_build.py .buildozer/android/platform/build-arm64-v8a/dists/sideband/build.py debug: buildozer android debug prebake: -ifneq (,$(wildcard .buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/src/main/res/xml/device_filter.xml)) +ifneq (,$(wildcard .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/res/xml/device_filter.xml)) @echo Device filter XML exists, skipping prebake else @(echo Prebaking build before patching files...) @@ -87,7 +87,7 @@ version: @(echo $$(python ./gv.py)) install: - adb install bin/sideband-$$(python ./gv.py)-arm64-v8a_armeabi-v7a-release.apk + adb install bin/sideband-$$(python ./gv.py)-arm64-v8a-release.apk console: (adb logcat | grep "python\|sidebandservice") diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index f970683..4c437e2 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -10,9 +10,9 @@ source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements, version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20250327 +android.numeric_version = 20251027 -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 +requirements = kivy==2.3.0,libbz2,sqlite3,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 @@ -31,13 +31,14 @@ fullscreen = 0 android.permissions = INTERNET,POST_NOTIFICATIONS,WAKE_LOCK,FOREGROUND_SERVICE,CHANGE_WIFI_MULTICAST_STATE,BLUETOOTH_SCAN,BLUETOOTH_ADVERTISE,BLUETOOTH_CONNECT,ACCESS_NETWORK_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,MANAGE_EXTERNAL_STORAGE,ACCESS_BACKGROUND_LOCATION,RECORD_AUDIO,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,FOREGROUND_SERVICE_CONNECTED_DEVICE -android.api = 31 +android.api = 33 android.minapi = 24 android.ndk = 25b android.skip_update = False android.accept_sdk_license = True android.release_artifact = apk -android.archs = arm64-v8a,armeabi-v7a +android.archs = arm64-v8a +#android.archs = arm64-v8a,armeabi-v7a #android.logcat_filters = *:S python:D services = sidebandservice:services/sidebandservice.py:foreground diff --git a/sbapp/main.py b/sbapp/main.py index 46e7d0b..187e99c 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.7.0" +__version__ = "1.8.0" __variant__ = "" import sys From dfac5cbd4af009f80a175ef33d273f7cf3188eee Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 28 Oct 2025 02:29:25 +0100 Subject: [PATCH 110/271] Updated dependencies --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index f766588..cf15e6b 100644 --- a/setup.py +++ b/setup.py @@ -122,7 +122,7 @@ setuptools.setup( "materialyoucolor>=2.0.7", "ffpyplayer", "sh", - "numpy>=2.3.4", + "numpy>=2.0.0", "lxst>=0.3.0", "mistune>=3.0.2", "beautifulsoup4", From 3f0d91ecdbb0b5ef2e85a2a8ff596fdd2c11e853 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 28 Oct 2025 12:33:06 +0100 Subject: [PATCH 111/271] Fixed Android BLE stack re-connection hang for RNodeInterface --- sbapp/services/sidebandservice.py | 11 +++++++ sbapp/sideband/core.py | 48 +++++++++++++------------------ 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index 814c2b6..f76ccb6 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -229,6 +229,8 @@ class SidebandService(): self.notification_intent = None self.notification_small_icon = None + self.rnode_ble_reset_required = False + if RNS.vendor.platformutils.is_android(): self.android_service = autoclass('org.kivy.android.PythonService').mService self.app_context = self.android_service.getApplication().getApplicationContext() @@ -476,6 +478,15 @@ class SidebandService(): self.sideband.setstate("wants.settings_reload", False) self.sideband.reload_configuration() + if self.sideband.getstate("wants.rnode_ble_reset"): + self.sideband.setstate("wants.rnode_ble_reset", False) + RNS.log("RNode BLE hardware error detected, re-initializing Android BLE dispatcher", RNS.LOG_ERROR) + if hasattr(self.sideband, "interface_rnode") and self.sideband.interface_rnode != None: + self.sideband.interface_rnode.reset_ble() + RNS.log("BLE hardware reset executed", RNS.LOG_INFO) + else: + RNS.log("No RNode interface active, could not execute BLE hardware reset", RNS.LOG_ERROR) + time.sleep(sleep_time) self.sideband.cleanup() diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 8fa432c..91c88f8 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -105,20 +105,20 @@ class PropagationNodeDetector(): self.owner_app = owner.owner_app class SidebandCore(): - CONV_P2P = 0x01 - CONV_GROUP = 0x02 - CONV_BROADCAST = 0x03 - CONV_VOICE = 0x04 + CONV_P2P = 0x01 + CONV_GROUP = 0x02 + CONV_BROADCAST = 0x03 + CONV_VOICE = 0x04 - MAX_ANNOUNCES = 24 + MAX_ANNOUNCES = 24 - 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 + 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 @@ -128,6 +128,8 @@ class SidebandCore(): LOG_DEQUE_MAXLEN = 128 + ERROR_INVALID_BLE_MTU = 0x20 + aspect_filter = "lxmf.delivery" def received_announce(self, destination_hash, announced_identity, app_data, announce_packet_hash): # Add the announce to the directory announce @@ -139,7 +141,7 @@ class SidebandCore(): "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. + # for Sideband's 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"" @@ -3580,22 +3582,12 @@ class SidebandCore(): if hasattr(self, "interface_rnode") and self.interface_rnode != None: if len(self.interface_rnode.hw_errors) > 0: - self.setpersistent("runtime.errors.rnode", self.interface_rnode.hw_errors[0]) - self.interface_rnode.hw_errors = [] + if self.interface_rnode.hw_errors[0]["error"] == self.ERROR_INVALID_BLE_MTU: + self.setstate("wants.rnode_ble_reset", True) + else: + self.setpersistent("runtime.errors.rnode", self.interface_rnode.hw_errors[0]) - # if not self.interface_rnode_adding: - # RNS.log("Hardware error on RNodeInterface, scheduling re-init", RNS.LOG_DEBUG) - # if self.interface_rnode in RNS.Transport.interfaces: - # RNS.Transport.interfaces.remove(self.interface_rnode) - # del self.interface_rnode - # self.interface_rnode = None - # self.interface_rnode_adding = True - # def job(): - # self.__add_rnodeinterface(delay=5) - # if self.config["start_announce"] == True: - # time.sleep(12) - # self.lxmf_announce(attached_interface=self.interface_rnode) - # threading.Thread(target=job, daemon=True).start() + self.interface_rnode.hw_errors = [] if (now - last_multicast_lock_check > 120): RNS.log("Checking multicast and wake locks", RNS.LOG_DEBUG) From 165f480d7ea7929eef464c524366f1c3e8d63bda Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 29 Oct 2025 02:08:27 +0100 Subject: [PATCH 112/271] Conversation list refactoring --- sbapp/main.py | 9 +- sbapp/ui/conversations.py | 903 +++++++++++++++++++++++++------------- 2 files changed, 601 insertions(+), 311 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 187e99c..c5dbc7e 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2704,11 +2704,10 @@ class SidebandApp(MDApp): if not self.conversations_view: self.conversations_view = Conversations(self) - for child in self.conversations_view.ids.conversations_scrollview.children: - self.conversations_view.ids.conversations_scrollview.remove_widget(child) - - self.conversations_view.ids.conversations_scrollview.effect_cls = ScrollEffect - self.conversations_view.ids.conversations_scrollview.add_widget(self.conversations_view.get_widget()) + # for child in self.conversations_view.ids.conversations_scrollview.children: + # self.conversations_view.ids.conversations_scrollview.remove_widget(child) + # self.conversations_view.ids.conversations_scrollview.effect_cls = ScrollEffect + # self.conversations_view.ids.conversations_scrollview.add_widget(self.conversations_view.get_widget()) self.root.ids.screen_manager.current = "conversations_screen" if self.messages_view: diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index ac263a5..502a63c 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -3,8 +3,9 @@ import time from kivy.metrics import dp,sp from kivy.uix.boxlayout import BoxLayout -from kivy.properties import StringProperty, BooleanProperty +from kivy.properties import StringProperty, BooleanProperty, OptionProperty, ColorProperty, Property from kivymd.uix.list import MDList, IconLeftWidget, IconRightWidget, OneLineAvatarIconListItem +from kivymd.uix.recycleview import MDRecycleView from kivymd.uix.menu import MDDropdownMenu from kivymd.toast import toast from kivy.uix.gridlayout import GridLayout @@ -18,6 +19,15 @@ from kivymd.uix.dialog import MDDialog from kivy.lang.builder import Builder +theme_text_color_options = ( + "Primary", + "Secondary", + "Hint", + "Error", + "Custom", + "ContrastParentBackground", +) + from kivy.utils import escape_markup if RNS.vendor.platformutils.get_platform() == "android": from ui.helpers import multilingual_markup @@ -39,12 +49,209 @@ class ConvSettings(BoxLayout): is_object = BooleanProperty() ptt_enabled = BooleanProperty() +class ConversationEntry(OneLineAvatarIconListItem): + app = None + owner_screen = None + conversation_dropdown = None + voice_dropdown = None + clear_dialog = None + clear_telemetry_dialog = None + delete_dialog = None + + icon = StringProperty() + ti_color = OptionProperty(None, options=theme_text_color_options) + icon_fg = Property(None, allownone=True) + icon_bg = Property(None, allownone=True) + + def __init__(self): + super().__init__() + self.bind(on_release=self.app.conversation_action) + self.ids.left_icon.bind(on_release=self.left_icon_action) + self.ids.right_icon.bind(on_release=self.right_icon_action) + self.__init_menus() + + def __init_menus(self): + dmi_h = 40 + if ConversationEntry.voice_dropdown == None: + dmv_items = [ { "viewclass": "OneLineListItem", "text": "Edit", "height": dp(dmi_h), "on_release": self.edit_action}, + { "text": "Copy Identity Hash", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": self.copy_address_action}, + { "text": "Delete", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": self.delete_conversation_action } ] + + ConversationEntry.voice_dropdown = MDDropdownMenu(caller=None, items=dmv_items, position="auto", width=dp(256), elevation=0, radius=dp(3)) + ConversationEntry.voice_dropdown.effect_cls = ScrollEffect + ConversationEntry.voice_dropdown.md_bg_color = self.app.color_hover + + if ConversationEntry.conversation_dropdown == None: + dm_items = [ { "viewclass": "OneLineListItem", "text": "Edit", "height": dp(dmi_h), "on_release": self.edit_action }, + { "viewclass": "OneLineListItem", "text": "Call", "height": dp(dmi_h), "on_release": self.call_action }, + { "text": "Copy Address", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": self.copy_address_action }, + { "text": "Clear Messages", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": self.clear_messages_action }, + { "text": "Clear Telemetry", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": self.clear_telemetry_action }, + { "text": "Delete Conversation", "viewclass": "OneLineListItem", "height": dp(dmi_h), "on_release": self.delete_conversation_action } ] + + ConversationEntry.conversation_dropdown = MDDropdownMenu(caller=None, items=dm_items, position="auto", width=dp(256), elevation=0, radius=dp(3)) + ConversationEntry.conversation_dropdown.effect_cls = ScrollEffect + ConversationEntry.conversation_dropdown.md_bg_color = self.app.color_hover + + def dispatch_update(self): + self.owner_screen.update() + + def dropdown_dismiss(self): + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + + def copy_address_action(self): + context_dest = ConversationEntry.conversation_dropdown.context_dest; caller = ConversationEntry.conversation_dropdown.caller + Clipboard.copy(RNS.hexrep(context_dest, delimit=False)) + self.dropdown_dismiss() + + def edit_action(self): + context_dest = ConversationEntry.conversation_dropdown.context_dest; caller = ConversationEntry.conversation_dropdown.caller + RNS.log(f"Menu action from {caller} for {RNS.prettyhexrep(context_dest)}") + dest = context_dest + try: + t_s = time.time() + cd = self.app.sideband._db_conversation(dest) + disp_name = self.app.sideband.raw_display_name(dest) + is_trusted = self.app.sideband.is_trusted(dest, conv_data=cd) + is_object = self.app.sideband.is_object(dest, conv_data=cd) + ptt_enabled = self.app.sideband.ptt_enabled(dest, conv_data=cd) + send_telemetry = self.app.sideband.should_send_telemetry(dest, conv_data=cd) + allow_requests = self.app.sideband.requests_allowed_from(dest, conv_data=cd) + yes_button = MDRectangleFlatButton(text="Save",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_accept, text_color=self.app.color_accept) + no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) + dialog_content = ConvSettings(disp_name=disp_name, context_dest=RNS.hexrep(dest, delimit=False), trusted=is_trusted, + telemetry=send_telemetry, allow_requests=allow_requests, is_object=is_object, ptt_enabled=ptt_enabled) + dialog_content.ids.name_field.font_name = self.app.input_font + dialog = MDDialog(title="Edit Conversation", text="With "+RNS.prettyhexrep(dest), + type="custom", content_cls=dialog_content, buttons=[yes_button, no_button]) + dialog.d_content = dialog_content + def dl_no(s): dialog.dismiss() + def dl_yes(s): + try: + name = dialog.d_content.ids["name_field"].text + trusted = dialog.d_content.ids["trusted_switch"].active + telemetry = dialog.d_content.ids["telemetry_switch"].active + allow_requests = dialog.d_content.ids["allow_requests_switch"].active + conv_is_object = dialog.d_content.ids["is_object_switch"].active + ptt_is_enabled = dialog.d_content.ids["ptt_enabled_switch"].active + if trusted: self.app.sideband.trusted_conversation(dest) + else: self.app.sideband.untrusted_conversation(dest) + if telemetry: self.app.sideband.send_telemetry_in_conversation(dest) + else: self.app.sideband.no_telemetry_in_conversation(dest) + if allow_requests: self.app.sideband.allow_requests_from(dest) + else: self.app.sideband.disallow_requests_from(dest) + if conv_is_object: self.app.sideband.conversation_set_object(dest, True) + else: self.app.sideband.conversation_set_object(dest, False) + if ptt_is_enabled:self.app.sideband.conversation_set_ptt_enabled(dest, True) + else: self.app.sideband.conversation_set_ptt_enabled(dest, False) + self.app.sideband.named_conversation(name, dest) + + except Exception as e: RNS.log("Error while saving conversation settings: "+str(e), RNS.LOG_ERROR) + + dialog.dismiss() + + def cb(dt): self.dispatch_update() + Clock.schedule_once(cb, 0.2) + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + dialog.open() + RNS.log("Generated edit dialog in "+str(RNS.prettytime(time.time()-t_s)), RNS.LOG_DEBUG) + + except Exception as e: + RNS.log("Error while creating conversation settings: "+str(e), RNS.LOG_ERROR) + + def delete_conversation_action(self): + context_dest = ConversationEntry.conversation_dropdown.context_dest; caller = ConversationEntry.conversation_dropdown.caller + if ConversationEntry.delete_dialog == None: + yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) + ConversationEntry.delete_dialog = MDDialog( title="Delete conversation?", buttons=[ yes_button, no_button ]) + def dl_yes(s): + ConversationEntry.delete_dialog.dismiss() + self.app.sideband.delete_conversation(ConversationEntry.conversation_dropdown.context_dest) + def cb(dt): self.dispatch_update() + Clock.schedule_once(cb, 0.1) + def dl_no(s): + self.delete_dialog.dismiss() + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + + self.dropdown_dismiss() + ConversationEntry.delete_dialog.open() + + def call_action(self): + context_dest = ConversationEntry.conversation_dropdown.context_dest; caller = ConversationEntry.conversation_dropdown.caller + identity = RNS.Identity.recall(ConversationEntry.conversation_dropdown.context_dest) + if identity: self.app.dial_action(identity.hash) + else: toast("Can't call, identity unknown") + self.dropdown_dismiss() + + def clear_messages_action(self): + context_dest = ConversationEntry.conversation_dropdown.context_dest; caller = ConversationEntry.conversation_dropdown.caller + if ConversationEntry.clear_dialog == None: + yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) + ConversationEntry.clear_dialog = MDDialog(title="Clear all messages in conversation?", buttons=[ yes_button, no_button ]) + + def dl_yes(s): + ConversationEntry.clear_dialog.dismiss() + self.app.sideband.clear_conversation(ConversationEntry.conversation_dropdown.context_dest) + def dl_no(s): + self.clear_dialog.dismiss() + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + + ConversationEntry.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + self.clear_dialog.open() + RNS.log(f"Menu action from {caller} for {RNS.prettyhexrep(context_dest)}") + + def clear_telemetry_action(self): + context_dest = ConversationEntry.conversation_dropdown.context_dest; caller = ConversationEntry.conversation_dropdown.caller + if ConversationEntry.clear_telemetry_dialog == None: + yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) + ConversationEntry.clear_telemetry_dialog = MDDialog( title="Clear all telemetry related to this peer?", buttons=[ yes_button, no_button ]) + def dl_yes(s): + ConversationEntry.clear_telemetry_dialog.dismiss() + self.app.sideband.clear_telemetry(self.conversation_dropdown.context_dest) + def dl_no(s): + ConversationEntry.clear_telemetry_dialog.dismiss() + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + + ConversationEntry.voice_dropdown.dismiss(); ConversationEntry.conversation_dropdown.dismiss() + ConversationEntry.clear_telemetry_dialog.open() + + def left_icon_action(self, sender): + RNS.log(f"Action from: {sender} {self.text}") + if self.object: self.app.object_details_action(sender=self, source_dest=self.sb_uid, from_objects=True) + else: self.app.conversation_action(self) + + def right_icon_action(self, sender): + ConversationEntry.voice_dropdown.context_dest = self.sb_uid + ConversationEntry.voice_dropdown.caller = self.ids.right_icon + ConversationEntry.conversation_dropdown.caller = self.ids.right_icon + ConversationEntry.conversation_dropdown.context_dest = self.sb_uid + if self.conv_type == self.app.sideband.CONV_VOICE: ConversationEntry.voice_dropdown.open() + else: ConversationEntry.conversation_dropdown.open() + +class ConversationList(MDRecycleView): + def __init__(self): + super().__init__() + self.data = [] + class Conversations(): def __init__(self, app): self.app = app self.context_dests = [] self.added_item_dests = [] - self.list = None + # self.list = None + self.conversation_list = None self.ids = None if not self.app.root.ids.screen_manager.has_screen("conversations_screen"): @@ -176,362 +383,416 @@ class Conversations(): return iconl - def update_widget(self): + def get_icon_colors(self, conv): + context_dest = conv["dest"] + trusted = conv["trust"] == 1 + appearance_from_all = self.app.sideband.config["display_style_from_all"] + appearance = self.app.sideband.peer_appearance(context_dest, conv=conv) + da = self.app.sideband.DEFAULT_APPEARANCE + ic_s = 24; ic_p = 14 + + fg = None; bg = None; ti_color = None + + if (trusted or appearance_from_all) and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: + fg = appearance[1] or da[1]; bg = appearance[2] or da[2] + ti_color = "Custom" + else: ti_color = None + + return {"ti_color": ti_color, "fg": fg, "bg": bg} + + def update_conversation_list(self): us = time.time() - RNS.log("Updating conversation list widgets", RNS.LOG_DEBUG) - if self.list == None: - self.list = MDList() - - remove_widgets = [] - for w in self.list.children: - if not w.sb_uid in [e["dest"] for e in self.context_dests]: - remove_widgets.append(w) - self.added_item_dests.remove(w.sb_uid) - - for w in remove_widgets: - self.list.remove_widget(w) - - + ConversationEntry.app = self.app + ConversationEntry.owner_screen = self + entries = [] for conv in self.context_dests: context_dest = conv["dest"] conv_type = conv["type"] unread = conv["unread"] last_activity = conv["last_activity"] + colors = self.get_icon_colors(conv) peer_disp_name = multilingual_markup(escape_markup(str(self.app.sideband.peer_display_name(context_dest))).encode("utf-8")).decode("utf-8") - if not context_dest in self.added_item_dests: - existing_conv = self.app.sideband._db_conversation(context_dest) - is_object = self.app.sideband.is_object(context_dest, conv_data=existing_conv) - ptt_enabled = self.app.sideband.ptt_enabled(context_dest, conv_data=existing_conv) - iconl = self.get_icon(conv) - item = OneLineAvatarIconListItem(text=peer_disp_name, on_release=self.app.conversation_action) - item.add_widget(iconl) - item.last_activity = last_activity - item.iconl = iconl - item.sb_uid = context_dest - item.sb_unread = unread - iconl.sb_uid = context_dest - item.conv_type = conv_type + existing_conv = self.app.sideband._db_conversation(context_dest) + is_object = self.app.sideband.is_object(context_dest, conv_data=existing_conv) + is_trusted = self.app.sideband.is_trusted(context_dest, conv_data=existing_conv) + ptt_enabled = self.app.sideband.ptt_enabled(context_dest, conv_data=existing_conv) + icon = self.trust_icon(conv) - def gen_edit(item): - def x(): - t_s = time.time() - dest = self.conversation_dropdown.context_dest - try: - cd = self.app.sideband._db_conversation(dest) - disp_name = self.app.sideband.raw_display_name(dest) - is_trusted = self.app.sideband.is_trusted(dest, conv_data=cd) - is_object = self.app.sideband.is_object(dest, conv_data=cd) - ptt_enabled = self.app.sideband.ptt_enabled(dest, conv_data=cd) - send_telemetry = self.app.sideband.should_send_telemetry(dest, conv_data=cd) - allow_requests = self.app.sideband.requests_allowed_from(dest, conv_data=cd) + cl_entry = {"icon": icon, "text": peer_disp_name, "conv_type": conv_type, + "ti_color": "Primary", "icon_fg": "#FFFFFF", "icon_bg": "#00000000", + "conv_type": conv_type, "sb_uid": context_dest, "sb_unread": unread, + "trusted": is_trusted, "object": is_object, "last_activity": last_activity} - yes_button = MDRectangleFlatButton(text="Save",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_accept, text_color=self.app.color_accept) - no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) - dialog_content = ConvSettings(disp_name=disp_name, context_dest=RNS.hexrep(dest, delimit=False), trusted=is_trusted, - telemetry=send_telemetry, allow_requests=allow_requests, is_object=is_object, ptt_enabled=ptt_enabled) - dialog_content.ids.name_field.font_name = self.app.input_font + if colors["ti_color"]: cl_entry["ti_color"] = colors["ti_color"] + if colors["fg"]: cl_entry["icon_fg"] = colors["fg"] + if colors["bg"]: cl_entry["icon_bg"] = colors["bg"] + entries.append(cl_entry) - dialog = MDDialog( - title="Edit Conversation", - text= "With "+RNS.prettyhexrep(dest), - type="custom", - content_cls=dialog_content, - buttons=[ yes_button, no_button ], - # elevation=0, - ) - dialog.d_content = dialog_content - def dl_yes(s): - try: - name = dialog.d_content.ids["name_field"].text - trusted = dialog.d_content.ids["trusted_switch"].active - telemetry = dialog.d_content.ids["telemetry_switch"].active - allow_requests = dialog.d_content.ids["allow_requests_switch"].active - conv_is_object = dialog.d_content.ids["is_object_switch"].active - ptt_is_enabled = dialog.d_content.ids["ptt_enabled_switch"].active - if trusted: - self.app.sideband.trusted_conversation(dest) - else: - self.app.sideband.untrusted_conversation(dest) + entries.sort(key=lambda w: (w["trusted"], w["last_activity"]), reverse=True) + self.conversation_list.data = entries - if telemetry: - self.app.sideband.send_telemetry_in_conversation(dest) - else: - self.app.sideband.no_telemetry_in_conversation(dest) + RNS.log("Updated recycle list widgets in "+RNS.prettytime(time.time()-us), RNS.LOG_DEBUG) - if allow_requests: - self.app.sideband.allow_requests_from(dest) - else: - self.app.sideband.disallow_requests_from(dest) + def update_widget(self): + RNS.log("Updating conversation list widgets", RNS.LOG_DEBUG) + # if self.list == None: self.list = MDList() + if self.conversation_list == None: + self.conversation_list = ConversationList() + self.ids.conversation_list_container.add_widget(self.conversation_list) - if conv_is_object: - self.app.sideband.conversation_set_object(dest, True) - else: - self.app.sideband.conversation_set_object(dest, False) + # remove_widgets = [] + # for w in self.list.children: + # if not w.sb_uid in [e["dest"] for e in self.context_dests]: + # remove_widgets.append(w) + # self.added_item_dests.remove(w.sb_uid) - if ptt_is_enabled: - RNS.log("Setting PTT enabled") - self.app.sideband.conversation_set_ptt_enabled(dest, True) - else: - RNS.log("Setting PTT disabled") - self.app.sideband.conversation_set_ptt_enabled(dest, False) + # for w in remove_widgets: + # self.list.remove_widget(w) + + self.update_conversation_list() - self.app.sideband.named_conversation(name, dest) + # us = time.time() + # for conv in self.context_dests: + # context_dest = conv["dest"] + # conv_type = conv["type"] + # unread = conv["unread"] + # last_activity = conv["last_activity"] - except Exception as e: - RNS.log("Error while saving conversation settings: "+str(e), RNS.LOG_ERROR) + # peer_disp_name = multilingual_markup(escape_markup(str(self.app.sideband.peer_display_name(context_dest))).encode("utf-8")).decode("utf-8") + # if not context_dest in self.added_item_dests: + # existing_conv = self.app.sideband._db_conversation(context_dest) + # is_object = self.app.sideband.is_object(context_dest, conv_data=existing_conv) + # ptt_enabled = self.app.sideband.ptt_enabled(context_dest, conv_data=existing_conv) + # iconl = self.get_icon(conv) + # item = OneLineAvatarIconListItem(text=peer_disp_name, on_release=self.app.conversation_action) + # item.add_widget(iconl) + # item.last_activity = last_activity + # item.iconl = iconl + # item.sb_uid = context_dest + # item.sb_unread = unread + # iconl.sb_uid = context_dest + # item.conv_type = conv_type - dialog.dismiss() + # def gen_edit(item): + # def x(): + # t_s = time.time() + # dest = self.conversation_dropdown.context_dest + # try: + # cd = self.app.sideband._db_conversation(dest) + # disp_name = self.app.sideband.raw_display_name(dest) + # is_trusted = self.app.sideband.is_trusted(dest, conv_data=cd) + # is_object = self.app.sideband.is_object(dest, conv_data=cd) + # ptt_enabled = self.app.sideband.ptt_enabled(dest, conv_data=cd) + # send_telemetry = self.app.sideband.should_send_telemetry(dest, conv_data=cd) + # allow_requests = self.app.sideband.requests_allowed_from(dest, conv_data=cd) - def cb(dt): - self.update() - Clock.schedule_once(cb, 0.2) + # yes_button = MDRectangleFlatButton(text="Save",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_accept, text_color=self.app.color_accept) + # no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) + # dialog_content = ConvSettings(disp_name=disp_name, context_dest=RNS.hexrep(dest, delimit=False), trusted=is_trusted, + # telemetry=send_telemetry, allow_requests=allow_requests, is_object=is_object, ptt_enabled=ptt_enabled) + # dialog_content.ids.name_field.font_name = self.app.input_font - def dl_no(s): - dialog.dismiss() + # dialog = MDDialog( + # title="Edit Conversation", + # text= "With "+RNS.prettyhexrep(dest), + # type="custom", + # content_cls=dialog_content, + # buttons=[ yes_button, no_button ], + # # elevation=0, + # ) + # dialog.d_content = dialog_content + # def dl_yes(s): + # try: + # name = dialog.d_content.ids["name_field"].text + # trusted = dialog.d_content.ids["trusted_switch"].active + # telemetry = dialog.d_content.ids["telemetry_switch"].active + # allow_requests = dialog.d_content.ids["allow_requests_switch"].active + # conv_is_object = dialog.d_content.ids["is_object_switch"].active + # ptt_is_enabled = dialog.d_content.ids["ptt_enabled_switch"].active + # if trusted: + # self.app.sideband.trusted_conversation(dest) + # else: + # self.app.sideband.untrusted_conversation(dest) - yes_button.bind(on_release=dl_yes) - no_button.bind(on_release=dl_no) - self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - dialog.open() - RNS.log("Generated edit dialog in "+str(RNS.prettytime(time.time()-t_s)), RNS.LOG_DEBUG) + # if telemetry: + # self.app.sideband.send_telemetry_in_conversation(dest) + # else: + # self.app.sideband.no_telemetry_in_conversation(dest) - except Exception as e: - RNS.log("Error while creating conversation settings: "+str(e), RNS.LOG_ERROR) + # if allow_requests: + # self.app.sideband.allow_requests_from(dest) + # else: + # self.app.sideband.disallow_requests_from(dest) - return x + # if conv_is_object: + # self.app.sideband.conversation_set_object(dest, True) + # else: + # self.app.sideband.conversation_set_object(dest, False) - def gen_clear(item): - def x(): - if self.clear_dialog == None: - yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) - no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) + # if ptt_is_enabled: + # RNS.log("Setting PTT enabled") + # self.app.sideband.conversation_set_ptt_enabled(dest, True) + # else: + # RNS.log("Setting PTT disabled") + # self.app.sideband.conversation_set_ptt_enabled(dest, False) - self.clear_dialog = MDDialog( - title="Clear all messages in conversation?", - buttons=[ yes_button, no_button ], - # elevation=0, - ) - def dl_yes(s): - self.clear_dialog.dismiss() - self.app.sideband.clear_conversation(self.conversation_dropdown.context_dest) - def dl_no(s): - self.clear_dialog.dismiss() + # self.app.sideband.named_conversation(name, dest) - yes_button.bind(on_release=dl_yes) - no_button.bind(on_release=dl_no) + # except Exception as e: + # RNS.log("Error while saving conversation settings: "+str(e), RNS.LOG_ERROR) - self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - self.clear_dialog.open() - return x + # dialog.dismiss() - def gen_clear_telemetry(item): - def x(): - if self.clear_telemetry_dialog == None: - yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) - no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) + # def cb(dt): + # self.update() + # Clock.schedule_once(cb, 0.2) - self.clear_telemetry_dialog = MDDialog( - title="Clear all telemetry related to this peer?", - buttons=[ yes_button, no_button ], - # elevation=0, - ) - def dl_yes(s): - self.clear_telemetry_dialog.dismiss() - self.app.sideband.clear_telemetry(self.conversation_dropdown.context_dest) - def dl_no(s): - self.clear_telemetry_dialog.dismiss() + # def dl_no(s): + # dialog.dismiss() - yes_button.bind(on_release=dl_yes) - no_button.bind(on_release=dl_no) + # yes_button.bind(on_release=dl_yes) + # no_button.bind(on_release=dl_no) + # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + # dialog.open() + # RNS.log("Generated edit dialog in "+str(RNS.prettytime(time.time()-t_s)), RNS.LOG_DEBUG) - self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - self.clear_telemetry_dialog.open() - return x + # except Exception as e: + # RNS.log("Error while creating conversation settings: "+str(e), RNS.LOG_ERROR) - def gen_del(item): - def x(): - if self.delete_dialog == None: - yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) - no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) - self.delete_dialog = MDDialog( - title="Delete conversation?", - buttons=[ yes_button, no_button ], - # elevation=0, - ) - def dl_yes(s): - self.delete_dialog.dismiss() - self.app.sideband.delete_conversation(self.conversation_dropdown.context_dest) - def cb(dt): - self.update() - Clock.schedule_once(cb, 0.2) - def dl_no(s): - self.delete_dialog.dismiss() + # return x - yes_button.bind(on_release=dl_yes) - no_button.bind(on_release=dl_no) + # def gen_clear(item): + # def x(): + # if self.clear_dialog == None: + # yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + # no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) - self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - self.delete_dialog.open() - return x + # self.clear_dialog = MDDialog( + # title="Clear all messages in conversation?", + # buttons=[ yes_button, no_button ], + # # elevation=0, + # ) + # def dl_yes(s): + # self.clear_dialog.dismiss() + # self.app.sideband.clear_conversation(self.conversation_dropdown.context_dest) + # def dl_no(s): + # self.clear_dialog.dismiss() - def gen_copy_addr(item): - def x(): - Clipboard.copy(RNS.hexrep(self.conversation_dropdown.context_dest, delimit=False)) - self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - return x + # yes_button.bind(on_release=dl_yes) + # no_button.bind(on_release=dl_no) - def gen_call(item): - def x(): - identity = RNS.Identity.recall(self.conversation_dropdown.context_dest) - if identity: self.app.dial_action(identity.hash) - else: toast("Can't call, identity unknown") - self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - return x + # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + # self.clear_dialog.open() + # return x - item.iconr = IconRightWidget(icon="dots-vertical"); + # def gen_clear_telemetry(item): + # def x(): + # if self.clear_telemetry_dialog == None: + # yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + # no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) - if self.voice_dropdown == None: - dmi_h = 40 - dmv_items = [ - { - "viewclass": "OneLineListItem", - "text": "Edit", - "height": dp(dmi_h), - "on_release": gen_edit(item) - }, - { - "text": "Copy Identity Hash", - "viewclass": "OneLineListItem", - "height": dp(dmi_h), - "on_release": gen_copy_addr(item) - }, - { - "text": "Delete", - "viewclass": "OneLineListItem", - "height": dp(dmi_h), - "on_release": gen_del(item) - } - ] + # self.clear_telemetry_dialog = MDDialog( + # title="Clear all telemetry related to this peer?", + # buttons=[ yes_button, no_button ], + # # elevation=0, + # ) + # def dl_yes(s): + # self.clear_telemetry_dialog.dismiss() + # self.app.sideband.clear_telemetry(self.conversation_dropdown.context_dest) + # def dl_no(s): + # self.clear_telemetry_dialog.dismiss() - self.voice_dropdown = MDDropdownMenu( - caller=item.iconr, - items=dmv_items, - position="auto", - width=dp(256), - elevation=0, - radius=dp(3), - ) - self.voice_dropdown.effect_cls = ScrollEffect - self.voice_dropdown.md_bg_color = self.app.color_hover + # yes_button.bind(on_release=dl_yes) + # no_button.bind(on_release=dl_no) - if self.conversation_dropdown == None: - dmi_h = 40 - dm_items = [ - { - "viewclass": "OneLineListItem", - "text": "Edit", - "height": dp(dmi_h), - "on_release": gen_edit(item) - }, - { - "viewclass": "OneLineListItem", - "text": "Call", - "height": dp(dmi_h), - "on_release": gen_call(item) - }, - { - "text": "Copy Address", - "viewclass": "OneLineListItem", - "height": dp(dmi_h), - "on_release": gen_copy_addr(item) - }, - { - "text": "Clear Messages", - "viewclass": "OneLineListItem", - "height": dp(dmi_h), - "on_release": gen_clear(item) - }, - { - "text": "Clear Telemetry", - "viewclass": "OneLineListItem", - "height": dp(dmi_h), - "on_release": gen_clear_telemetry(item) - }, - { - "text": "Delete Conversation", - "viewclass": "OneLineListItem", - "height": dp(dmi_h), - "on_release": gen_del(item) - } - ] + # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + # self.clear_telemetry_dialog.open() + # return x - self.conversation_dropdown = MDDropdownMenu( - caller=item.iconr, - items=dm_items, - position="auto", - width=dp(256), - elevation=0, - radius=dp(3), - ) - self.conversation_dropdown.effect_cls = ScrollEffect - self.conversation_dropdown.md_bg_color = self.app.color_hover + # def gen_del(item): + # def x(): + # if self.delete_dialog == None: + # yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + # no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) + # self.delete_dialog = MDDialog( + # title="Delete conversation?", + # buttons=[ yes_button, no_button ], + # # elevation=0, + # ) + # def dl_yes(s): + # self.delete_dialog.dismiss() + # self.app.sideband.delete_conversation(self.conversation_dropdown.context_dest) + # def cb(dt): + # self.update() + # Clock.schedule_once(cb, 0.2) + # def dl_no(s): + # self.delete_dialog.dismiss() - if conv_type == self.app.sideband.CONV_VOICE: - item.dmenu = self.voice_dropdown - else: - item.dmenu = self.conversation_dropdown + # yes_button.bind(on_release=dl_yes) + # no_button.bind(on_release=dl_no) - def callback_factory(ref, dest): - def x(sender): - self.conversation_dropdown.context_dest = dest - self.voice_dropdown.context_dest = dest - ref.dmenu.caller = ref.iconr - ref.dmenu.open() - return x + # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + # self.delete_dialog.open() + # return x - item.iconr.bind(on_release=callback_factory(item, context_dest)) + # def gen_copy_addr(item): + # def x(): + # Clipboard.copy(RNS.hexrep(self.conversation_dropdown.context_dest, delimit=False)) + # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + # return x - item.add_widget(item.iconr) + # def gen_call(item): + # def x(): + # identity = RNS.Identity.recall(self.conversation_dropdown.context_dest) + # if identity: self.app.dial_action(identity.hash) + # else: toast("Can't call, identity unknown") + # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() + # return x - item.trusted = self.app.sideband.is_trusted(context_dest, conv_data=existing_conv) - item.conv_type = conv_type + # item.iconr = IconRightWidget(icon="dots-vertical"); + + # if self.voice_dropdown == None: + # dmi_h = 40 + # dmv_items = [ + # { + # "viewclass": "OneLineListItem", + # "text": "Edit", + # "height": dp(dmi_h), + # "on_release": gen_edit(item) + # }, + # { + # "text": "Copy Identity Hash", + # "viewclass": "OneLineListItem", + # "height": dp(dmi_h), + # "on_release": gen_copy_addr(item) + # }, + # { + # "text": "Delete", + # "viewclass": "OneLineListItem", + # "height": dp(dmi_h), + # "on_release": gen_del(item) + # } + # ] + + # self.voice_dropdown = MDDropdownMenu( + # caller=item.iconr, + # items=dmv_items, + # position="auto", + # width=dp(256), + # elevation=0, + # radius=dp(3), + # ) + # self.voice_dropdown.effect_cls = ScrollEffect + # self.voice_dropdown.md_bg_color = self.app.color_hover + + # if self.conversation_dropdown == None: + # dmi_h = 40 + # dm_items = [ + # { + # "viewclass": "OneLineListItem", + # "text": "Edit", + # "height": dp(dmi_h), + # "on_release": gen_edit(item) + # }, + # { + # "viewclass": "OneLineListItem", + # "text": "Call", + # "height": dp(dmi_h), + # "on_release": gen_call(item) + # }, + # { + # "text": "Copy Address", + # "viewclass": "OneLineListItem", + # "height": dp(dmi_h), + # "on_release": gen_copy_addr(item) + # }, + # { + # "text": "Clear Messages", + # "viewclass": "OneLineListItem", + # "height": dp(dmi_h), + # "on_release": gen_clear(item) + # }, + # { + # "text": "Clear Telemetry", + # "viewclass": "OneLineListItem", + # "height": dp(dmi_h), + # "on_release": gen_clear_telemetry(item) + # }, + # { + # "text": "Delete Conversation", + # "viewclass": "OneLineListItem", + # "height": dp(dmi_h), + # "on_release": gen_del(item) + # } + # ] + + # self.conversation_dropdown = MDDropdownMenu( + # caller=item.iconr, + # items=dm_items, + # position="auto", + # width=dp(256), + # elevation=0, + # radius=dp(3), + # ) + # self.conversation_dropdown.effect_cls = ScrollEffect + # self.conversation_dropdown.md_bg_color = self.app.color_hover + + # if conv_type == self.app.sideband.CONV_VOICE: + # item.dmenu = self.voice_dropdown + # else: + # item.dmenu = self.conversation_dropdown + + # def callback_factory(ref, dest): + # def x(sender): + # self.conversation_dropdown.context_dest = dest + # self.voice_dropdown.context_dest = dest + # ref.dmenu.caller = ref.iconr + # ref.dmenu.open() + # return x + + # item.iconr.bind(on_release=callback_factory(item, context_dest)) + + # item.add_widget(item.iconr) + + # item.trusted = self.app.sideband.is_trusted(context_dest, conv_data=existing_conv) + # item.conv_type = conv_type - self.added_item_dests.append(context_dest) - self.list.add_widget(item) + # self.added_item_dests.append(context_dest) + # self.list.add_widget(item) - else: - for w in self.list.children: - if w.sb_uid == context_dest: - trust_icon = self.trust_icon(conv) - trusted = conv["trust"] == 1 - da = self.app.sideband.DEFAULT_APPEARANCE - appearance = self.app.sideband.peer_appearance(context_dest, conv) - if trusted and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: - fg = appearance[1] or da[1]; bg = appearance[2] or da[2] - ti_color = "Custom" - else: - ti_color = None + # else: + # for w in self.list.children: + # if w.sb_uid == context_dest: + # trust_icon = self.trust_icon(conv) + # trusted = conv["trust"] == 1 + # da = self.app.sideband.DEFAULT_APPEARANCE + # appearance = self.app.sideband.peer_appearance(context_dest, conv) + # if trusted and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: + # fg = appearance[1] or da[1]; bg = appearance[2] or da[2] + # ti_color = "Custom" + # else: + # ti_color = None - w.last_activity = last_activity - if ti_color != None: - w.iconl.theme_icon_color = ti_color - if bg != None: w.iconl.md_bg_color = bg - if fg != None: w.iconl.icon_color = fg - else: - w.iconl.theme_icon_color = "Primary" - w.iconl.md_bg_color = [0,0,0,0] + # w.last_activity = last_activity + # if ti_color != None: + # w.iconl.theme_icon_color = ti_color + # if bg != None: w.iconl.md_bg_color = bg + # if fg != None: w.iconl.icon_color = fg + # else: + # w.iconl.theme_icon_color = "Primary" + # w.iconl.md_bg_color = [0,0,0,0] - if w.iconl.icon != trust_icon: w.iconl.icon = trust_icon - if w.sb_unread != unread: w.sb_unread = unread - if w.text != peer_disp_name: w.text = peer_disp_name + # if w.iconl.icon != trust_icon: w.iconl.icon = trust_icon + # if w.sb_unread != unread: w.sb_unread = unread + # if w.text != peer_disp_name: w.text = peer_disp_name - self.list.children.sort(key=lambda w: (w.trusted, w.last_activity)) + # self.list.children.sort(key=lambda w: (w.trusted, w.last_activity)) - RNS.log("Updated conversation list widgets in "+RNS.prettytime(time.time()-us), RNS.LOG_DEBUG) + # RNS.log("Updated conversation list widgets in "+RNS.prettytime(time.time()-us), RNS.LOG_DEBUG) def get_widget(self): - return self.list + return self.conversation_list conv_screen_kv = """ MDScreen: @@ -558,11 +819,41 @@ MDScreen: ['account-plus', lambda x: root.app.new_conversation_action(self)], ] - ScrollView: - id: conversations_scrollview + # ScrollView: + # id: conversations_scrollview + + MDBoxLayout: + orientation: "vertical" + id: conversation_list_container """ Builder.load_string(""" + + + IconLeftWidget: + id: left_icon + theme_icon_color: root.ti_color + icon_color: root.icon_fg + md_bg_color: root.icon_bg + icon: root.icon + _default_icon_pad: dp(14) + icon_size: dp(24) + + IconRightWidget: + id: right_icon + icon: "dots-vertical" + +: + viewclass: "ConversationEntry" + effect_cls: "ScrollEffect" + + RecycleBoxLayout: + default_size: None, dp(57) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height + orientation: "vertical" + orientation: "vertical" spacing: "24dp" From d8581c981c231c805dc376d7fd0ec3565d6ea59f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 29 Oct 2025 02:22:23 +0100 Subject: [PATCH 113/271] Refactored conversation list --- sbapp/main.py | 11 +- sbapp/sideband/core.py | 2 +- sbapp/ui/conversations.py | 355 -------------------------------------- 3 files changed, 3 insertions(+), 365 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index c5dbc7e..8039d64 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2704,11 +2704,6 @@ class SidebandApp(MDApp): if not self.conversations_view: self.conversations_view = Conversations(self) - # for child in self.conversations_view.ids.conversations_scrollview.children: - # self.conversations_view.ids.conversations_scrollview.remove_widget(child) - # self.conversations_view.ids.conversations_scrollview.effect_cls = ScrollEffect - # self.conversations_view.ids.conversations_scrollview.add_widget(self.conversations_view.get_widget()) - self.root.ids.screen_manager.current = "conversations_screen" if self.messages_view: self.messages_view.ids.messages_scrollview.active_conversation = None @@ -2866,12 +2861,10 @@ class SidebandApp(MDApp): dialog.dismiss() self.message_sync_dialog.d_content.ids.sync_progress.value = 0.1 self.message_sync_dialog.d_content.ids.sync_status.text = "" - - # self.sideband.cancel_lxmf_sync() + if self.sideband.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_COMPLETE: + self.sideband.message_router.acknowledge_sync_completion(reset_state=True) def dl_stop(s): - # self.sideband.setstate("app.flags.lxmf_sync_dialog_open", False) - # dialog.dismiss() self.sideband.cancel_lxmf_sync() def cb(dt): self.widget_hide(self.sync_dialog.stop_button, True) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 91c88f8..4c62d36 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5358,7 +5358,7 @@ class SidebandCore(): if new_msgs == 0: return "Done, no new messages" else: - return "Downloaded "+str(new_msgs)+" new messages" + return "Downloaded "+str(new_msgs)+" messages" else: return "Unknown" diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index 502a63c..e2491fc 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -280,9 +280,6 @@ class Conversations(): self.added_item_dests = [] def update(self): - # if self.app.sideband.getstate("app.flags.unread_conversations"): - # self.clear_list() - self.context_dests = self.app.sideband.list_conversations(conversations=self.app.include_conversations, objects=self.app.include_objects) view_title = "Conversations" @@ -436,361 +433,12 @@ class Conversations(): def update_widget(self): RNS.log("Updating conversation list widgets", RNS.LOG_DEBUG) - # if self.list == None: self.list = MDList() if self.conversation_list == None: self.conversation_list = ConversationList() self.ids.conversation_list_container.add_widget(self.conversation_list) - - # remove_widgets = [] - # for w in self.list.children: - # if not w.sb_uid in [e["dest"] for e in self.context_dests]: - # remove_widgets.append(w) - # self.added_item_dests.remove(w.sb_uid) - - # for w in remove_widgets: - # self.list.remove_widget(w) self.update_conversation_list() - # us = time.time() - # for conv in self.context_dests: - # context_dest = conv["dest"] - # conv_type = conv["type"] - # unread = conv["unread"] - # last_activity = conv["last_activity"] - - # peer_disp_name = multilingual_markup(escape_markup(str(self.app.sideband.peer_display_name(context_dest))).encode("utf-8")).decode("utf-8") - # if not context_dest in self.added_item_dests: - # existing_conv = self.app.sideband._db_conversation(context_dest) - # is_object = self.app.sideband.is_object(context_dest, conv_data=existing_conv) - # ptt_enabled = self.app.sideband.ptt_enabled(context_dest, conv_data=existing_conv) - # iconl = self.get_icon(conv) - # item = OneLineAvatarIconListItem(text=peer_disp_name, on_release=self.app.conversation_action) - # item.add_widget(iconl) - # item.last_activity = last_activity - # item.iconl = iconl - # item.sb_uid = context_dest - # item.sb_unread = unread - # iconl.sb_uid = context_dest - # item.conv_type = conv_type - - # def gen_edit(item): - # def x(): - # t_s = time.time() - # dest = self.conversation_dropdown.context_dest - # try: - # cd = self.app.sideband._db_conversation(dest) - # disp_name = self.app.sideband.raw_display_name(dest) - # is_trusted = self.app.sideband.is_trusted(dest, conv_data=cd) - # is_object = self.app.sideband.is_object(dest, conv_data=cd) - # ptt_enabled = self.app.sideband.ptt_enabled(dest, conv_data=cd) - # send_telemetry = self.app.sideband.should_send_telemetry(dest, conv_data=cd) - # allow_requests = self.app.sideband.requests_allowed_from(dest, conv_data=cd) - - # yes_button = MDRectangleFlatButton(text="Save",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_accept, text_color=self.app.color_accept) - # no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) - # dialog_content = ConvSettings(disp_name=disp_name, context_dest=RNS.hexrep(dest, delimit=False), trusted=is_trusted, - # telemetry=send_telemetry, allow_requests=allow_requests, is_object=is_object, ptt_enabled=ptt_enabled) - # dialog_content.ids.name_field.font_name = self.app.input_font - - # dialog = MDDialog( - # title="Edit Conversation", - # text= "With "+RNS.prettyhexrep(dest), - # type="custom", - # content_cls=dialog_content, - # buttons=[ yes_button, no_button ], - # # elevation=0, - # ) - # dialog.d_content = dialog_content - # def dl_yes(s): - # try: - # name = dialog.d_content.ids["name_field"].text - # trusted = dialog.d_content.ids["trusted_switch"].active - # telemetry = dialog.d_content.ids["telemetry_switch"].active - # allow_requests = dialog.d_content.ids["allow_requests_switch"].active - # conv_is_object = dialog.d_content.ids["is_object_switch"].active - # ptt_is_enabled = dialog.d_content.ids["ptt_enabled_switch"].active - # if trusted: - # self.app.sideband.trusted_conversation(dest) - # else: - # self.app.sideband.untrusted_conversation(dest) - - # if telemetry: - # self.app.sideband.send_telemetry_in_conversation(dest) - # else: - # self.app.sideband.no_telemetry_in_conversation(dest) - - # if allow_requests: - # self.app.sideband.allow_requests_from(dest) - # else: - # self.app.sideband.disallow_requests_from(dest) - - # if conv_is_object: - # self.app.sideband.conversation_set_object(dest, True) - # else: - # self.app.sideband.conversation_set_object(dest, False) - - # if ptt_is_enabled: - # RNS.log("Setting PTT enabled") - # self.app.sideband.conversation_set_ptt_enabled(dest, True) - # else: - # RNS.log("Setting PTT disabled") - # self.app.sideband.conversation_set_ptt_enabled(dest, False) - - # self.app.sideband.named_conversation(name, dest) - - # except Exception as e: - # RNS.log("Error while saving conversation settings: "+str(e), RNS.LOG_ERROR) - - # dialog.dismiss() - - # def cb(dt): - # self.update() - # Clock.schedule_once(cb, 0.2) - - # def dl_no(s): - # dialog.dismiss() - - # yes_button.bind(on_release=dl_yes) - # no_button.bind(on_release=dl_no) - # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - # dialog.open() - # RNS.log("Generated edit dialog in "+str(RNS.prettytime(time.time()-t_s)), RNS.LOG_DEBUG) - - # except Exception as e: - # RNS.log("Error while creating conversation settings: "+str(e), RNS.LOG_ERROR) - - # return x - - # def gen_clear(item): - # def x(): - # if self.clear_dialog == None: - # yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) - # no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) - - # self.clear_dialog = MDDialog( - # title="Clear all messages in conversation?", - # buttons=[ yes_button, no_button ], - # # elevation=0, - # ) - # def dl_yes(s): - # self.clear_dialog.dismiss() - # self.app.sideband.clear_conversation(self.conversation_dropdown.context_dest) - # def dl_no(s): - # self.clear_dialog.dismiss() - - # yes_button.bind(on_release=dl_yes) - # no_button.bind(on_release=dl_no) - - # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - # self.clear_dialog.open() - # return x - - # def gen_clear_telemetry(item): - # def x(): - # if self.clear_telemetry_dialog == None: - # yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) - # no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) - - # self.clear_telemetry_dialog = MDDialog( - # title="Clear all telemetry related to this peer?", - # buttons=[ yes_button, no_button ], - # # elevation=0, - # ) - # def dl_yes(s): - # self.clear_telemetry_dialog.dismiss() - # self.app.sideband.clear_telemetry(self.conversation_dropdown.context_dest) - # def dl_no(s): - # self.clear_telemetry_dialog.dismiss() - - # yes_button.bind(on_release=dl_yes) - # no_button.bind(on_release=dl_no) - - # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - # self.clear_telemetry_dialog.open() - # return x - - # def gen_del(item): - # def x(): - # if self.delete_dialog == None: - # yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) - # no_button = MDRectangleFlatButton(text="No",font_size=dp(18)) - # self.delete_dialog = MDDialog( - # title="Delete conversation?", - # buttons=[ yes_button, no_button ], - # # elevation=0, - # ) - # def dl_yes(s): - # self.delete_dialog.dismiss() - # self.app.sideband.delete_conversation(self.conversation_dropdown.context_dest) - # def cb(dt): - # self.update() - # Clock.schedule_once(cb, 0.2) - # def dl_no(s): - # self.delete_dialog.dismiss() - - # yes_button.bind(on_release=dl_yes) - # no_button.bind(on_release=dl_no) - - # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - # self.delete_dialog.open() - # return x - - # def gen_copy_addr(item): - # def x(): - # Clipboard.copy(RNS.hexrep(self.conversation_dropdown.context_dest, delimit=False)) - # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - # return x - - # def gen_call(item): - # def x(): - # identity = RNS.Identity.recall(self.conversation_dropdown.context_dest) - # if identity: self.app.dial_action(identity.hash) - # else: toast("Can't call, identity unknown") - # self.voice_dropdown.dismiss(); self.conversation_dropdown.dismiss() - # return x - - # item.iconr = IconRightWidget(icon="dots-vertical"); - - # if self.voice_dropdown == None: - # dmi_h = 40 - # dmv_items = [ - # { - # "viewclass": "OneLineListItem", - # "text": "Edit", - # "height": dp(dmi_h), - # "on_release": gen_edit(item) - # }, - # { - # "text": "Copy Identity Hash", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_copy_addr(item) - # }, - # { - # "text": "Delete", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_del(item) - # } - # ] - - # self.voice_dropdown = MDDropdownMenu( - # caller=item.iconr, - # items=dmv_items, - # position="auto", - # width=dp(256), - # elevation=0, - # radius=dp(3), - # ) - # self.voice_dropdown.effect_cls = ScrollEffect - # self.voice_dropdown.md_bg_color = self.app.color_hover - - # if self.conversation_dropdown == None: - # dmi_h = 40 - # dm_items = [ - # { - # "viewclass": "OneLineListItem", - # "text": "Edit", - # "height": dp(dmi_h), - # "on_release": gen_edit(item) - # }, - # { - # "viewclass": "OneLineListItem", - # "text": "Call", - # "height": dp(dmi_h), - # "on_release": gen_call(item) - # }, - # { - # "text": "Copy Address", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_copy_addr(item) - # }, - # { - # "text": "Clear Messages", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_clear(item) - # }, - # { - # "text": "Clear Telemetry", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_clear_telemetry(item) - # }, - # { - # "text": "Delete Conversation", - # "viewclass": "OneLineListItem", - # "height": dp(dmi_h), - # "on_release": gen_del(item) - # } - # ] - - # self.conversation_dropdown = MDDropdownMenu( - # caller=item.iconr, - # items=dm_items, - # position="auto", - # width=dp(256), - # elevation=0, - # radius=dp(3), - # ) - # self.conversation_dropdown.effect_cls = ScrollEffect - # self.conversation_dropdown.md_bg_color = self.app.color_hover - - # if conv_type == self.app.sideband.CONV_VOICE: - # item.dmenu = self.voice_dropdown - # else: - # item.dmenu = self.conversation_dropdown - - # def callback_factory(ref, dest): - # def x(sender): - # self.conversation_dropdown.context_dest = dest - # self.voice_dropdown.context_dest = dest - # ref.dmenu.caller = ref.iconr - # ref.dmenu.open() - # return x - - # item.iconr.bind(on_release=callback_factory(item, context_dest)) - - # item.add_widget(item.iconr) - - # item.trusted = self.app.sideband.is_trusted(context_dest, conv_data=existing_conv) - # item.conv_type = conv_type - - # self.added_item_dests.append(context_dest) - # self.list.add_widget(item) - - # else: - # for w in self.list.children: - # if w.sb_uid == context_dest: - # trust_icon = self.trust_icon(conv) - # trusted = conv["trust"] == 1 - # da = self.app.sideband.DEFAULT_APPEARANCE - # appearance = self.app.sideband.peer_appearance(context_dest, conv) - # if trusted and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: - # fg = appearance[1] or da[1]; bg = appearance[2] or da[2] - # ti_color = "Custom" - # else: - # ti_color = None - - # w.last_activity = last_activity - # if ti_color != None: - # w.iconl.theme_icon_color = ti_color - # if bg != None: w.iconl.md_bg_color = bg - # if fg != None: w.iconl.icon_color = fg - # else: - # w.iconl.theme_icon_color = "Primary" - # w.iconl.md_bg_color = [0,0,0,0] - - # if w.iconl.icon != trust_icon: w.iconl.icon = trust_icon - # if w.sb_unread != unread: w.sb_unread = unread - # if w.text != peer_disp_name: w.text = peer_disp_name - - # self.list.children.sort(key=lambda w: (w.trusted, w.last_activity)) - - # RNS.log("Updated conversation list widgets in "+RNS.prettytime(time.time()-us), RNS.LOG_DEBUG) - def get_widget(self): return self.conversation_list @@ -819,9 +467,6 @@ MDScreen: ['account-plus', lambda x: root.app.new_conversation_action(self)], ] - # ScrollView: - # id: conversations_scrollview - MDBoxLayout: orientation: "vertical" id: conversation_list_container From 2e44d49d6b64b420b5ed73dbe9633c1d0af9f940 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 29 Oct 2025 12:51:50 +0100 Subject: [PATCH 114/271] Updated gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index d5b5e7e..69ecdf7 100644 --- a/.gitignore +++ b/.gitignore @@ -36,5 +36,4 @@ sbapp*.egg-info LXST environment archived_build_tools -able .gradle From 9b6a51a03ee496b7d6849c1aa00c9a57a3a9b179 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 29 Oct 2025 12:54:59 +0100 Subject: [PATCH 115/271] Use local version of able --- libs/able/.gitignore | 16 + libs/able/CHANGELOG.rst | 103 +++++ libs/able/LICENSE | 22 ++ libs/able/MANIFEST.in | 4 + libs/able/able/__init__.py | 84 ++++ libs/able/able/adapter.py | 179 +++++++++ libs/able/able/advertising.py | 330 ++++++++++++++++ libs/able/able/android/__init__.py | 0 libs/able/able/android/dispatcher.py | 105 +++++ libs/able/able/android/jni.py | 151 +++++++ libs/able/able/dispatcher.py | 371 ++++++++++++++++++ libs/able/able/filters.py | 237 +++++++++++ libs/able/able/permissions.py | 53 +++ libs/able/able/queue.py | 90 +++++ libs/able/able/scan_settings.py | 20 + libs/able/able/src/org/able/BLE.java | 283 +++++++++++++ .../able/able/src/org/able/BLEAdvertiser.java | 61 +++ .../able/src/org/able/PythonBluetooth.java | 25 ++ .../org/able/PythonBluetoothAdvertiser.java | 13 + libs/able/able/structures.py | 81 ++++ libs/able/able/utils.py | 42 ++ libs/able/able/version.py | 5 + libs/able/docs/Makefile | 177 +++++++++ libs/able/docs/api.rst | 154 ++++++++ libs/able/docs/conf.py | 295 ++++++++++++++ libs/able/docs/example.rst | 192 +++++++++ libs/able/docs/index.rst | 3 + libs/able/examples/adapter_state_change.py | 27 ++ libs/able/examples/advertising_battery.py | 71 ++++ libs/able/examples/alert/buildozer.spec | 27 ++ libs/able/examples/alert/error_message.kv | 21 + libs/able/examples/alert/error_message.py | 39 ++ libs/able/examples/alert/main.py | 64 +++ libs/able/examples/mtu.py | 52 +++ .../examples/multi_devices/buildozer.spec | 27 ++ libs/able/examples/multi_devices/main.py | 96 +++++ .../examples/service_advertise/buildozer.spec | 27 ++ libs/able/examples/service_advertise/main.py | 56 +++ .../examples/service_advertise/service.py | 28 ++ .../able/examples/service_scan/buildozer.spec | 29 ++ libs/able/examples/service_scan/main.py | 48 +++ libs/able/examples/service_scan/service.py | 27 ++ libs/able/recipes/__init__.py | 0 libs/able/recipes/able_recipe/__init__.py | 34 ++ libs/able/recipes/able_recipe/setup.py | 9 + libs/able/setup.py | 135 +++++++ libs/able/testapps/bletest/.gitignore | 1 + libs/able/testapps/bletest/bletestapp.kv | 193 +++++++++ libs/able/testapps/bletest/buildozer.spec | 17 + libs/able/testapps/bletest/main.py | 245 ++++++++++++ libs/able/testapps/bletest/server.go | 95 +++++ libs/able/tests/__init__.py | 0 libs/able/tests/notebooks/.gitignore | 4 + libs/able/tests/notebooks/init.md | 43 ++ libs/able/tests/notebooks/run | 22 ++ libs/able/tests/notebooks/run_all_tests | 4 + libs/able/tests/notebooks/test_basic.expected | 26 ++ libs/able/tests/notebooks/test_basic.md | 74 ++++ .../notebooks/test_scan_filters.expected | 72 ++++ .../able/tests/notebooks/test_scan_filters.md | 222 +++++++++++ .../notebooks/test_scan_settings.expected | 27 ++ .../tests/notebooks/test_scan_settings.md | 105 +++++ libs/able/tests/test_adapter.py | 81 ++++ libs/able/tests/test_ble_queue.py | 34 ++ libs/able/tests/test_dispatcher.py | 47 +++ libs/able/tests/test_filters.py | 50 +++ libs/able/tests/test_setup.py | 30 ++ 67 files changed, 5305 insertions(+) create mode 100644 libs/able/.gitignore create mode 100644 libs/able/CHANGELOG.rst create mode 100644 libs/able/LICENSE create mode 100644 libs/able/MANIFEST.in create mode 100644 libs/able/able/__init__.py create mode 100644 libs/able/able/adapter.py create mode 100644 libs/able/able/advertising.py create mode 100644 libs/able/able/android/__init__.py create mode 100644 libs/able/able/android/dispatcher.py create mode 100644 libs/able/able/android/jni.py create mode 100644 libs/able/able/dispatcher.py create mode 100644 libs/able/able/filters.py create mode 100644 libs/able/able/permissions.py create mode 100644 libs/able/able/queue.py create mode 100644 libs/able/able/scan_settings.py create mode 100644 libs/able/able/src/org/able/BLE.java create mode 100644 libs/able/able/src/org/able/BLEAdvertiser.java create mode 100644 libs/able/able/src/org/able/PythonBluetooth.java create mode 100644 libs/able/able/src/org/able/PythonBluetoothAdvertiser.java create mode 100644 libs/able/able/structures.py create mode 100644 libs/able/able/utils.py create mode 100644 libs/able/able/version.py create mode 100644 libs/able/docs/Makefile create mode 100644 libs/able/docs/api.rst create mode 100644 libs/able/docs/conf.py create mode 100644 libs/able/docs/example.rst create mode 100644 libs/able/docs/index.rst create mode 100644 libs/able/examples/adapter_state_change.py create mode 100644 libs/able/examples/advertising_battery.py create mode 100644 libs/able/examples/alert/buildozer.spec create mode 100644 libs/able/examples/alert/error_message.kv create mode 100644 libs/able/examples/alert/error_message.py create mode 100644 libs/able/examples/alert/main.py create mode 100644 libs/able/examples/mtu.py create mode 100644 libs/able/examples/multi_devices/buildozer.spec create mode 100644 libs/able/examples/multi_devices/main.py create mode 100644 libs/able/examples/service_advertise/buildozer.spec create mode 100644 libs/able/examples/service_advertise/main.py create mode 100644 libs/able/examples/service_advertise/service.py create mode 100644 libs/able/examples/service_scan/buildozer.spec create mode 100644 libs/able/examples/service_scan/main.py create mode 100644 libs/able/examples/service_scan/service.py create mode 100644 libs/able/recipes/__init__.py create mode 100644 libs/able/recipes/able_recipe/__init__.py create mode 100644 libs/able/recipes/able_recipe/setup.py create mode 100644 libs/able/setup.py create mode 100644 libs/able/testapps/bletest/.gitignore create mode 100644 libs/able/testapps/bletest/bletestapp.kv create mode 100644 libs/able/testapps/bletest/buildozer.spec create mode 100644 libs/able/testapps/bletest/main.py create mode 100644 libs/able/testapps/bletest/server.go create mode 100644 libs/able/tests/__init__.py create mode 100644 libs/able/tests/notebooks/.gitignore create mode 100644 libs/able/tests/notebooks/init.md create mode 100755 libs/able/tests/notebooks/run create mode 100755 libs/able/tests/notebooks/run_all_tests create mode 100644 libs/able/tests/notebooks/test_basic.expected create mode 100644 libs/able/tests/notebooks/test_basic.md create mode 100644 libs/able/tests/notebooks/test_scan_filters.expected create mode 100644 libs/able/tests/notebooks/test_scan_filters.md create mode 100644 libs/able/tests/notebooks/test_scan_settings.expected create mode 100644 libs/able/tests/notebooks/test_scan_settings.md create mode 100644 libs/able/tests/test_adapter.py create mode 100644 libs/able/tests/test_ble_queue.py create mode 100644 libs/able/tests/test_dispatcher.py create mode 100644 libs/able/tests/test_filters.py create mode 100644 libs/able/tests/test_setup.py diff --git a/libs/able/.gitignore b/libs/able/.gitignore new file mode 100644 index 0000000..56629a1 --- /dev/null +++ b/libs/able/.gitignore @@ -0,0 +1,16 @@ +.buildozer/ +bin/ +docs/_build/ +*~ +*.swp +*.sublime-workspace +*.pyo +*.pyc +*.so + +build/ +dist/ +sdist/ +wheels/ +*.egg-info + diff --git a/libs/able/CHANGELOG.rst b/libs/able/CHANGELOG.rst new file mode 100644 index 0000000..f56f9ad --- /dev/null +++ b/libs/able/CHANGELOG.rst @@ -0,0 +1,103 @@ +Changelog +========= + +1.0.16 +------ + +* Added `autoconnect` parameter to connection methods + `#45 `_ + +1.0.15 +------ + +* Changing the wheel name to avoid installing a package from cache + `#40 `_ + +1.0.14 +------ + +* Added event handler for bluetooth adapter state change + `#39 `_ by `robgar2001 `_ +* Removal of deprecated `convert_path` from setup script + +1.0.13 +------ + +* Fixed build failure when pip isolated environment is used `#38 `_ + +1.0.12 +------ + +* Fixed crash on API level 31 (Android 12) `#37 `_ +* Added new optional `BluetoothDispatcher` parameter to specifiy required permissions: `runtime_permissions`. + Runtime permissions that are required by by default: + ACCESS_FINE_LOCATION, BLUETOOTH_SCAN, BLUETOOTH_CONNECT, BLUETOOTH_ADVERTISE +* Changed `able.require_bluetooth_enabled` behavior: first asks for runtime permissions + and if permissions are granted then offers to enable the adapter +* `require_runtime_permissions` decorator deprecated + +1.0.11 +------ + +* Improved logging of reconnection management + `#33 `_ by `robgar2001 `_ + +1.0.10 +------ + +* Fixed build failure after AAB support was added to python-for-android + +1.0.9 +----- + +* Switched from deprecated scanning method `BluetoothAdapter.startLeScan` to `BluetoothLeScanner.startScan` +* Added support for BLE scanning settings: `able.scan_settings` module +* Added support for BLE scanning filters: `able.filters` module + + +1.0.8 +----- + +* Added support to use `able` in Android services +* Added decorators: + + - `able.require_bluetooth_enabled`: to call `BluetoothDispatcher` method when bluetooth adapter becomes ready + - `able.require_runtime_permissions`: to call `BluetoothDispatcher` method when location runtime permission is granted + + +1.0.7 +----- + +* Added `able.advertising`: module to perform BLE advertise operations +* Added property to get and set Bluetoth adapter name + + +1.0.6 +----- + +* Fixed `TypeError` exception on `BluetoothDispatcher.enable_notifications` + + +1.0.5 +----- + +* Added `BluetoothDispatcher.bonded_devices` property: list of paired BLE devices + +1.0.4 +----- + +* Fixed sending string data with `write_characteristic` function + +1.0.3 +----- + +* Changed package version generation: + + - Version is set during the build, from the git tag + - Development (git master) version is always "0.0.0" +* Added ATT MTU changing method and callback +* Added MTU changing example +* Fixed: + + - set `BluetoothDispatcher.gatt` attribute in GATT connection handler, + to avoid possible `on_connection_state_change()` call before the `gatt` attribute is set diff --git a/libs/able/LICENSE b/libs/able/LICENSE new file mode 100644 index 0000000..53601b8 --- /dev/null +++ b/libs/able/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2017 b3b + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/libs/able/MANIFEST.in b/libs/able/MANIFEST.in new file mode 100644 index 0000000..571bea0 --- /dev/null +++ b/libs/able/MANIFEST.in @@ -0,0 +1,4 @@ +include LICENSE +include README.rst +include CHANGELOG.rst +include able/src/org/able/*.java diff --git a/libs/able/able/__init__.py b/libs/able/able/__init__.py new file mode 100644 index 0000000..2ebad68 --- /dev/null +++ b/libs/able/able/__init__.py @@ -0,0 +1,84 @@ +from enum import IntEnum + +from able.structures import Advertisement, Services +from able.version import __version__ # noqa +from kivy.utils import platform + +__all__ = ( + "Advertisement", + "BluetoothDispatcher", + "Services", +) + +# constants +GATT_SUCCESS = 0 #: GATT operation completed successfully +STATE_CONNECTED = 2 #: The profile is in connected state +STATE_DISCONNECTED = 0 #: The profile is in disconnected state + + +class AdapterState(IntEnum): + """Bluetooth adapter state constants. + https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#STATE_OFF + """ + + OFF = 10 #: Adapter is off + TURNING_ON = 11 #: Adapter is turning on + ON = 12 #: Adapter is on + TURNING_OFF = 13 #: Adapter is turning off + + +class WriteType(IntEnum): + """GATT characteristic write types constants.""" + + DEFAULT = ( + 2 #: Write characteristic, requesting acknowledgement by the remote device + ) + NO_RESPONSE = ( + 1 #: Write characteristic without requiring a response by the remote device + ) + SIGNED = 4 #: Write characteristic including authentication signature + + +if platform == "android": + from able.android.dispatcher import BluetoothDispatcher +else: + + # mock android and PyJNIus modules usage + import sys + from unittest.mock import Mock + + sys.modules["android"] = Mock() + sys.modules["android.permissions"] = Mock() + jnius = Mock() + + class mocked_autoclass(Mock): + def __call__(self, *args, **kwargs): + mock = Mock() + mock.__repr__ = lambda s: f"jnius.autoclass('{args[0]}')" + mock.SDK_INT = 255 + return mock + + jnius.autoclass = mocked_autoclass() + sys.modules["jnius"] = jnius + + from able.dispatcher import BluetoothDispatcherBase + + class BluetoothDispatcher(BluetoothDispatcherBase): + """Bluetooth Low Energy interface + + :param queue_timeout: BLE operations queue timeout + :param enable_ble_code: request code to identify activity that alows + user to turn on Bluetooth adapter + :param runtime_permissions: overridden list of + :py:mod:`permissions ` + to be requested on runtime. + """ + + +from able.adapter import require_bluetooth_enabled +from able.permissions import Permission + + +def require_runtime_permissions(method): + """Deprecated decorator, left for backwards compatibility.""" + return method diff --git a/libs/able/able/adapter.py b/libs/able/able/adapter.py new file mode 100644 index 0000000..ae5f378 --- /dev/null +++ b/libs/able/able/adapter.py @@ -0,0 +1,179 @@ +from dataclasses import dataclass, field +from functools import partial, wraps +from typing import Optional + +from android import activity +from android.permissions import ( + check_permission, + request_permissions, +) +from jnius import autoclass +from kivy.logger import Logger + + +Activity = autoclass("android.app.Activity") + + +def require_bluetooth_enabled(method): + """Decorator to call `BluetoothDispatcher` method + when runtime permissions are granted + and Bluetooth adapter becomes ready. + + Decorator launches system activities that allows the user + to grant runtime permissions and turn on Bluetooth, + if Bluetooth is not enabled. + """ + + @wraps(method) + def wrapper(self, *args, **kwargs): + manager = AdapterManager.get_attached_manager(self) + if manager: + return manager.execute(partial(method, self, *args, **kwargs)) + return None + + return wrapper + + +def set_adapter_failure_rollback(handler): + """Decorator to launch handler + if permissions are not granted or adapter is not enabled.""" + + def inner(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + manager = AdapterManager.get_attached_manager(self) + if manager: + manager.rollback_handlers.append(partial(handler, self)) + return func(self, *args, **kwargs) + return None + + return wrapper + + return inner + + +@dataclass +class AdapterManager: + """ + Class for managing the execution of operations + that require the BLE adapter. + Operations are deferred until runtime permissions are granted + and the BLE adapter is enabled. + """ + + ble: "org.able.BLE" + enable_ble_code: str + runtime_permissions: list + operations: list = field(default_factory=list) + rollback_handlers: list = field(default_factory=list) + is_permissions_granted: bool = False + is_permissions_requested: bool = False + is_adapter_requested: bool = False + + @property + def adapter(self) -> Optional["android.bluetooth.BluetoothAdapter"]: + if self.has_permissions: + adapter = self.ble.mBluetoothAdapter + if adapter and adapter.isEnabled(): + return adapter + return None + + @property + def has_permissions(self): + if not self.is_permissions_granted: + self.is_permissions_granted = self.check_permissions() + return self.is_permissions_granted + + @property + def is_service_context(self): + return not activity._activity + + def __post_init__(self): + if self.is_service_context: + self.is_permissions_granted = True + else: + activity.bind(on_activity_result=self.on_activity_result) + + @classmethod + def get_attached_manager(cls, instance): + manager = getattr(instance, "_adapter_manager", None) + if not manager: + Logger.error("BLE adapter manager is not installed") + return manager + + def install(self, instance): + setattr(instance, "_adapter_manager", self) + + def check_permissions(self): + return all( + [check_permission(permission) for permission in self.runtime_permissions] + ) + + def request_permissions(self): + if self.is_permissions_requested: + return + self.is_permissions_requested = True + if not self.is_service_context: + Logger.debug("Request runtime permissions") + request_permissions( + self.runtime_permissions, + self.on_runtime_permissions, + ) + else: + Logger.error("Required permissions are not granted for service") + + def request_adapter(self): + if self.is_adapter_requested: + return + self.is_adapter_requested = True + self.ble.getAdapter(self.enable_ble_code) + + def rollback(self): + self._execute_operations(self.rollback_handlers) + + def execute(self, operation): + if self.adapter: + # execute immediately, if adapter is enabled + return operation() + self.operations.append(operation) + self.execute_operations() + + def execute_operations(self): + if self.has_permissions: + if self.adapter: + self._execute_operations(self.operations) + else: + self.request_adapter() + else: + self.request_permissions() + + def _execute_operations(self, operations): + self.operations = [] + self.rollback_handlers = [] + for operation in operations: + try: + operation() + except Exception as exc: + Logger.exception(exc) + + def on_runtime_permissions(self, permissions, grant_results): + granted = all(grant_results) + self.is_permissions_granted = granted + self.is_permissions_requested = False # allow future invocations + if granted: + Logger.debug("Required permissions are granted") + self.execute_operations() + else: + Logger.error("Required permissions are not granted") + self.rollback() + + def on_activity_result(self, requestCode, resultCode, intent): + if requestCode == self.enable_ble_code: + enabled = resultCode == Activity.RESULT_OK + self.is_adapter_requested = False # allow future invocations + if enabled: + Logger.debug("BLE adapter is enabled") + self.execute_operations() + else: + Logger.error("BLE adapter is not enabled") + self.rollback() diff --git a/libs/able/able/advertising.py b/libs/able/able/advertising.py new file mode 100644 index 0000000..1c61762 --- /dev/null +++ b/libs/able/able/advertising.py @@ -0,0 +1,330 @@ +"""BLE advertise operations.""" +from abc import abstractmethod +from dataclasses import dataclass +from enum import IntEnum +from typing import List, Optional, Union + +from jnius import JavaException, autoclass +from kivy.event import EventDispatcher + +from able.android.dispatcher import BluetoothDispatcher +from able.android.jni import PythonBluetoothAdvertiser +from able.utils import force_convertible_to_java_array + + +AdvertiseDataBuilder = autoclass('android.bluetooth.le.AdvertiseData$Builder') +AdvertisingSet = autoclass('android.bluetooth.le.AdvertisingSet') +AdvertisingSetParametersBuilder = autoclass('android.bluetooth.le.AdvertisingSetParameters$Builder') +AndroidAdvertiseData = autoclass('android.bluetooth.le.AdvertiseData') +BluetoothLeAdvertiser = autoclass('android.bluetooth.le.BluetoothLeAdvertiser') +ParcelUuid = autoclass('android.os.ParcelUuid') + +BLEAdvertiser = autoclass('org.able.BLEAdvertiser') + + +class Interval(IntEnum): + """Advertising interval constants. + https://developer.android.com/reference/android/bluetooth/le/AdvertisingSetParameters#INTERVAL_HIGH + """ + MIN = 160 #: Minimum value for advertising interval, around every 100ms + MEDIUM = 400 #: Advertise on medium frequency, around every 250ms + HIGH = 1600 #: Advertise on low frequency, around every 1000ms + MAX = 16777215 #: Maximum value for advertising interval + + +class TXPower(IntEnum): + """Advertising transmission (TX) power level constants. + https://developer.android.com/reference/android/bluetooth/le/AdvertisingSetParameters#TX_POWER_HIGH + """ + MIN = -127 #: Minimum value for TX power + ULTRA_LOW = -21 #: Advertise using the lowest TX power level + LOW = -15 #: Advertise using the low TX power level + MEDIUM = -7 #: Advertise using the medium TX power level + MAX = 1 #: Maximum value for TX power + + +class Status: + """Advertising operation status constants. + https://developer.android.com/reference/android/bluetooth/le/AdvertisingSetCallback#constants + """ + SUCCESS = 0 + DATA_TOO_LARGE = 1 + TOO_MANY_ADVERTISERS = 2 + ALREADY_STARTED = 3 + INTERNAL_ERROR = 4 + FEATURE_UNSUPPORTED = 5 + + +@dataclass +class ADStructure: + + @abstractmethod + def add_payload(self, builder: AdvertiseDataBuilder): + pass + + +class DeviceName(ADStructure): + """Include device name (complete local name) in advertise packet.""" + + def add_payload(self, builder): + builder.setIncludeDeviceName(True) + + +class TXPowerLevel(ADStructure): + """Include transmission power level in the advertise packet.""" + + def add_payload(self, builder): + builder.setIncludeTxPowerLevel(True) + + +@dataclass +class ServiceUUID(ADStructure): + """Service UUID to advertise. + + :param uid: UUID to be advertised + """ + uid: str + + def add_payload(self, builder): + builder.addServiceUuid( + ParcelUuid.fromString(self.uid) + ) + + +@dataclass +class ServiceData(ADStructure): + """Service data to advertise. + + :param uid: UUID of the service the data is associated with + :param data: Service data + """ + + uid: str + data: Union[list, tuple, bytes, bytearray] + + def add_payload(self, builder): + builder.addServiceData( + ParcelUuid.fromString(self.uid), + force_convertible_to_java_array(self.data) + ) + + +@dataclass +class ManufacturerData(ADStructure): + """Manufacturer specific data to advertise. + + :param id: Manufacturer ID + :param data: Manufacturer specific data + """ + id: int + data: Union[list, tuple, bytes, bytearray] + + def add_payload(self, builder): + builder.addManufacturerData( + self.id, + force_convertible_to_java_array(self.data) + ) + + +class AdvertiseData: + """Builder for data payload to be advertised. + + :param payload: List of AD structures to include in advertisement + + >>> AdvertiseData(DeviceName(), ManufacturerData(10, b'specific data')) + [DeviceName(), ManufacturerData(id=10, data=b'specific data')] + """ + + def __init__(self, *payload: List[ADStructure]): + self.payload = payload + self.data = self.build() + + def __repr__(self): + sections = ", ".join(repr(ad) for ad in self.payload) + return f"[{sections}]" + + def build(self) -> AndroidAdvertiseData: + builder = AdvertiseDataBuilder() + for ad in self.payload: + ad.add_payload(builder) + return builder.build() + + +class Advertiser(EventDispatcher): + """Base class for BLE advertise operations. + + :param ble: BLE interface instance + :param data: Advertisement data to be broadcasted + :param scan_data: Scan response associated with the advertisement data + :param interval: Advertising interval + ``_ + :param tx_power: Transmission power level + ``_ + + >>> Advertiser( + ... ble=BluetoothDispatcher(), + ... data=AdvertiseData(DeviceName()), + ... scan_data=AdvertiseData(TXPowerLevel()), + ... interval=Interval.MIN, + ... tx_power=TXPower.MAX + ... ) #doctest: +ELLIPSIS + + """ + + __events__ = ( + 'on_advertising_started', + 'on_advertising_stopped', + 'on_advertising_enabled', + 'on_advertising_data_set', + 'on_scan_response_data_set', + 'on_advertising_parameters_updated', + 'on_advertising_set_changed', + ) + + def __init__( + self, + ble: BluetoothDispatcher, + data: AdvertiseData = None, + scan_data: AdvertiseData = None, + interval: int = Interval.HIGH, + tx_power: int = TXPower.MEDIUM, + ): + self._ble = ble + self._data = data + self._scan_data = scan_data + self._interval = interval + self._tx_power = tx_power + + self._events_interface = PythonBluetoothAdvertiser(self) + self._advertiser = BLEAdvertiser(self._events_interface) + self._callback_set = self._advertiser.mCallbackSet + self._advertising_set = None + + @property + def data(self): + """ + :setter: Update advertising data + :type: Optional[AdvertiseData] + """ + return self._data + + @data.setter + def data(self, value): + self._data = value + self._update_advertising_set() + + @property + def scan_data(self): + """ + :setter: Update the scan response + :type: Optional[AdvertiseData] + """ + return self._scan_data + + @scan_data.setter + def scan_data(self, value): + self._scan_data = value + self._update_advertising_set() + + @property + def interval(self): + """ + :setter: Update the advertising interval + :type: int + """ + return self._interval + + @interval.setter + def interval(self, value): + self._interval = value + self._update_advertising_set() + + @property + def tx_power(self): + """ + :setter: Update the transmission power level + :type: int + """ + return self._tx_power + + @tx_power.setter + def tx_power(self, value): + self._tx_power = value + self._update_advertising_set() + + @property + def bluetooth_le_advertiser(self) -> Optional[BluetoothLeAdvertiser]: + adapter = self._ble.adapter + return adapter and adapter.getBluetoothLeAdvertiser() + + @property + def parameters(self) -> AdvertisingSetParametersBuilder: + builder = AdvertisingSetParametersBuilder() + builder.setLegacyMode(True) \ + .setConnectable(False) \ + .setScannable(True) \ + .setInterval(self._interval) \ + .setTxPowerLevel(self._tx_power) + return builder.build() + + def start(self): + """Start advertising. + + Start a system activity that allows the user to turn on Bluetooth if Bluetooth is not enabled. + """ + if not self._advertising_set: + self._ble._start_advertising(self) + + def stop(self): + """Stop advertising.""" + advertiser = self.bluetooth_le_advertiser + if advertiser: + advertiser.stopAdvertisingSet(self._callback_set) + + def on_advertising_started(self, advertising_set: AdvertisingSet, tx_power: int, status: Status): + """Handler for advertising start operation (onAdvertisingSetStarted). + """ + + def on_advertising_stopped(self, advertising_set: AdvertisingSet): + """Handler for advertising stop operation (onAdvertisingSetStopped).""" + + def on_advertising_enabled(self, advertising_set: AdvertisingSet, enable: bool, status: Status): + """Handler for advertising enable/disable operation (onAdvertisingEnabled).""" + + def on_advertising_data_set(self, advertising_set: AdvertisingSet, status: Status): + """Handler for data set operation (onAdvertisingDataSet).""" + + def on_scan_response_data_set(self, advertising_set: AdvertisingSet, status: Status): + """Handler for scan response data set operation (onScanResponseDataSet).""" + + def on_advertising_parameters_updated(self, advertising_set: AdvertisingSet, tx_power: int, status: Status): + """Handler for parameters set operation (onAdvertisingParametersUpdated).""" + + def on_advertising_set_changed(self, advertising_set): + self._advertising_set = advertising_set + + def _start(self): + advertiser = self.bluetooth_le_advertiser + if advertiser: + self._callback_set = self._advertiser.createCallback() + try: + advertiser.startAdvertisingSet( + self.parameters, + self._data and self._data.data, + self._scan_data and self._scan_data.data, + None, # periodicParameters + None, # periodicData + self._callback_set + ) + except JavaException as exc: + if exc.classname == 'java.lang.IllegalArgumentException' and \ + exc.innermessage.endswith('data too big'): + self.dispatch('on_advertising_started', None, 0, Status.DATA_TOO_LARGE) + raise + + def _update_advertising_set(self): + advertising_set = self._advertising_set + if advertising_set: + advertising_set.setAdvertisingParameters(self.parameters) + advertising_set.setScanResponseData(self._scan_data and self._scan_data.data) + advertising_set.setAdvertisingData(self._data and self._data.data) diff --git a/libs/able/able/android/__init__.py b/libs/able/able/android/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/libs/able/able/android/dispatcher.py b/libs/able/able/android/dispatcher.py new file mode 100644 index 0000000..ea90759 --- /dev/null +++ b/libs/able/able/android/dispatcher.py @@ -0,0 +1,105 @@ +from jnius import JavaException, autoclass +from kivy.logger import Logger + +from able.adapter import ( + AdapterManager, + require_bluetooth_enabled, + set_adapter_failure_rollback, +) +from able.android.jni import PythonBluetooth +from able.dispatcher import BluetoothDispatcherBase +from able.scan_settings import ScanSettingsBuilder + +ArrayList = autoclass("java.util.ArrayList") + +try: + BLE = autoclass("org.able.BLE") +except: + Logger.error( + "able_recipe: Failed to load Java class org.able.BLE. Possible build error." + ) + raise +else: + Logger.info("able_recipe: org.able.BLE Java class loaded") + +BluetoothAdapter = autoclass("android.bluetooth.BluetoothAdapter") +BluetoothDevice = autoclass("android.bluetooth.BluetoothDevice") +BluetoothGattDescriptor = autoclass("android.bluetooth.BluetoothGattDescriptor") + +ENABLE_NOTIFICATION_VALUE = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE +ENABLE_INDICATION_VALUE = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE +DISABLE_NOTIFICATION_VALUE = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE + + +class BluetoothDispatcher(BluetoothDispatcherBase): + @property + @require_bluetooth_enabled + def adapter(self): + return AdapterManager.get_attached_manager(self).adapter + + @property + def bonded_devices(self): + ble_types = (BluetoothDevice.DEVICE_TYPE_LE, BluetoothDevice.DEVICE_TYPE_DUAL) + adapter = self.adapter + devices = adapter.getBondedDevices().toArray() if adapter else [] + return [dev for dev in devices if dev.getType() in ble_types] + + def _set_ble_interface(self): + self._events_interface = PythonBluetooth(self) + self._ble = BLE(self._events_interface) + + @set_adapter_failure_rollback( + lambda self: self.dispatch("on_scan_started", success=False) + ) + @require_bluetooth_enabled + def start_scan(self, filters=None, settings=None): + filters_array = ArrayList() + for f in filters or []: + filters_array.add(f.build()) + if not settings: + settings = ScanSettingsBuilder() + try: + settings = settings.build() + except AttributeError: + pass + self._ble.startScan(self.enable_ble_code, filters_array, settings) + + def stop_scan(self): + self._ble.stopScan() + + @require_bluetooth_enabled + def connect_by_device_address(self, address: str, autoconnect: bool = False): + address = address.upper() + if not BluetoothAdapter.checkBluetoothAddress(address): + raise ValueError(f"{address} is not a valid Bluetooth address") + adapter = self.adapter + if adapter: + self.connect_gatt(adapter.getRemoteDevice(address), autoconnect) + + @require_bluetooth_enabled + def enable_notifications(self, characteristic, enable=True, indication=False): + if not self.gatt.setCharacteristicNotification(characteristic, enable): + return False + + if not enable: + # DISABLE_NOTIFICAITON_VALUE is for disabling + # both notifications and indications + descriptor_value = DISABLE_NOTIFICATION_VALUE + elif indication: + descriptor_value = ENABLE_INDICATION_VALUE + else: + descriptor_value = ENABLE_NOTIFICATION_VALUE + + for descriptor in characteristic.getDescriptors().toArray(): + self.write_descriptor(descriptor, descriptor_value) + return True + + @require_bluetooth_enabled + def _start_advertising(self, advertiser): + advertiser._start() + + @require_bluetooth_enabled + def _set_name(self, value): + adapter = self.adapter + if adapter: + self.adapter.setName(value) diff --git a/libs/able/able/android/jni.py b/libs/able/able/android/jni.py new file mode 100644 index 0000000..bac7c50 --- /dev/null +++ b/libs/able/able/android/jni.py @@ -0,0 +1,151 @@ +from able import GATT_SUCCESS +from able.structures import Advertisement, Services +from jnius import PythonJavaClass, java_method +from kivy.logger import Logger + + +class PythonBluetooth(PythonJavaClass): + __javainterfaces__ = ['org.able.PythonBluetooth'] + __javacontext__ = 'app' + + def __init__(self, dispatcher): + super(PythonBluetooth, self).__init__() + self.dispatcher = dispatcher + + @java_method('(Ljava/lang/String;)V') + def on_error(self, msg): + Logger.debug("on_error") + self.dispatcher.dispatch('on_error', msg) + + @java_method('(Landroid/bluetooth/le/ScanResult;)V') + def on_scan_result(self, result): + device = result.getDevice() # type: android.bluetooth.BluetoothDevice + record = result.getScanRecord() # type: android.bluetooth.le.ScanRecord + if record: + self.dispatcher.dispatch( + 'on_device', + device, + result.getRssi(), + Advertisement(record.getBytes()) + ) + else: + Logger.warning( + "Scan result for device without the scan record: %s", + device + ) + + @java_method('(Z)V') + def on_scan_started(self, success): + Logger.debug("on_scan_started") + self.dispatcher.dispatch('on_scan_started', success) + + @java_method('()V') + def on_scan_completed(self): + Logger.debug("on_scan_completed") + self.dispatcher.dispatch('on_scan_completed') + + @java_method('(II)V') + def on_connection_state_change(self, status, state): + Logger.debug("on_connection_state_change status={} state: {}".format( + status, state)) + self.dispatcher.dispatch('on_connection_state_change', status, state) + + @java_method('(I)V') + def on_bluetooth_adapter_state_change(self, state): + Logger.debug("on_bluetooth_adapter_state_change state: {}".format(state)) + self.dispatcher.dispatch('on_bluetooth_adapter_state_change', state) + + @java_method('(ILjava/util/List;)V') + def on_services(self, status, services): + services_dict = Services() + if status == GATT_SUCCESS: + for service in services.toArray(): + service_uuid = service.getUuid().toString() + Logger.debug("Service discovered: {}".format(service_uuid)) + services_dict[service_uuid] = {} + for c in service.getCharacteristics().toArray(): + characteristic_uuid = c.getUuid().toString() + Logger.debug("Characteristic discovered: {}".format( + characteristic_uuid)) + services_dict[service_uuid][characteristic_uuid] = c + self.dispatcher.dispatch('on_services', status, services_dict) + + @java_method('(Landroid/bluetooth/BluetoothGattCharacteristic;)V') + def on_characteristic_changed(self, characteristic): + # uuid = characteristic.getUuid().toString() + self.dispatcher.dispatch('on_characteristic_changed', characteristic) + + @java_method('(Landroid/bluetooth/BluetoothGattCharacteristic;I)V') + def on_characteristic_read(self, characteristic, status): + self.dispatcher.dispatch('on_gatt_release') + # uuid = characteristic.getUuid().toString() + self.dispatcher.dispatch('on_characteristic_read', + characteristic, + status) + + @java_method('(Landroid/bluetooth/BluetoothGattCharacteristic;I)V') + def on_characteristic_write(self, characteristic, status): + self.dispatcher.dispatch('on_gatt_release') + # uuid = characteristic.getUuid().toString() + self.dispatcher.dispatch('on_characteristic_write', + characteristic, + status) + + @java_method('(Landroid/bluetooth/BluetoothGattDescriptor;I)V') + def on_descriptor_read(self, descriptor, status): + self.dispatcher.dispatch('on_gatt_release') + # characteristic = descriptor.getCharacteristic() + # uuid = characteristic.getUuid().toString() + self.dispatcher.dispatch('on_descriptor_read', descriptor, status) + + @java_method('(Landroid/bluetooth/BluetoothGattDescriptor;I)V') + def on_descriptor_write(self, descriptor, status): + self.dispatcher.dispatch('on_gatt_release') + # characteristic = descriptor.getCharacteristic() + # uuid = characteristic.getUuid().toString() + self.dispatcher.dispatch('on_descriptor_write', descriptor, status) + + @java_method('(II)V') + def on_rssi_updated(self, rssi, status): + self.dispatcher.dispatch('on_gatt_release') + self.dispatcher.dispatch('on_rssi_updated', rssi, status) + + @java_method('(II)V') + def on_mtu_changed(self, mtu, status): + self.dispatcher.dispatch('on_gatt_release') + self.dispatcher.dispatch('on_mtu_changed', mtu, status) + + +class PythonBluetoothAdvertiser(PythonJavaClass): + __javainterfaces__ = ['org.able.PythonBluetoothAdvertiser'] + __javacontext__ = 'app' + + def __init__(self, dispatcher): + super().__init__() + self.dispatcher = dispatcher + + @java_method('(Landroid/bluetooth/le/AdvertisingSet;II)V') + def on_advertising_started(self, advertising_set, tx_power, status): + self.dispatcher.dispatch('on_advertising_set_changed', advertising_set) + self.dispatcher.dispatch('on_advertising_started', advertising_set, tx_power, status) + + @java_method('(Landroid/bluetooth/le/AdvertisingSet;)V') + def on_advertising_stopped(self, advertising_set): + self.dispatcher.dispatch('on_advertising_set_changed', None) + self.dispatcher.dispatch('on_advertising_stopped', advertising_set) + + @java_method('(Landroid/bluetooth/le/AdvertisingSet;BI)V') + def on_advertising_enabled(self, advertising_set, enable, status): + self.dispatcher.dispatch('on_advertising_enabled', advertising_set, enable, status) + + @java_method('(Landroid/bluetooth/le/AdvertisingSet;I)V') + def on_advertising_data_set(self, advertising_set, status): + self.dispatcher.dispatch('on_advertising_data_set', advertising_set, status) + + @java_method('(Landroid/bluetooth/le/AdvertisingSet;I)V') + def on_scan_response_data_set(self, advertising_set, status): + self.dispatcher.dispatch('on_scan_response_data_set', advertising_set, status) + + @java_method('(Landroid/bluetooth/le/AdvertisingSet;II)V') + def on_advertising_parameters_updated(self, advertising_set, tx_power, status): + self.dispatcher.dispatch('on_advertising_parameters_updated', advertising_set, tx_power, status) diff --git a/libs/able/able/dispatcher.py b/libs/able/able/dispatcher.py new file mode 100644 index 0000000..7efff78 --- /dev/null +++ b/libs/able/able/dispatcher.py @@ -0,0 +1,371 @@ +from typing import List, Optional + +from kivy.event import EventDispatcher +from kivy.logger import Logger + +from able import WriteType +from able.adapter import AdapterManager +from able.filters import Filter +from able.permissions import DEFAULT_RUNTIME_PERMISSIONS +from able.queue import BLEQueue, ble_task, ble_task_done +from able.scan_settings import ScanSettingsBuilder +from able.utils import force_convertible_to_java_array + + +class BLEError: + """Raise Exception on attribute access""" + + def __init__(self, msg): + self.msg = msg + + def __getattr__(self, name): + raise Exception(self.msg) + + +class BluetoothDispatcherBase(EventDispatcher): + __events__ = ( + "on_device", + "on_scan_started", + "on_scan_completed", + "on_services", + "on_connection_state_change", + "on_bluetooth_adapter_state_change", + "on_characteristic_changed", + "on_characteristic_read", + "on_characteristic_write", + "on_descriptor_read", + "on_descriptor_write", + "on_gatt_release", + "on_error", + "on_rssi_updated", + "on_mtu_changed", + ) + queue_class = BLEQueue + + def __init__( + self, + queue_timeout: float = 0.5, + enable_ble_code: int = 0xAB1E, + runtime_permissions: Optional[list[str]] = None, # DEFAULT_RUNTIME_PERMISSIONS + ): + super(BluetoothDispatcherBase, self).__init__() + self.queue_timeout = queue_timeout + self.enable_ble_code = enable_ble_code + self.runtime_permissions = [ + str(permission) + for permission in ( + runtime_permissions + if runtime_permissions is not None + else DEFAULT_RUNTIME_PERMISSIONS + ) + ] + self._remote_device_address = None + self._set_ble_interface() + self._set_queue() + self._set_adapter_manager() + + def _set_ble_interface(self): + self._ble = BLEError("BLE is not implemented for platform") + + def _set_queue(self): + self.queue = self.queue_class(timeout=self.queue_timeout) + + def _set_adapter_manager(self): + AdapterManager( + ble=self._ble, + enable_ble_code=self.enable_ble_code, + runtime_permissions=self.runtime_permissions, + ).install(self) + + def _check_runtime_permissions(self): + return True + + def _request_runtime_permissions(self): + pass + + @property + def adapter(self) -> Optional["android.bluetooth.BluetoothAdapter"]: + """Local device Bluetooth adapter. + Could be `None` if adapter is not enabled or access to the adapter is not granted yet. + + :type: `BluetoothAdapter `_ + `Java object `_ + """ + + @property + def gatt(self): + """GATT profile of the connected device + + :type: BluetoothGatt Java object + """ + return self._ble.getGatt() + + @property + def bonded_devices(self): + """List of Java `android.bluetooth.BluetoothDevice` objects of paired BLE devices. + + :type: List[BluetoothDevice] + """ + return [] + + @property + def name(self): + """Name of the Bluetooth adapter. + + :setter: Set name of the Bluetooth adapter + :type: Optional[str] + """ + adapter = self.adapter + return adapter and adapter.getName() + + @name.setter + def name(self, value): + self._set_name(value) + + def _set_name(self, value): + pass + + def set_queue_timeout(self, timeout): + """Change the BLE operations queue timeout""" + self.queue_timeout = timeout + self.queue.set_timeout(timeout) + + def start_scan( + self, + filters: Optional[List[Filter]] = None, + settings: Optional[ScanSettingsBuilder] = None, + ): + """Start a scan for devices. + The status of the scan start are reported with + :func:`scan_started ` event. + + :param filters: list of filters to restrict scan results. + Advertising record is considered matching the filters + if it matches any of the :class:`able.filters.Filter` in the list. + :param settings: scan settings + """ + pass + + def stop_scan(self): + """Stop the ongoing scan for devices.""" + pass + + def connect_by_device_address(self, address: str, autoconnect: bool = False): + """Connect to GATT Server of the device with a given Bluetooth hardware address, without scanning. + + :param address: Bluetooth hardware address string in "XX:XX:XX:XX:XX:XX" format + :param autoconnect: If True, automatically reconnects when available. + False = direct connect (default). + :raises: + ValueError: if `address` is not a valid Bluetooth address + """ + pass + + def connect_gatt(self, device, autoconnect: bool = False): + """Connect to GATT Server hosted by device + + :param device: BluetoothDevice Java object + :param autoconnect: If True, automatically reconnects when available. + False = direct connect (default). + """ + self._ble.connectGatt(device, autoconnect) + + def close_gatt(self): + """Close current GATT client""" + self._ble.closeGatt() + + def discover_services(self): + """Discovers services offered by a remote device. + The status of the discovery reported with + :func:`services ` event. + + :return: true, if the remote services discovery has been started + """ + return self.gatt.discoverServices() + + def enable_notifications(self, characteristic, enable=True, indication=False): + """Enable/disable notifications or indications for a given characteristic + + :param characteristic: BluetoothGattCharacteristic Java object + :param enable: enable notifications if True, else disable notifications + :param indication: handle indications instead of notifications + :return: True, if the operation was initiated successfully + """ + return True + + @ble_task + def write_descriptor(self, descriptor, value): + """Set and write the value of a given descriptor to the associated + remote device + + :param descriptor: BluetoothGattDescriptor Java object + :param value: value to write + """ + if not descriptor.setValue(force_convertible_to_java_array(value)): + Logger.error("Error on set descriptor value") + return + if not self.gatt.writeDescriptor(descriptor): + Logger.error("Error on descriptor write") + + @ble_task + def write_characteristic( + self, characteristic, value, write_type: Optional[WriteType] = None + ): + """Write a given characteristic value to the associated remote device + + :param characteristic: BluetoothGattCharacteristic Java object + :param value: value to write + :param write_type: specific write type to set for the characteristic + """ + self._ble.writeCharacteristic( + characteristic, force_convertible_to_java_array(value), int(write_type or 0) + ) + + @ble_task + def read_characteristic(self, characteristic): + """Read a given characteristic from the associated remote device + + :param characteristic: BluetoothGattCharacteristic Java object + """ + self._ble.readCharacteristic(characteristic) + + @ble_task + def update_rssi(self): + """Triggers an update for the RSSI from the associated remote device""" + self._ble.readRemoteRssi() + + @ble_task + def request_mtu(self, mtu: int): + """Request to change the ATT Maximum Transmission Unit value + + :param value: new MTU size + """ + self.gatt.requestMtu(mtu) + + def on_error(self, msg): + """Error handler + + :param msg: error message + """ + self._ble = BLEError(msg) # Exception for calls from another threads + raise Exception(msg) + + @ble_task_done + def on_gatt_release(self): + """`gatt_release` event handler. + Event is dispatched at every read/write completed operation + """ + pass + + def on_scan_started(self, success): + """`scan_started` event handler + + :param success: true, if scan was started successfully + """ + pass + + def on_scan_completed(self): + """`scan_completed` event handler""" + pass + + def on_device(self, device, rssi, advertisement): + """`device` event handler. + Event is dispatched when device is found during a scan. + + :param device: BluetoothDevice Java object + :param rssi: the RSSI value for the remote device + :param advertisement: :class:`Advertisement` data record + """ + pass + + def on_connection_state_change(self, status, state): + """`connection_state_change` event handler + + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + :param state: STATE_CONNECTED or STATE_DISCONNECTED + """ + pass + + def on_bluetooth_adapter_state_change(self, state): + """`bluetooth_adapter_state_change` event handler + Allows the user to detect when bluetooth adapter is turned on/off. + + :param state: STATE_OFF, STATE_TURNING_OFF, STATE_ON, STATE_TURNING_ON + """ + + def on_services(self, services, status): + """`services` event handler + + :param services: :class:`Services` dict filled with discovered + characteristics + (BluetoothGattCharacteristic Java objects) + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + """ + pass + + def on_characteristic_changed(self, characteristic): + """`characteristic_changed` event handler + + :param characteristic: BluetoothGattCharacteristic Java object + """ + pass + + def on_characteristic_read(self, characteristic, status): + """`characteristic_read` event handler + + :param characteristic: BluetoothGattCharacteristic Java object + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + """ + pass + + def on_characteristic_write(self, characteristic, status): + """`characteristic_write` event handler + + :param characteristic: BluetoothGattCharacteristic Java object + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + """ + pass + + def on_descriptor_read(self, descriptor, status): + """`descriptor_read` event handler + + :param descriptor: BluetoothGattDescriptor Java object + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + """ + pass + + def on_descriptor_write(self, descriptor, status): + """`descriptor_write` event handler + + :param descriptor: BluetoothGattDescriptor Java object + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + """ + pass + + def on_rssi_updated(self, rssi, status): + """`onReadRemoteRssi` event handler. + Event is dispatched at every RSSI update completed operation, + reporting a RSSI value for a remote device connection. + + :param rssi: integer containing RSSI value in dBm + :param status: status of the operation, + `GATT_SUCCESS` if the operation succeeds + """ + pass + + def on_mtu_changed(self, mtu, status): + """`onMtuChanged` event handler + Event is dispatched when MTU for a remote device has changed, + reporting a new MTU size. + + :param mtu: integer containing the new MTU size + :param status: status of the operation, + `GATT_SUCCESS` if the MTU has been changed successfully + """ + pass diff --git a/libs/able/able/filters.py b/libs/able/able/filters.py new file mode 100644 index 0000000..0b362f3 --- /dev/null +++ b/libs/able/able/filters.py @@ -0,0 +1,237 @@ +"""BLE scanning filters, +wrappers for Java class `android.bluetooth.le.ScanFilter.Builder` +https://developer.android.com/reference/android/bluetooth/le/ScanFilter.Builder +""" +from abc import abstractmethod +from dataclasses import dataclass, field +from typing import List, Union +import uuid + +from jnius import autoclass + +ParcelUuid = autoclass('android.os.ParcelUuid') +BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter') +ScanFilter = autoclass('android.bluetooth.le.ScanFilter') +ScanFilterBuilder = autoclass('android.bluetooth.le.ScanFilter$Builder') + + +@dataclass +class Filter: + """Base class for BLE scanning fiters. + + >>> # Filters of different kinds could be ANDed to set multiple conditions. + >>> # Both device name and address required: + >>> combined_filter = DeviceNameFilter("Example") & DeviceAddressFilter("01:02:03:AB:CD:EF") + + >>> DeviceNameFilter("Example1") & DeviceNameFilter("Example2") + Traceback (most recent call last): + ValueError: cannot combine filters of the same type + """ + + def __post_init__(self): + self.filters = [self] + + def __and__(self, other): + if type(self) in (type(f) for f in other.filters): + raise ValueError('cannot combine filters of the same type') + self.filters.extend(other.filters) + return self + + def build(self): + builder = ScanFilterBuilder() + for scan_filter in self.filters: + scan_filter.filter(builder) + return builder.build() + + @abstractmethod + def filter(self, builder): + pass + + +class EmptyFilter(Filter): + """Filter with no restrictions.""" + + def filter(self, builder): + pass + + +@dataclass +class DeviceAddressFilter(Filter): + """Set filter on device address. + Uses Java method `ScanFilter.Builder.setDeviceAddress`. + + :param address: Address in the format of "01:02:03:AB:CD:EF" + + >>> DeviceAddressFilter("01:02:03:AB:CD:EF") + DeviceAddressFilter(address='01:02:03:AB:CD:EF') + """ + address: str + + def __post_init__(self): + super().__post_init__() + if not BluetoothAdapter.checkBluetoothAddress(str(self.address)): + raise ValueError(f"{self.address} is not a valid Bluetooth address") + + def filter(self, builder): + builder.setDeviceAddress(str(self.address)) + + +@dataclass +class DeviceNameFilter(Filter): + """Set filter on device name. + Uses Java method `ScanFilter.Builder.setDeviceName`. + + :param name: Device name + """ + name: str + + def filter(self, builder): + builder.setDeviceName(str(self.name)) + + +@dataclass +class ManufacturerDataFilter(Filter): + """Set filter on manufacture data. + Uses Java method `ScanFilter.Builder.setManufacturerData`. + + :param id: Manufacturer ID + :param data: Manufacturer specific data + :param mask: bit mask for partial filtration of the `data`. For any bit in the mask, + set it to 1 if it needs to match the one in manufacturer data, + otherwise set it to 0 to ignore that bit. + + + >>> # Filter by just ID, ignoring the data: + >>> ManufacturerDataFilter(0x0AD0, []) + ManufacturerDataFilter(id=2768, data=[], mask=None) + + >>> ManufacturerDataFilter(0x0AD0, [0x2, 0x15, 0x8d]) + ManufacturerDataFilter(id=2768, data=[2, 21, 141], mask=None) + + >>> # With mask set to ignore the second data byte: + >>> ManufacturerDataFilter(0x0AD0, [0x2, 0, 0x8d], [0xff, 0, 0xff]) + ManufacturerDataFilter(id=2768, data=[2, 0, 141], mask=[255, 0, 255]) + + >>> ManufacturerDataFilter(0x0AD0, [0x2, 21, 0x8d], [0xff]) + Traceback (most recent call last): + ValueError: mask is shorter than the data + """ + id: int + data: Union[list, tuple, bytes, bytearray] + mask: List[int] = field(default_factory=lambda: None) + + def __post_init__(self): + super().__post_init__() + if self.mask and len(self.mask) < len(self.data): + raise ValueError('mask is shorter than the data') + + def filter(self, builder): + if self.mask: + builder.setManufacturerData(self.id, self.data, self.mask) + else: + builder.setManufacturerData(self.id, self.data) + + +@dataclass +class ServiceDataFilter(Filter): + """Set filter on service data. + Uses Java method `ScanFilter.Builder.setServiceData`. + + :param uid: UUID of the service in the format of + "0000180f-0000-1000-8000-00805f9b34fb" + :param data: service data + :param mask: bit mask for partial filtration of the `data`. For any bit in the mask, + set it to 1 if it needs to match the one in service data, + otherwise set it to 0 to ignore that bit. + + >>> ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", []) + ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[], mask=None) + + >>> # With mask set to ignore the first data byte: + >>> ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", [0, 0x11], [0, 0xff]) + ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[0, 17], mask=[0, 255]) + + >>> ServiceDataFilter("0000180f", []) + Traceback (most recent call last): + ValueError: badly formed hexadecimal UUID string + + >>> ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", [0x12, 0x34], [0xff]) + Traceback (most recent call last): + ValueError: mask is shorter than the data + """ + uid: str + data: Union[list, tuple, bytes, bytearray] + mask: List[int] = field(default_factory=lambda: None) + + def __post_init__(self): + super().__post_init__() + # validate UUID value + uuid.UUID(self.uid) + if self.mask and len(self.mask) < len(self.data): + raise ValueError('mask is shorter than the data') + + def filter(self, builder): + uid = ParcelUuid.fromString(self.uid) + if self.mask: + builder.setServiceData(uid, self.data, self.mask) + else: + builder.setServiceData(uid, self.data) + + +@dataclass +class ServiceSolicitationFilter(Filter): + """Set filter on service solicitation uuid. + Uses Java method `ScanFilter.Builder.setServiceSolicitation`. + + :param uid: UUID of the service in the format of + "0000180f-0000-1000-8000-00805f9b34fb" + """ + uid: str + + def filter(self, builder): + uid = ParcelUuid.fromString(self.uid) + builder.setServiceSolicitation(uid) + + +@dataclass +class ServiceUUIDFilter(Filter): + """Set filter on service uuid. + Uses Java method `ScanFilter.Builder.setServiceUuid`. + + :param uid: UUID of the service in the format of + "0000180f-0000-1000-8000-00805f9b34fb" + :mask: bit mask for partial filtration of the UUID, in the format of + "ffffffff-0000-0000-0000-ffffffffffff". Set any bit in the mask + to 1 to indicate a match is needed for the bit in `uid`, + and 0 to ignore that bit. + + >>> ServiceUUIDFilter('16fe0d00-c111-11e3-b8c8-0002a5d5c51b') + ServiceUUIDFilter(uid='16fe0d00-c111-11e3-b8c8-0002a5d5c51b', mask=None) + + >>> ServiceUUIDFilter( + ... '16fe0d00-c111-11e3-b8c8-0002a5d5c51b', + ... 'ffffffff-0000-0000-0000-000000000000' + ... ) #doctest: +ELLIPSIS + ServiceUUIDFilter(uid='16fe0d00-...', mask='ffffffff-...') + + >>> ServiceUUIDFilter('123') + Traceback (most recent call last): + ValueError: badly formed hexadecimal UUID string + """ + uid: str + mask: str = None + + def __post_init__(self): + super().__post_init__() + # validate UUID values + uuid.UUID(self.uid) + if self.mask: + uuid.UUID(self.mask) + + def filter(self, builder): + uid = ParcelUuid.fromString(self.uid) + if self.mask: + mask = ParcelUuid.fromString(self.mask) + builder.setServiceUuid(uid, mask) + else: + builder.setServiceUuid(uid) diff --git a/libs/able/able/permissions.py b/libs/able/able/permissions.py new file mode 100644 index 0000000..862e79e --- /dev/null +++ b/libs/able/able/permissions.py @@ -0,0 +1,53 @@ +"""Before executing, all :class:`BluetoothDispatcher ` methods that requires Bluetooth adapter +(`start_scan`, `connect_by_device_address`, `enable_notifications`, `adapter` property ...), +are asking the user to: + +#. grant runtime permissions, +#. turn on Bluetooth adapter. + +The list of requested runtime permissions varies depending on the level of the target Android API level: + +* target API level <=30: ACCESS_FINE_LOCATION - to obtain BLE scan results +* target API level >= 31: + + * BLUETOOTH_CONNECT - to enable adapter and to connect to devices + * BLUETOOTH_SCAN - to start the scan + * ACCESS_FINE_LOCATION - to detect beacons during the scan + * BLUETOOTH_ADVERTISE - to be able to advertise to nearby Bluetooth devices + +Requested permissions list can be changed with the `BluetoothDispatcher.runtime_permissions` parameter. +""" +from jnius import autoclass + +SDK_INT = int(autoclass("android.os.Build$VERSION").SDK_INT) + + +class Permission: + """ + String constants values for BLE-related permissions. + https://developer.android.com/reference/android/Manifest.permission + """ + + ACCESS_BACKGROUND_LOCATION = "android.permission.ACCESS_BACKGROUND_LOCATION" + ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION" + BLUETOOTH_ADVERTISE = "android.permission.BLUETOOTH_ADVERTISE" + BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT" + BLUETOOTH_SCAN = "android.permission.BLUETOOTH_SCAN" + + +if SDK_INT >= 31: + # API level 31 (Android 12) introduces new permissions + DEFAULT_RUNTIME_PERMISSIONS = [ + Permission.BLUETOOTH_ADVERTISE, + Permission.BLUETOOTH_CONNECT, + Permission.BLUETOOTH_SCAN, + # ACCESS_FINE_LOCATION is not mandatory for scan, + # but required to discover beacons + Permission.ACCESS_FINE_LOCATION, + ] +else: + # For API levels 29-30, + # ACCESS_FINE_LOCATION permission is needed to obtain BLE scan results + DEFAULT_RUNTIME_PERMISSIONS = [ + Permission.ACCESS_FINE_LOCATION, + ] diff --git a/libs/able/able/queue.py b/libs/able/able/queue.py new file mode 100644 index 0000000..8d30124 --- /dev/null +++ b/libs/able/able/queue.py @@ -0,0 +1,90 @@ +import threading +from functools import wraps, partial +try: + from queue import Empty, Queue +except ImportError: + from Queue import Empty, Queue +from kivy.clock import Clock +from kivy.logger import Logger + + +def ble_task(method): + """ + Enque method + """ + @wraps(method) + def wrapper(obj, *args, **kwargs): + task = partial(method, obj, *args, **kwargs) + obj.queue.enque(task) + return wrapper + + +def ble_task_done(method): + @wraps(method) + def wrapper(obj, *args, **kwargs): + obj.queue.done(*args, **kwargs) + method(obj, *args, **kwargs) + return wrapper + + +def with_lock(method): + @wraps(method) + def wrapped(obj, *args, **kwargs): + locked = obj.lock.acquire(False) + if locked: + try: + return method(obj, *args, **kwargs) + finally: + obj.lock.release() + return wrapped + + +class BLEQueue(object): + + def __init__(self, timeout=0): + self.lock = threading.Lock() + self.ready = True + self.queue = Queue() + self.set_timeout(timeout) + + def set_timeout(self, timeout): + Logger.debug("set queue timeout to {}".format(timeout)) + self.timeout = timeout + self.timeout_event = Clock.schedule_once( + self.on_timeout, self.timeout or 0) + self.timeout_event.cancel() + + def enque(self, task): + queue = self.queue + if self.timeout == 0: + self.execute_task(task) + else: + queue.put_nowait(task) + self.execute_next() + + @with_lock + def execute_next(self, ready=False): + if ready: + self.ready = True + elif not self.ready: + return + try: + task = self.queue.get_nowait() + except Empty: + return + self.ready = False + if task is not None: + self.execute_task(task) + + def done(self, *args, **kwargs): + self.timeout_event.cancel() + self.ready = True + self.execute_next() + + def on_timeout(self, *args, **kwargs): + self.done() + + def execute_task(self, task): + if self.timeout and self.timeout_event: + self.timeout_event() + task() diff --git a/libs/able/able/scan_settings.py b/libs/able/able/scan_settings.py new file mode 100644 index 0000000..e5b1201 --- /dev/null +++ b/libs/able/able/scan_settings.py @@ -0,0 +1,20 @@ +"""BLE scanning settings. +""" +from jnius import autoclass +from kivy.utils import platform + + +if platform != 'android': + class ScanSettings: + """PyJNIus wrapper for Java class `android.bluetooth.le.ScanSettings`. + https://developer.android.com/reference/android/bluetooth/le/ScanSettings + """ + + class ScanSettingsBuilder: + """PyJNIus wrapper for Java class `android.bluetooth.le.ScanSettings.Builder`. + https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder + """ + +else: + ScanSettings = autoclass('android.bluetooth.le.ScanSettings') + ScanSettingsBuilder = autoclass('android.bluetooth.le.ScanSettings$Builder') diff --git a/libs/able/able/src/org/able/BLE.java b/libs/able/able/src/org/able/BLE.java new file mode 100644 index 0000000..25771bb --- /dev/null +++ b/libs/able/able/src/org/able/BLE.java @@ -0,0 +1,283 @@ +package org.able; + +import android.app.Activity; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.pm.PackageManager; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothManager; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothProfile; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCallback; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; +import android.bluetooth.BluetoothGattService; +import android.bluetooth.le.BluetoothLeScanner; +import android.bluetooth.le.ScanCallback; +import android.bluetooth.le.ScanResult; + +import android.bluetooth.le.ScanFilter; +import android.bluetooth.le.ScanSettings; + +import android.os.Handler; +import android.util.Log; +import java.util.List; +import org.kivy.android.PythonActivity; +import org.kivy.android.PythonService; +import org.able.PythonBluetooth; + + +public class BLE { + private String TAG = "BLE-python"; + private PythonBluetooth mPython; + private Context mContext; + private BluetoothAdapter mBluetoothAdapter; + private BluetoothLeScanner mBluetoothLeScanner; + private BluetoothGatt mBluetoothGatt; + private List mBluetoothGattServices; + private boolean mScanning; + private boolean mIsServiceContext = false; + + public void showError(final String msg) { + Log.e(TAG, msg); + if (!mIsServiceContext) { PythonActivity.mActivity.toastError(TAG + " error. " + msg); } + mPython.on_error(msg); + } + + public BLE(PythonBluetooth python) { + mPython = python; + mContext = (Context) PythonActivity.mActivity; + mBluetoothGatt = null; + + if (mContext == null) { + Log.d(TAG, "Service context detected"); + mIsServiceContext = true; + mContext = (Context) PythonService.mService; + } + + if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + showError("Device does not support Bluetooth Low Energy."); + return; + } + + final BluetoothManager bluetoothManager = + (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); + mBluetoothAdapter = bluetoothManager.getAdapter(); + mContext.registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); + } + + public BluetoothAdapter getAdapter(int EnableBtCode) { + if (mBluetoothAdapter == null) { + showError("Device do not support Bluetooth Low Energy."); + return null; + } + if (!mBluetoothAdapter.isEnabled()) { + if (mIsServiceContext) { + showError("BLE adapter is not enabled"); + } else { + Log.d(TAG, "BLE adapter is not enabled"); + Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + PythonActivity.mActivity.startActivityForResult(enableBtIntent, EnableBtCode); + } + return null; + } + return mBluetoothAdapter; + } + + public BluetoothGatt getGatt() { + return mBluetoothGatt; + } + + public void startScan(int EnableBtCode, + List filters, + ScanSettings settings) { + Log.d(TAG, "startScan"); + BluetoothAdapter adapter = getAdapter(EnableBtCode); + if (adapter != null) { + Log.d(TAG, "BLE adapter is ready for scan"); + if (mBluetoothLeScanner == null) { + mBluetoothLeScanner = adapter.getBluetoothLeScanner(); + } + if (mBluetoothLeScanner != null) { + mScanning = false; + mBluetoothLeScanner.startScan(filters, settings, mScanCallback); + } else { + showError("Could not get BLE Scanner object."); + mPython.on_scan_started(false); + } + } + } + + public void stopScan() { + if (mBluetoothLeScanner != null) { + Log.d(TAG, "stopScan"); + mBluetoothLeScanner.stopScan(mScanCallback); + if (mScanning) { + mScanning = false; + mPython.on_scan_completed(); + } + } + } + + private final ScanCallback mScanCallback = + new ScanCallback() { + @Override + public void onScanResult(final int callbackType, final ScanResult result) { + if (!mScanning) { + mScanning = true; + Log.d(TAG, "BLE scan started successfully"); + mPython.on_scan_started(true); + } + if (mIsServiceContext) { + mPython.on_scan_result(result); + return; + } + PythonActivity.mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + mPython.on_scan_result(result); + } + }); + } + + @Override + public void onBatchScanResults(List results) { + Log.d(TAG, "onBatchScanResults"); + } + + @Override + public void onScanFailed(int errorCode) { + Log.e(TAG, "BLE Scan failed, error code:" + errorCode); + mPython.on_scan_started(false); + } + }; + + public void connectGatt(BluetoothDevice device) { + connectGatt(device, false); + } + + public void connectGatt(BluetoothDevice device, boolean autoConnect) { + Log.d(TAG, "connectGatt"); + if (mBluetoothGatt == null) { + mBluetoothGatt = device.connectGatt(mContext, autoConnect, mGattCallback, BluetoothDevice.TRANSPORT_LE); + } else { + Log.d(TAG, "BluetoothGatt object exists, use either closeGatt() to close Gatt or BluetoothGatt.connect() to re-connect"); + } + } + + public void closeGatt() { + Log.d(TAG, "closeGatt"); + if (mBluetoothGatt != null) { + mBluetoothGatt.close(); + mBluetoothGatt = null; + } + } + + private final BroadcastReceiver mReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { + Log.d(TAG, "onReceive - BluetoothAdapter state changed"); + int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); + mPython.on_bluetooth_adapter_state_change(state); + } + } + }; + + private final BluetoothGattCallback mGattCallback = + new BluetoothGattCallback() { + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + if (newState == BluetoothProfile.STATE_CONNECTED) { + Log.d(TAG, "Connected to GATT server, status:" + status); + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + Log.d(TAG, "Disconnected from GATT server, status:" + status); + } + if (mBluetoothGatt == null) { + mBluetoothGatt = gatt; + } + mPython.on_connection_state_change(status, newState); + } + + @Override + public void onServicesDiscovered(BluetoothGatt gatt, int status) { + if (status == BluetoothGatt.GATT_SUCCESS) { + Log.d(TAG, "onServicesDiscovered - success"); + mBluetoothGattServices = mBluetoothGatt.getServices(); + } else { + showError("onServicesDiscovered status:" + status); + mBluetoothGattServices = null; + } + mPython.on_services(status, mBluetoothGattServices); + } + + @Override + public void onCharacteristicChanged(BluetoothGatt gatt, + BluetoothGattCharacteristic characteristic) { + mPython.on_characteristic_changed(characteristic); + } + + @Override + public void onCharacteristicRead(BluetoothGatt gatt, + BluetoothGattCharacteristic characteristic, + int status) { + mPython.on_characteristic_read(characteristic, status); + } + + @Override + public void onCharacteristicWrite(BluetoothGatt gatt, + BluetoothGattCharacteristic characteristic, + int status) { + mPython.on_characteristic_write(characteristic, status); + } + + @Override + public void onDescriptorRead(BluetoothGatt gatt, + BluetoothGattDescriptor descriptor, + int status) { + mPython.on_descriptor_read(descriptor, status); + } + + @Override + public void onDescriptorWrite(BluetoothGatt gatt, + BluetoothGattDescriptor descriptor, + int status) { + mPython.on_descriptor_write(descriptor, status); + } + + @Override + public void onReadRemoteRssi(BluetoothGatt gatt, + int rssi, int status) { + mPython.on_rssi_updated(rssi, status); + } + + @Override + public void onMtuChanged(BluetoothGatt gatt, + int mtu, int status) { + Log.d(TAG, String.format("onMtuChanged mtu=%d status=%d", mtu, status)); + mPython.on_mtu_changed(mtu, status); + } + }; + + public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic, byte[] data, int writeType) { + if (characteristic.setValue(data)) { + if (writeType != 0) { + characteristic.setWriteType(writeType); + } + return mBluetoothGatt.writeCharacteristic(characteristic); + } + return false; + } + + public boolean readCharacteristic(BluetoothGattCharacteristic characteristic) { + return mBluetoothGatt.readCharacteristic(characteristic); + } + + public boolean readRemoteRssi() { + return mBluetoothGatt.readRemoteRssi(); + } +} diff --git a/libs/able/able/src/org/able/BLEAdvertiser.java b/libs/able/able/src/org/able/BLEAdvertiser.java new file mode 100644 index 0000000..fcff023 --- /dev/null +++ b/libs/able/able/src/org/able/BLEAdvertiser.java @@ -0,0 +1,61 @@ +package org.able; + +import android.bluetooth.le.AdvertisingSet; +import android.bluetooth.le.AdvertisingSetCallback; +import org.able.PythonBluetoothAdvertiser; +import android.util.Log; + + +public class BLEAdvertiser { + private String TAG = "BLE-python"; + private PythonBluetoothAdvertiser mPython; + public AdvertisingSetCallback mCallbackSet; + + public BLEAdvertiser(PythonBluetoothAdvertiser python) { + mPython = python; + } + + public AdvertisingSetCallback createCallback() { + mCallbackSet = new AdvertisingSetCallback() { + @Override + public void onAdvertisingSetStarted(AdvertisingSet advertisingSet, int txPower, int status) { + Log.d(TAG, "onAdvertisingSetStarted, status:" + status); + mPython.on_advertising_started(advertisingSet, txPower, status); + } + + @Override + public void onAdvertisingSetStopped(AdvertisingSet advertisingSet) { + Log.d(TAG, "onAdvertisingSetStopped"); + mCallbackSet = null; + mPython.on_advertising_stopped(advertisingSet); + } + + + @Override + public void onAdvertisingEnabled(AdvertisingSet advertisingSet, boolean enable, int status) { + Log.d(TAG, "onAdvertisingEnabled, enable:" + enable + "status:" + status); + mPython.on_advertising_enabled(advertisingSet, enable, status); + } + + + @Override + public void onAdvertisingDataSet(AdvertisingSet advertisingSet, int status) { + Log.d(TAG, "onAdvertisingDataSet, status:" + status); + mPython.on_advertising_data_set(advertisingSet, status); + } + + @Override + public void onScanResponseDataSet(AdvertisingSet advertisingSet, int status) { + Log.d(TAG, "onScanResponseDataSet, status:" + status); + mPython.on_scan_response_data_set(advertisingSet, status); + } + + @Override + public void onAdvertisingParametersUpdated(AdvertisingSet advertisingSet, int txPower, int status) { + Log.d(TAG, "onAdvertisingParametersUpdated, status:" + status); + mPython.on_advertising_parameters_updated(advertisingSet, txPower, status); + } + }; + return mCallbackSet; + } +} diff --git a/libs/able/able/src/org/able/PythonBluetooth.java b/libs/able/able/src/org/able/PythonBluetooth.java new file mode 100644 index 0000000..8179ca2 --- /dev/null +++ b/libs/able/able/src/org/able/PythonBluetooth.java @@ -0,0 +1,25 @@ +package org.able; + +import java.util.List; +import android.bluetooth.BluetoothGattService; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; +import android.bluetooth.le.ScanResult; + +interface PythonBluetooth +{ + public void on_error(String msg); + public void on_scan_started(boolean success); + public void on_scan_result(ScanResult result); + public void on_scan_completed(); + public void on_services(int status, List services); + public void on_characteristic_changed(BluetoothGattCharacteristic characteristic); + public void on_characteristic_read(BluetoothGattCharacteristic characteristic, int status); + public void on_characteristic_write(BluetoothGattCharacteristic characteristic, int status); + public void on_descriptor_read(BluetoothGattDescriptor descriptor, int status); + public void on_descriptor_write(BluetoothGattDescriptor descriptor, int status); + public void on_connection_state_change(int status, int state); + public void on_bluetooth_adapter_state_change(int state); + public void on_rssi_updated(int rssi, int status); + public void on_mtu_changed (int mtu, int status); +} diff --git a/libs/able/able/src/org/able/PythonBluetoothAdvertiser.java b/libs/able/able/src/org/able/PythonBluetoothAdvertiser.java new file mode 100644 index 0000000..d2c6d38 --- /dev/null +++ b/libs/able/able/src/org/able/PythonBluetoothAdvertiser.java @@ -0,0 +1,13 @@ +package org.able; + +import android.bluetooth.le.AdvertisingSet; + +interface PythonBluetoothAdvertiser +{ + public void on_advertising_started(AdvertisingSet advertisingSet, int txPower, int status); + public void on_advertising_stopped(AdvertisingSet advertisingSet); + public void on_advertising_enabled(AdvertisingSet advertisingSet, boolean enable, int status); + public void on_advertising_data_set(AdvertisingSet advertisingSet, int status); + public void on_scan_response_data_set(AdvertisingSet advertisingSet, int status); + public void on_advertising_parameters_updated(AdvertisingSet advertisingSet, int txPower, int status); +} diff --git a/libs/able/able/structures.py b/libs/able/able/structures.py new file mode 100644 index 0000000..2bd3e93 --- /dev/null +++ b/libs/able/able/structures.py @@ -0,0 +1,81 @@ +import re + +from collections import namedtuple + + +class Advertisement(object): + """Advertisement data record parser + + >>> ad = Advertisement([2, 1, 0x6, 6, 255, 82, 83, 95, 82, 48]) + >>> for data in ad: + ... data + AD(ad_type=1, data=bytearray(b'\\x06')) + AD(ad_type=255, data=bytearray(b'RS_R0')) + >>> list(ad)[0].ad_type == Advertisement.ad_types.flags + True + """ + + AD = namedtuple("AD", ['ad_type', 'data']) + + class ad_types: + """ + Assigned numbers for some of `advertisement data types + `_. + + flags : "Flags" (0x01) + + complete_local_name : "Complete Local Name" (0x09) + + service_data : "Service Data" (0x16) + + manufacturer_specific_data : "Manufacturer Specific Data" (0xff) + """ + flags = 0x01 + complete_local_name = 0x09 + service_data = 0x16 + manufacturer_specific_data = 0xff + + def __init__(self, data): + self.data = data + + def __iter__(self): + return Advertisement.parse(self.data) + + @classmethod + def parse(cls, data): + pos = 0 + while pos < len(data): + length = data[pos] + if length < 2: + return + try: + ad_type = data[pos + 1] + except IndexError: + return + next_pos = pos + length + 1 + if ad_type: + segment = slice(pos + 2, next_pos) + yield Advertisement.AD(ad_type, bytearray(data[segment])) + pos = next_pos + + +class Services(dict): + """Services dict + + >>> services = Services({'service0': {'c1-aa': 0, 'aa-c2-aa': 1}, + ... 'service1': {'bb-c3-bb': 2}}) + >>> services.search('c3') + 2 + >>> services.search('c4') + """ + + def search(self, pattern, flags=re.IGNORECASE): + """Search for characteristic by pattern + + :param pattern: regexp pattern + :param flags: regexp flags, re.IGNORECASE by default + """ + for characteristics in self.values(): + for uuid, characteristic in characteristics.items(): + if re.search(pattern, uuid, flags): + return characteristic diff --git a/libs/able/able/utils.py b/libs/able/able/utils.py new file mode 100644 index 0000000..3108372 --- /dev/null +++ b/libs/able/able/utils.py @@ -0,0 +1,42 @@ +from typing import Any, Union + + +def force_convertible_to_java_array( + value: Any +) -> Union[list, tuple, bytes, bytearray]: + """Construct a value that is convertible to a Java array. + + >>> force_convertible_to_java_array([3, 1, 4]) + [3, 1, 4] + >>> force_convertible_to_java_array(['314']) + ['314'] + >>> force_convertible_to_java_array('314') + b'314' + >>> force_convertible_to_java_array(314) + [314] + >>> force_convertible_to_java_array(0) + [0] + >>> force_convertible_to_java_array('') + [] + >>> force_convertible_to_java_array(None) + [] + >>> force_convertible_to_java_array({}) + [] + """ + if isinstance(value, (list, tuple, bytes, bytearray)): + return value + + try: + return value.encode() or [] + except AttributeError: + pass + + try: + return list(value) + except TypeError: + pass + + if value is None: + return [] + + return [value] diff --git a/libs/able/able/version.py b/libs/able/able/version.py new file mode 100644 index 0000000..4ec92f4 --- /dev/null +++ b/libs/able/able/version.py @@ -0,0 +1,5 @@ +"""Package version. +This file is filled with actual value during the PyPI package build. +Development version is always "0.0.0". +""" +__version__ = '0.0.0' diff --git a/libs/able/docs/Makefile b/libs/able/docs/Makefile new file mode 100644 index 0000000..4a5e9a7 --- /dev/null +++ b/libs/able/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ABLE.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ABLE.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/ABLE" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ABLE" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/libs/able/docs/api.rst b/libs/able/docs/api.rst new file mode 100644 index 0000000..5226cae --- /dev/null +++ b/libs/able/docs/api.rst @@ -0,0 +1,154 @@ +API +--- + +.. automodule:: able + +Client +^^^^^^ + +BluetoothDispatcher +""""""""""""""""""" + +.. autoclass:: BluetoothDispatcher + :members: adapter, + gatt, + bonded_devices, + name, + set_queue_timeout, + start_scan, + stop_scan, + connect_by_device_address, + connect_gatt, + close_gatt, + discover_services, + enable_notifications, + write_descriptor, + write_characteristic, + read_characteristic, + update_rssi, + request_mtu, + on_error, + on_gatt_release, + on_scan_started, + on_scan_completed, + on_device, + on_bluetooth_adapter_state_changeable, + on_connection_state_change, + on_services, + on_characteristic_changed, + on_characteristic_read, + on_characteristic_write, + on_descriptor_read, + on_descriptor_write, + on_rssi_updated, + on_mtu_changed, + +Decorators +"""""""""" + +.. autofunction:: require_bluetooth_enabled + + +Advertisement +""""""""""""" + +.. autoclass:: Advertisement + + .. autoclass:: able::Advertisement.ad_types + +Services +"""""""" + +.. autoclass:: Services + :members: + +Constants +""""""""" + +.. autodata:: GATT_SUCCESS +.. autodata:: STATE_CONNECTED +.. autodata:: STATE_DISCONNECTED +.. autoclass:: AdapterState + :members: + :member-order: bysource +.. autoclass:: WriteType + :members: + +Permissions +^^^^^^^^^^^ + +.. automodule:: able.permissions +.. automodule:: able +.. autoclass:: Permission + :members: + :undoc-members: + :member-order: bysource + + +Scan settings +^^^^^^^^^^^^^ + +.. automodule:: able.scan_settings +.. autoclass:: ScanSettingsBuilder +.. autoclass:: ScanSettings + + +>>> settings = ScanSettingsBuilder() \ +... .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE) \ +... .setCallbackType( +... ScanSettings.CALLBACK_TYPE_FIRST_MATCH | +... ScanSettings.CALLBACK_TYPE_MATCH_LOST +... ) + + +Scan filters +^^^^^^^^^^^^ + +.. automodule:: able.filters + :members: + :member-order: bysource + :show-inheritance: + + +Advertising +^^^^^^^^^^^ + +.. automodule:: able.advertising + +Advertiser +"""""""""" +.. autoclass:: Advertiser + :members: + :member-order: bysource + + +Payload +""""""" +.. autoclass:: AdvertiseData + +.. autoclass:: DeviceName + :show-inheritance: +.. autoclass:: TXPowerLevel + :show-inheritance: +.. autoclass:: ServiceUUID + :show-inheritance: +.. autoclass:: ServiceData + :show-inheritance: +.. autoclass:: ManufacturerData + :show-inheritance: + +Constants +""""""""" + +.. autoclass:: Interval + :members: + :member-order: bysource + +.. autoclass:: TXPower + :members: + :member-order: bysource + +.. autoclass:: Status + :members: + :undoc-members: + :member-order: bysource diff --git a/libs/able/docs/conf.py b/libs/able/docs/conf.py new file mode 100644 index 0000000..28029ad --- /dev/null +++ b/libs/able/docs/conf.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# +# ABLE documentation build configuration file, created by +# sphinx-quickstart on Sun Apr 16 23:19:55 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('..')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'ABLE' +copyright = u'2017, b3b' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'ABLEdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'ABLE.tex', u'ABLE Documentation', + u'b3b', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'able', u'ABLE Documentation', + [u'b3b'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'ABLE', u'ABLE Documentation', + u'b3b', 'ABLE', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False + + +# http://stackoverflow.com/questions/28366818/preserve-default-arguments-of-wrapped-decorated-python-function-in-sphinx-document +# Monkey-patch functools.wraps +import functools + +def no_op_wraps(func): + """Replaces functools.wraps in order to undo wrapping. + + Can be used to preserve the decorated function's signature + in the documentation generated by Sphinx. + + """ + def wrapper(decorator): + return func + return wrapper + +functools.wraps = no_op_wraps + + +# http://docs.readthedocs.io/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules +# I get import errors on libraries that depend on C modules +from mock import MagicMock + +class Mock(MagicMock): + @classmethod + def __getattr__(cls, name): + return MagicMock() + +MOCK_MODULES = ['kivy', 'kivy.utils', 'kivy.clock', 'kivy.logger', + 'kivy.event'] +sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) +sys.modules['kivy.event'].EventDispatcher = object diff --git a/libs/able/docs/example.rst b/libs/able/docs/example.rst new file mode 100644 index 0000000..a408c21 --- /dev/null +++ b/libs/able/docs/example.rst @@ -0,0 +1,192 @@ +Usage Examples +============== + +Alert +----- + +.. literalinclude:: ./examples/alert.py + :language: python + +Full example code: `alert `_ + + +Change MTU +---------- +.. literalinclude:: ./examples/mtu.py + :language: python + + +Scan settings +------------- + +.. code-block:: python + + from able import BluetoothDispatcher + from able.scan_settings import ScanSettingsBuilder, ScanSettings + + # Use faster detection (more power usage) mode + settings = ScanSettingsBuilder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + BluetoothDispatcher().start_scan(settings=settings) + + +Scan filters +------------ + +.. code-block:: python + + from able import BluetoothDispatcher + from able.filters import ( + DeviceAddressFilter, + DeviceNameFilter, + ManufacturerDataFilter, + ServiceDataFilter, + ServiceUUIDFilter + ) + + ble = BluetoothDispatcher() + + # Start scanning with the condition that device has one of names: "Device1" or "Device2" + ble.start_scan(filters=[DeviceNameFilter("Device1"), DeviceNameFilter("Device2")]) + ble.stop_scan() + + # Start scanning with the condition that + # device advertises "180f" service and one of names: "Device1" or "Device2" + ble.start_scan(filters=[ + ServiceUUIDFilter('0000180f-0000-1000-8000-00805f9b34fb') & DeviceNameFilter("Device1"), + ServiceUUIDFilter('0000180f-0000-1000-8000-00805f9b34fb') & DeviceNameFilter("Device2") + ]) + + +Adapter state +------------- + +.. literalinclude:: ./examples/adapter_state_change.py + :language: python + + +Advertising +----------- + +Advertise with data and additional (scannable) data +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. code-block:: python + + from able import BluetoothDispatcher + from able.advertising import ( + Advertiser, + AdvertiseData, + ManufacturerData, + Interval, + ServiceUUID, + ServiceData, + TXPower, + ) + + advertiser = Advertiser( + ble=BluetoothDispatcher(), + data=AdvertiseData(ServiceUUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")), + scan_data=AdvertiseData(ManufacturerData(id=0xAABB, data=b"some data")), + interval=Interval.MEDIUM, + tx_power=TXPower.MEDIUM, + ) + + advertiser.start() + + +Set and advertise device name +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: python + + from able import BluetoothDispatcher + from able.advertising import Advertiser, AdvertiseData, DeviceName + + ble = BluetoothDispatcher() + ble.name = "New test device name" + + # There must be a wait and check, it takes time for new name to take effect + print(f"New device name is set: {ble.name}") + + Advertiser( + ble=ble, + data=AdvertiseData(DeviceName()) + ) + + +Battery service data +^^^^^^^^^^^^^^^^^^^^ + +.. literalinclude:: ./examples/advertising_battery.py + :language: python + + +Use iBeacon advertising format +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: python + + import uuid + from able import BluetoothDispatcher + from able.advertising import Advertiser, AdvertiseData, ManufacturerData + + + data = AdvertiseData( + ManufacturerData( + 0x4C, # Apple Manufacturer ID + bytes([ + 0x2, # SubType: Custom Manufacturer Data + 0x15 # Subtype lenth + ]) + + uuid.uuid4().bytes + # UUID of beacon + bytes([ + 0, 15, # Major value + 0, 1, # Minor value + 10 # RSSI, dBm at 1m + ])) + ) + + Advertiser(BluetoothDispatcher(), data).start() + + +Android Services +---------------- + +BLE devices scanning service +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**main.py** + +.. literalinclude:: ./examples/service_scan_main.py + :language: python + +**service.py** + +.. literalinclude:: ./examples/service_scan_service.py + :language: python + +Full example code: `service_scan `_ + + +Advertising service +^^^^^^^^^^^^^^^^^^^ + +**main.py** + +.. literalinclude:: ./examples/service_advertise_main.py + :language: python + +**service.py** + +.. literalinclude:: ./examples/service_advertise_service.py + :language: python + +Full example code: `service_advertise `_ + + +Connect to multiple devices +--------------------------- + +.. literalinclude:: ./examples/multi_devices/main.py + :language: python + +Full example code: `multi_devices `_ diff --git a/libs/able/docs/index.rst b/libs/able/docs/index.rst new file mode 100644 index 0000000..0c01475 --- /dev/null +++ b/libs/able/docs/index.rst @@ -0,0 +1,3 @@ +.. include:: ../README.rst +.. include:: api.rst +.. include:: example.rst diff --git a/libs/able/examples/adapter_state_change.py b/libs/able/examples/adapter_state_change.py new file mode 100644 index 0000000..0e97f6b --- /dev/null +++ b/libs/able/examples/adapter_state_change.py @@ -0,0 +1,27 @@ +"""Detect and log Bluetooth adapter state change.""" + +from typing import Optional + +from kivy.logger import Logger +from kivy.uix.widget import Widget + +from able import AdapterState, BluetoothDispatcher + + +class Dispatcher(BluetoothDispatcher): + def on_bluetooth_adapter_state_change(self, state: int): + Logger.info( + f"Bluetoth adapter state changed to {state} ('{AdapterState(state).name}')." + ) + if state == AdapterState.OFF: + Logger.info("Adapter state changed to OFF.") + + +class StateChangeApp(App): + def build(self): + Dispatcher() + return Widget() + + +if __name__ == "__main__": + StateChangeApp.run() diff --git a/libs/able/examples/advertising_battery.py b/libs/able/examples/advertising_battery.py new file mode 100644 index 0000000..970e622 --- /dev/null +++ b/libs/able/examples/advertising_battery.py @@ -0,0 +1,71 @@ +"""Advertise battery level, that degrades every second.""" +from kivy.app import App +from kivy.clock import Clock +from kivy.uix.label import Label + +from able import BluetoothDispatcher +from able import advertising + +# Standard fully-qualified UUID for the Battery Service +BATTERY_SERVICE_UUID = "0000180f-0000-1000-8000-00805f9b34fb" + + +class BatteryAdvertiser(advertising.Advertiser): + + def on_advertising_started(self, advertising_set, tx_power, status): + if status == advertising.Status.SUCCESS: + print("Advertising is started successfully") + else: + print(f"Advertising start error status: {status}") + + def on_advertising_stopped(self, advertising_set): + print("Advertising stopped") + + +class BatteryLabel(Label): + """Widget to control advertiser and show current battery level.""" + + def __init__(self): + self._level = 0 + super().__init__(text="Waiting for advertising to start...") + self.advertiser = BatteryAdvertiser( + ble=BluetoothDispatcher(), + data=self.construct_data(level=100), + interval=advertising.Interval.MIN + ) + self.advertiser.bind(on_advertising_started=self.on_started) # bind to start of advertising + self.advertiser.start() + + def on_started(self, advertiser, advertising_set, tx_power, status): + if status == advertising.Status.SUCCESS: + # Advertising is started - update battery level every second + self.clock = Clock.schedule_interval(self.update_level, 1) + + def update_level(self, dt): + level = self._level = (self._level - 1) % 101 + self.text = str(level) + + if level > 0: + # Set new advertising data + self.advertiser.data = self.construct_data(level) + else: + self.clock.cancel() + # Stop advertising + self.advertiser.stop() + + def construct_data(self, level): + return advertising.AdvertiseData( + advertising.DeviceName(), + advertising.TXPowerLevel(), + advertising.ServiceData(BATTERY_SERVICE_UUID, [level]) + ) + + +class BatteryApp(App): + + def build(self): + return BatteryLabel() + + +if __name__ == "__main__": + BatteryApp().run() diff --git a/libs/able/examples/alert/buildozer.spec b/libs/able/examples/alert/buildozer.spec new file mode 100644 index 0000000..43b4d7b --- /dev/null +++ b/libs/able/examples/alert/buildozer.spec @@ -0,0 +1,27 @@ +[app] +title = Alert Mi +version = 1.1 +package.name = alert_mi +package.domain = org.kivy +source.dir = . +source.include_exts = py,png,jpg,kv,atlas + +requirements = python3,kivy,android,able_recipe + +android.accept_sdk_license = True +android.permissions = + BLUETOOTH, + BLUETOOTH_ADMIN, + BLUETOOTH_SCAN, + BLUETOOTH_CONNECT, + BLUETOOTH_ADVERTISE, + ACCESS_FINE_LOCATION + +# android.api = 31 +# android.minapi = 31 + + +[buildozer] +warn_on_root = 1 +# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) +log_level = 2 diff --git a/libs/able/examples/alert/error_message.kv b/libs/able/examples/alert/error_message.kv new file mode 100644 index 0000000..90edcf0 --- /dev/null +++ b/libs/able/examples/alert/error_message.kv @@ -0,0 +1,21 @@ +: + BoxLayout: + orientation: 'vertical' + padding: 10 + spacing: 20 + Label: + size_hint_y: None + font_size: '18sp' + height: '24sp' + text: 'Application has crashed, details: ' + ScrollView: + size_hint: 1, 1 + TextInput: + text: root.message + size_hint: 1, None + height: self.minimum_height + Button: + size_hint_y: None + height: '40sp' + text: 'OK, terminate' + on_press: root.dismiss() diff --git a/libs/able/examples/alert/error_message.py b/libs/able/examples/alert/error_message.py new file mode 100644 index 0000000..d6722a7 --- /dev/null +++ b/libs/able/examples/alert/error_message.py @@ -0,0 +1,39 @@ +import os +import traceback + +from kivy.base import ( + ExceptionHandler, + ExceptionManager, + stopTouchApp, +) +from kivy.properties import StringProperty +from kivy.uix.popup import Popup +from kivy.lang import Builder +from kivy.logger import Logger + + +Builder.load_file(os.path.join(os.path.dirname(__file__), 'error_message.kv')) + + +class ErrorMessageOnException(ExceptionHandler): + + def handle_exception(self, exception): + Logger.exception('Unhandled Exception catched') + message = ErrorMessage(message=traceback.format_exc()) + + def raise_exception(*ar2gs, **kwargs): + stopTouchApp() + raise Exception("Exit due to errors") + + message.bind(on_dismiss=raise_exception) + message.open() + return ExceptionManager.PASS + + +class ErrorMessage(Popup): + title = StringProperty('Bang!') + message = StringProperty('') + + +def install_exception_handler(): + ExceptionManager.add_handler(ErrorMessageOnException()) diff --git a/libs/able/examples/alert/main.py b/libs/able/examples/alert/main.py new file mode 100644 index 0000000..433673a --- /dev/null +++ b/libs/able/examples/alert/main.py @@ -0,0 +1,64 @@ +"""Turn the alert on Mi Band device +""" +from kivy.app import App +from kivy.uix.button import Button + +from able import BluetoothDispatcher, GATT_SUCCESS +from error_message import install_exception_handler + + +class BLE(BluetoothDispatcher): + device = alert_characteristic = None + + def start_alert(self, *args, **kwargs): + if self.alert_characteristic: # alert service is already discovered + self.alert(self.alert_characteristic) + elif self.device: # device is already founded during the scan + self.connect_gatt(self.device) # reconnect + else: + self.stop_scan() # stop previous scan + self.start_scan() # start a scan for devices + + def on_device(self, device, rssi, advertisement): + # some device is found during the scan + name = device.getName() + if name and name.startswith('MI'): # is a Mi Band device + self.device = device + self.stop_scan() + + def on_scan_completed(self): + if self.device: + self.connect_gatt(self.device) # connect to device + + def on_connection_state_change(self, status, state): + if status == GATT_SUCCESS and state: # connection established + self.discover_services() # discover what services a device offer + else: # disconnection or error + self.alert_characteristic = None + self.close_gatt() # close current connection + + def on_services(self, status, services): + # 0x2a06 is a standard code for "Alert Level" characteristic + # https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.alert_level.xml + self.alert_characteristic = services.search('2a06') + self.alert(self.alert_characteristic) + + def alert(self, characteristic): + self.write_characteristic(characteristic, [2]) # 2 is for "High Alert" + + +class AlertApp(App): + + def build(self): + self.ble = None + return Button(text='Press to Alert Mi', on_press=self.start_alert) + + def start_alert(self, *args, **kwargs): + if not self.ble: + self.ble = BLE() + self.ble.start_alert() + + +if __name__ == '__main__': + install_exception_handler() + AlertApp().run() diff --git a/libs/able/examples/mtu.py b/libs/able/examples/mtu.py new file mode 100644 index 0000000..83a8da9 --- /dev/null +++ b/libs/able/examples/mtu.py @@ -0,0 +1,52 @@ +"""Request MTU change, and write 100 bytes to a characteristic.""" +from kivy.app import App +from kivy.clock import Clock +from kivy.logger import Logger +from kivy.uix.widget import Widget + +from able import BluetoothDispatcher, GATT_SUCCESS + + +class BLESender(BluetoothDispatcher): + + def __init__(self): + super().__init__() + self.characteristic_to_write = None + Clock.schedule_once(self.connect, 0) + + def connect(self, _): + self.connect_by_device_address("FF:FF:FF:FF:FF:FF") + + def on_connection_state_change(self, status, state): + if status == GATT_SUCCESS and state: + self.discover_services() + + def on_services(self, status, services): + if status == GATT_SUCCESS: + self.characteristic_to_write = services.search("0d03") + # Need to request 100 + 3 extra bytes for ATT packet header + self.request_mtu(103) + + def on_mtu_changed(self, mtu, status): + if status == GATT_SUCCESS and mtu == 103: + Logger.info("MTU changed: now it is possible to send 100 bytes at once") + self.write_characteristic(self.characteristic_to_write, range(100)) + else: + Logger.error("MTU not changed: mtu=%d, status=%d", mtu, status) + + def on_characteristic_write(self, characteristic, status): + if status == GATT_SUCCESS: + Logger.info("Characteristic write succeed") + else: + Logger.error("Write status: %d", status) + + +class MTUApp(App): + + def build(self): + BLESender() + return Widget() + + +if __name__ == '__main__': + MTUApp().run() diff --git a/libs/able/examples/multi_devices/buildozer.spec b/libs/able/examples/multi_devices/buildozer.spec new file mode 100644 index 0000000..f75a488 --- /dev/null +++ b/libs/able/examples/multi_devices/buildozer.spec @@ -0,0 +1,27 @@ +[app] +title = Multiple BLE devices +version = 1.0 +package.name = multidevs +package.domain = test.able +source.dir = . +source.include_exts = py,png,jpg,kv,atlas + +requirements = python3,kivy,android,able_recipe + +android.accept_sdk_license = True +android.permissions = + BLUETOOTH, + BLUETOOTH_ADMIN, + BLUETOOTH_SCAN, + BLUETOOTH_CONNECT, + BLUETOOTH_ADVERTISE, + ACCESS_FINE_LOCATION + +# android.api = 31 +# android.minapi = 31 + + +[buildozer] +warn_on_root = 1 +# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) +log_level = 2 diff --git a/libs/able/examples/multi_devices/main.py b/libs/able/examples/multi_devices/main.py new file mode 100644 index 0000000..99b10e9 --- /dev/null +++ b/libs/able/examples/multi_devices/main.py @@ -0,0 +1,96 @@ +"""Scan for devices with name "KivyBLETest", +connect and periodically read connected devices RSSI. + +Multiple `BluetoothDispatcher` objects are used: + one for the scanning process and one for every connected device. +""" +from able import GATT_SUCCESS, BluetoothDispatcher +from able.filters import DeviceNameFilter +from kivy.app import App +from kivy.clock import Clock +from kivy.logger import Logger +from kivy.uix.label import Label + + +class DeviceDispatcher(BluetoothDispatcher): + """Dispatcher to control a single BLE device.""" + + def __init__(self, device: "BluetoothDevice"): + super().__init__() + self._device = device + self._address: str = device.getAddress() + self._name: str = device.getName() or "" + + @property + def title(self) -> str: + return f"<{self._address}><{self._name}>" + + def on_connection_state_change(self, status: int, state: int): + if status == GATT_SUCCESS and state: + Logger.info(f"Device: {self.title} connected") + else: + Logger.info(f"Device: {self.title} disconnected. {status=}, {state=}") + self.close_gatt() + Clock.schedule_once(callback=lambda dt: self.reconnect(), timeout=15) + + def on_rssi_updated(self, rssi: int, status: int): + Logger.info(f"Device: {self.title} RSSI: {rssi}") + + def periodically_update_rssi(self): + """ + Clock callback to read + the signal strength indicator for a connected device. + """ + if self.gatt: # if device is connected + self.update_rssi() + + def reconnect(self): + Logger.info(f"Device: {self.title} try to reconnect ...") + self.connect_gatt(self._device) + + def start(self): + """Start connection to device.""" + if not self.gatt: + self.connect_gatt(self._device) + Clock.schedule_interval( + callback=lambda dt: self.periodically_update_rssi(), timeout=5 + ) + + +class ScannerDispatcher(BluetoothDispatcher): + """Dispatcher to control the scanning process.""" + + def __init__(self): + super().__init__() + # Stores connected devices addresses + self._devices: dict[str, DeviceDispatcher] = {} + + def on_scan_started(self, success: bool): + if success: + Logger.info("Scan: started") + else: + Logger.error("Scan: error on start") + + def on_scan_completed(self): + Logger.info("Scan: completed") + + def on_device(self, device, rssi, advertisement): + address = device.getAddress() + if address not in self._devices: + # Create dispatcher instance for a new device + dispatcher = DeviceDispatcher(device) + # Remember address, + # to avoid multiple dispatchers creation for this device + self._devices[address] = dispatcher + Logger.info(f"Scan: device <{address}> added") + dispatcher.start() + + +class MultiDevicesApp(App): + def build(self): + ScannerDispatcher().start_scan(filters=[DeviceNameFilter("KivyBLETest")]) + return Label(text=self.name) + + +if __name__ == "__main__": + MultiDevicesApp().run() diff --git a/libs/able/examples/service_advertise/buildozer.spec b/libs/able/examples/service_advertise/buildozer.spec new file mode 100644 index 0000000..a8340f3 --- /dev/null +++ b/libs/able/examples/service_advertise/buildozer.spec @@ -0,0 +1,27 @@ +[app] +title = BLE advertising service +version = 1.1 +package.name = advservice +package.domain = test.able +source.dir = . +source.include_exts = py,png,jpg,kv,atlas + +android.permissions = + FOREGROUND_SERVICE, + BLUETOOTH, + BLUETOOTH_ADMIN, + BLUETOOTH_CONNECT, + BLUETOOTH_ADVERTISE + +requirements = kivy==2.1.0,python3,able_recipe +services = Able:service.py:foreground + +android.accept_sdk_license = True + +# android.api = 31 +# android.minapi = 31 + +[buildozer] +warn_on_root = 1 +# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) +log_level = 2 diff --git a/libs/able/examples/service_advertise/main.py b/libs/able/examples/service_advertise/main.py new file mode 100644 index 0000000..446158d --- /dev/null +++ b/libs/able/examples/service_advertise/main.py @@ -0,0 +1,56 @@ +"""Start advertising service.""" +from able import BluetoothDispatcher, Permission, require_bluetooth_enabled +from jnius import autoclass +from kivy.app import App +from kivy.lang import Builder + + +kv = """ +BoxLayout: + Button: + text: 'Start service' + on_press: app.ble_dispatcher.start_service() + Button: + text: 'Stop service' + on_press: app.ble_dispatcher.stop_service() +""" + + +class Dispatcher(BluetoothDispatcher): + @property + def service(self): + return autoclass("test.able.advservice.ServiceAble") + + @property + def activity(self): + return autoclass("org.kivy.android.PythonActivity").mActivity + + # Need to turn on the adapter, before service is started + @require_bluetooth_enabled + def start_service(self): + self.service.start( + self.activity, + # Pass UUID to advertise + "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", + ) + App.get_running_app().stop() # Can close the app, service will continue running + + def stop_service(self): + self.service.stop(self.activity) + + +class ServiceApp(App): + def build(self): + self.ble_dispatcher = Dispatcher( + # This app does not use device scanning, + # so the list of required permissions can be reduced + runtime_permissions=[ + Permission.BLUETOOTH_CONNECT, + Permission.BLUETOOTH_ADVERTISE, + ] + ) + return Builder.load_string(kv) + + +if __name__ == "__main__": + ServiceApp().run() diff --git a/libs/able/examples/service_advertise/service.py b/libs/able/examples/service_advertise/service.py new file mode 100644 index 0000000..69edc81 --- /dev/null +++ b/libs/able/examples/service_advertise/service.py @@ -0,0 +1,28 @@ +"""Service to advertise data, while not stopped.""" +import time +from os import environ + +from able import BluetoothDispatcher +from able.advertising import ( + Advertiser, + AdvertiseData, + ServiceUUID, +) + + +def main(): + uuid = environ.get( + "PYTHON_SERVICE_ARGUMENT", + "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" + ) + advertiser = Advertiser( + ble=BluetoothDispatcher(), + data=AdvertiseData(ServiceUUID(uuid)), + ) + advertiser.start() + while True: + time.sleep(0xDEAD) + + +if __name__ == "__main__": + main() diff --git a/libs/able/examples/service_scan/buildozer.spec b/libs/able/examples/service_scan/buildozer.spec new file mode 100644 index 0000000..54407b3 --- /dev/null +++ b/libs/able/examples/service_scan/buildozer.spec @@ -0,0 +1,29 @@ +[app] +title = BLE scan dev service +version = 1.1 +package.name = scanservice +package.domain = test.able +source.dir = . +source.include_exts = py,png,jpg,kv,atlas + +android.permissions = + FOREGROUND_SERVICE, + BLUETOOTH, + BLUETOOTH_ADMIN, + BLUETOOTH_SCAN, + BLUETOOTH_CONNECT, + BLUETOOTH_ADVERTISE, + ACCESS_FINE_LOCATION + +requirements = kivy==2.1.0,python3,able_recipe +services = Able:service.py:foreground + +android.accept_sdk_license = True + +# android.api = 31 +# android.minapi = 31 + +[buildozer] +warn_on_root = 1 +# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) +log_level = 2 diff --git a/libs/able/examples/service_scan/main.py b/libs/able/examples/service_scan/main.py new file mode 100644 index 0000000..ce1f8a2 --- /dev/null +++ b/libs/able/examples/service_scan/main.py @@ -0,0 +1,48 @@ +"""Start BLE devices scaning service.""" +from able import ( + BluetoothDispatcher, + require_bluetooth_enabled, +) +from jnius import autoclass +from kivy.app import App +from kivy.lang import Builder + + +kv = """ +BoxLayout: + Button: + text: 'Start service' + on_press: app.ble_dispatcher.start_service() + Button: + text: 'Stop service' + on_press: app.ble_dispatcher.stop_service() +""" + + +class Dispatcher(BluetoothDispatcher): + @property + def service(self): + return autoclass("test.able.scanservice.ServiceAble") + + @property + def activity(self): + return autoclass("org.kivy.android.PythonActivity").mActivity + + # Need to turn on the adapter and obtain permissions, before service is started + @require_bluetooth_enabled + def start_service(self): + self.service.start(self.activity, "") + App.get_running_app().stop() # Can close the app, service will continue to run + + def stop_service(self): + self.service.stop(self.activity) + + +class ServiceApp(App): + def build(self): + self.ble_dispatcher = Dispatcher() + return Builder.load_string(kv) + + +if __name__ == "__main__": + ServiceApp().run() diff --git a/libs/able/examples/service_scan/service.py b/libs/able/examples/service_scan/service.py new file mode 100644 index 0000000..74e393e --- /dev/null +++ b/libs/able/examples/service_scan/service.py @@ -0,0 +1,27 @@ +"""Service to run BLE scan for 60 seconds, +and log each `on_device` event. +""" +import time + +from able import BluetoothDispatcher +from kivy.logger import Logger + + +class BLE(BluetoothDispatcher): + def on_device(self, device, rssi, advertisement): + title = device.getName() or device.getAddress() + Logger.info("BLE Device found: %s", title) + + def on_error(self, msg): + Logger.error("BLE Error %s", msg) + + +def main(): + ble = BLE() + ble.start_scan() + time.sleep(60) + ble.stop_scan() + + +if __name__ == "__main__": + main() diff --git a/libs/able/recipes/__init__.py b/libs/able/recipes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/libs/able/recipes/able_recipe/__init__.py b/libs/able/recipes/able_recipe/__init__.py new file mode 100644 index 0000000..ac4d546 --- /dev/null +++ b/libs/able/recipes/able_recipe/__init__.py @@ -0,0 +1,34 @@ +""" +Android Bluetooth Low Energy +""" +from pythonforandroid.recipe import PythonRecipe +from pythonforandroid.toolchain import current_directory, info, shprint +import sh +from os.path import join + + +class AbleRecipe(PythonRecipe): + name = 'able_recipe' + depends = ['python3', 'setuptools', 'android'] + call_hostpython_via_targetpython = False + install_in_hostpython = True + + def prepare_build_dir(self, arch): + build_dir = self.get_build_dir(arch) + assert build_dir.endswith(self.name) + shprint(sh.rm, '-rf', build_dir) + shprint(sh.mkdir, build_dir) + + for filename in ('../../able', 'setup.py'): + shprint(sh.cp, '-a', join(self.get_recipe_dir(), filename), + build_dir) + + def postbuild_arch(self, arch): + super(AbleRecipe, self).postbuild_arch(arch) + info('Copying able java class to classes build dir') + with current_directory(self.get_build_dir(arch.arch)): + shprint(sh.cp, '-a', join('able', 'src', 'org'), + self.ctx.javaclass_dir) + + +recipe = AbleRecipe() diff --git a/libs/able/recipes/able_recipe/setup.py b/libs/able/recipes/able_recipe/setup.py new file mode 100644 index 0000000..c2ca462 --- /dev/null +++ b/libs/able/recipes/able_recipe/setup.py @@ -0,0 +1,9 @@ +from setuptools import setup + +setup( + name='able', + version='0.0.0', + packages=['able', 'able.android'], + description='Bluetooth Low Energy for Android', + license='MIT', +) diff --git a/libs/able/setup.py b/libs/able/setup.py new file mode 100644 index 0000000..9ed545b --- /dev/null +++ b/libs/able/setup.py @@ -0,0 +1,135 @@ +import os +import re +import shutil +from pathlib import Path +from setuptools import setup +from setuptools.command.install import install + + +main_ns = {} +with Path("able/version.py").open() as ver_file: + exec(ver_file.read(), main_ns) + +with Path("README.rst").open() as readme_file: + long_description = readme_file.read() + + +class PathParser: + @property + def javaclass_dir(self): + path = self.build_dir / "javaclasses" + if not path.exists(): + raise Exception( + "Java classes directory is not found. " + "Please report issue to: https://github.com/b3b/able/issues" + ) + path = path / self.distribution_name + print(f"Java classes directory found: '{path}'.") + path.mkdir(parents=True, exist_ok=True) + return path + + @property + def distribution_name(self): + path = self.python_path + while path.parent.name != "python-installs": + if len(path.parts) <= 1: + raise Exception( + "Distribution name is not found. " + "Please report issue to: https://github.com/b3b/able/issues" + ) + path = path.parent + print(f"Distribution name found: '{path.name}'.") + return path.name + + @property + def build_dir(self): + return self.python_installs_dir.parent + + @property + def python_installs_dir(self): + path = self.python_path.parent + while path.name != "python-installs": + if len(path.parts) <= 1: + raise Exception( + "Python installs directory is not found. " + "Please report issue to: https://github.com/b3b/able/issues" + ) + path = path.parent + return path + + @property + def python_path(self): + cppflags = os.environ["CPPFLAGS"] + print(f"Searching for Python install directory in CPPFLAGS: '{cppflags}'") + match = re.search(r"-I(/[^\s]+/build/python-installs/[^/\s]+/)", cppflags) + if not match: + raise Exception("Can't find Python install directory.") + found_path = Path(match.group(1)) + print("FOUND INSTALL DIRECTORY: "+found_path) + return found_path + + +class InstallRecipe(install): + """Command to install `able` recipe, + copies Java files to distribution `javaclass` directory.""" + + def run(self): + if False and "ANDROIDAPI" not in os.environ: + raise Exception( + "This recipe should not be installed directly, " + "only with the buildozer tool." + ) + + # Find Java classes target directory from the environment + javaclass_dir = str(PathParser().javaclass_dir) + + for java_file in ( + "able/src/org/able/BLE.java", + "able/src/org/able/BLEAdvertiser.java", + "able/src/org/able/PythonBluetooth.java", + "able/src/org/able/PythonBluetoothAdvertiser.java", + ): + shutil.copy(java_file, javaclass_dir) + + install.run(self) + + +setup( + name="able_recipe", + version=main_ns["__version__"], + packages=["able", "able.android"], + description="Bluetooth Low Energy for Android", + long_description=long_description, + long_description_content_type="text/x-rst", + author="b3b", + author_email="ash.b3b@gmail.com", + install_requires=[], + url="https://github.com/b3b/able", + project_urls={ + "Changelog": "https://github.com/b3b/able/blob/master/CHANGELOG.rst", + }, + # https://pypi.org/classifiers/ + classifiers=[ + "Development Status :: 3 - Alpha", + "License :: OSI Approved :: MIT License", + "Operating System :: Android", + "Topic :: System :: Networking", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + ], + keywords="android ble bluetooth kivy", + license="MIT", + zip_safe=False, + cmdclass={ + "install": InstallRecipe, + }, + options={ + "bdist_wheel": { + # Changing the wheel name + # to avoid installing a package from cache. + "plat_name": "unused-nocache", + }, + }, +) diff --git a/libs/able/testapps/bletest/.gitignore b/libs/able/testapps/bletest/.gitignore new file mode 100644 index 0000000..254defd --- /dev/null +++ b/libs/able/testapps/bletest/.gitignore @@ -0,0 +1 @@ +server diff --git a/libs/able/testapps/bletest/bletestapp.kv b/libs/able/testapps/bletest/bletestapp.kv new file mode 100644 index 0000000..bb9cab1 --- /dev/null +++ b/libs/able/testapps/bletest/bletestapp.kv @@ -0,0 +1,193 @@ +#:kivy 1.1.0 +#: import Factory kivy.factory.Factory +#: import findall re.findall + +: + padding_left: '4sp' + halign: 'left' + text_size: self.size + valign: 'middle' + +: + padding_left: '4sp' + halign: 'left' + text_size: self.size + valign: 'middle' + +: + title: 'Connect by MAC address' + size_hint: None, None + size: '400sp', '120sp' + BoxLayout: + orientation: 'vertical' + pos: self.pos + size: root.size + + TextInput: + size_hint_y: .5 + hint_text: 'Device address' + input_filter: lambda value, _ : ''.join(findall('[0-9a-fA-F:]+', value)).upper() + multiline: False + text: app.device_address + on_text: app.device_address = self.text + + BoxLayout: + orientation: 'horizontal' + size_hint_y: .5 + Button: + text: 'Connect' + on_press: root.dismiss(), app.connect_by_mac_address() + Button: + text: 'Cancel' + on_press: root.dismiss() + +: + padding: '10sp' + BoxLayout: + orientation: 'horizontal' + GridLayout: + cols: 2 + padding: '0sp' + spacing: '0sp' + orientation: 'lr-tb' + + Caption: + text: 'Adapter:' + Value: + text: app.adapter_state + + Caption: + text: 'State:' + Value: + text: app.state + halign: 'left' + valign: 'middle' + text_size: self.size + + Caption: + text: 'Read test:' + Value: + text: app.test_string + + Caption: + text: 'Notifications count:' + Value: + text: app.notification_value + + Caption: + text: 'N packets sended:' + Value: + text: app.increment_count_value + + Caption: + text: 'N packets delivered:' + Value: + text: app.counter_value + + Caption: + text: 'Total transmission time:' + Value: + text: app.counter_total_time + + BoxLayout: + spacing: '20sp' + orientation: 'vertical' + + BoxLayout: + orientation: 'horizontal' + size_hint_y: .3 + + Button: + text: 'Scan and connect' + on_press: app.start_scan() + + Button: + text: 'Connect by MAC address' + on_press: Factory.ConnectByMACDialog().open() + + BoxLayout: + id: queue_box + orientation: 'vertical' + size_hint_y: .15 + + BoxLayout: + orientation: 'horizontal' + Caption: + text: 'Enable GATT autoconnect:' + CheckBox: + id: timeout_checkbox + active: app.autoconnect + on_active: app.autoconnect = self.active + + BoxLayout: + orientation: 'horizontal' + size_hint_y: .2 + spacing: 10 + Button: + disabled: app.state != 'connected' + text: 'Read RSSI' + on_press: app.read_rssi() + Caption: + text: 'RSSI Value:' + Value: + text: app.rssi + + ToggleButton: + disabled: app.state != 'connected' + text: "Enable notifications" + size_hint_y: .2 + on_state: app.enable_notifications(self.state == 'down') + BoxLayout: + id: queue_box + orientation: 'vertical' + disabled: app.state != 'connected' + + BoxLayout: + orientation: 'horizontal' + Caption: + text: 'Enable BLE queue timeout:' + CheckBox: + id: timeout_checkbox + active: app.queue_timeout_enabled + on_active: app.queue_timeout_enabled = self.active + BoxLayout: + orientation: 'horizontal' + Caption: + text: 'BLE queue timeout (ms):' + TextInput: + disabled: queue_box.disabled or not timeout_checkbox.active + input_filter: 'int' + multiline: False + text: app.queue_timeout + on_text: app.queue_timeout = self.text + BoxLayout: + Button: + text: 'Apply queue settings' + on_press: app.set_queue_settings() + + BoxLayout: + disabled: app.state != 'connected' + orientation: 'vertical' + BoxLayout: + orientation: 'horizontal' + Caption: + text: 'Transmission interval (ms):' + TextInput: + input_filter: 'int' + multiline: False + text: app.incremental_interval + on_text: app.incremental_interval = self.text + BoxLayout: + orientation: 'horizontal' + Caption: + text: 'Packet count limit:' + TextInput: + input_filter: 'int' + multiline: False + text: app.counter_max + on_text: app.counter_max = self.text + padding_bottom: '100sp' + ToggleButton: + width: self.texture_size[0] + 50 + text: "Enable transmission" + on_state: app.enable_counter(self.state == 'down') diff --git a/libs/able/testapps/bletest/buildozer.spec b/libs/able/testapps/bletest/buildozer.spec new file mode 100644 index 0000000..102e39a --- /dev/null +++ b/libs/able/testapps/bletest/buildozer.spec @@ -0,0 +1,17 @@ +[app] +title = BLE functions test +version = 1.0 +package.name = kivy_ble_test +package.domain = org.kivy +source.dir = . +source.include_exts = py,png,jpg,kv,atlas +android.permissions = BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_FINE_LOCATION +requirements = python3,kivy,android,able_recipe + +# (str) Android's logcat filters to use +android.logcat_filters = *:S python:D + +[buildozer] +warn_on_root = 1 +# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) +log_level = 2 diff --git a/libs/able/testapps/bletest/main.py b/libs/able/testapps/bletest/main.py new file mode 100644 index 0000000..9d27429 --- /dev/null +++ b/libs/able/testapps/bletest/main.py @@ -0,0 +1,245 @@ +"""Connect to "KivyBLETest" server and test various BLE functions +""" +import time + +from able import AdapterState, GATT_SUCCESS, BluetoothDispatcher +from kivy.app import App +from kivy.clock import Clock +from kivy.config import Config +from kivy.properties import BooleanProperty, StringProperty +from kivy.uix.boxlayout import BoxLayout +from kivy.storage.jsonstore import JsonStore + +Config.set('kivy', 'log_level', 'debug') +Config.set('kivy', 'log_enable', '1') + + +class MainLayout(BoxLayout): + pass + + +class BLETestApp(App): + ble = BluetoothDispatcher() + adapter_state = StringProperty('') + state = StringProperty('') + test_string = StringProperty('') + rssi = StringProperty('') + notification_value = StringProperty('') + counter_value = StringProperty('') + increment_count_value = StringProperty('') + incremental_interval = StringProperty('100') + counter_max = StringProperty('128') + counter_value = StringProperty('') + counter_state = StringProperty('') + counter_total_time = StringProperty('') + queue_timeout_enabled = BooleanProperty(True) + queue_timeout = StringProperty('1000') + device_name = StringProperty('KivyBLETest') + device_address = StringProperty('') + autoconnect = BooleanProperty(False) + + store = JsonStore('bletestapp.json') + + uids = { + 'string': '0d01', + 'counter_reset': '0d02', + 'counter_increment': '0d03', + 'counter_read': '0d04', + 'notifications': '0d05' + } + + def build(self): + if self.store.exists('device'): + self.device_address = self.store.get('device')['address'] + else: + self.device_address = '' + return MainLayout() + + def on_pause(self): + return True + + def on_resume(self): + pass + + def init(self): + self.set_queue_settings() + self.ble.bind(on_device=self.on_device) + self.ble.bind(on_scan_started=self.on_scan_started) + self.ble.bind(on_scan_completed=self.on_scan_completed) + self.ble.bind(on_bluetooth_adapter_state_change=self.on_bluetooth_adapter_state_change) + self.ble.bind( + on_connection_state_change=self.on_connection_state_change) + self.ble.bind(on_services=self.on_services) + self.ble.bind(on_characteristic_read=self.on_characteristic_read) + self.ble.bind(on_characteristic_changed=self.on_characteristic_changed) + self.ble.bind(on_rssi_updated=self.on_rssi_updated) + + def start_scan(self): + if not self.state: + self.init() + self.state = 'scan_start' + self.ble.close_gatt() + self.ble.start_scan() + + def connect_by_mac_address(self): + self.store.put('device', address=self.device_address) + if not self.state: + self.init() + self.state = 'try_connect' + self.ble.close_gatt() + try: + self.ble.connect_by_device_address( + self.device_address, + autoconnect=self.autoconnect, + ) + except ValueError as exc: + self.state = str(exc) + + def on_scan_started(self, ble, success): + self.state = 'scan' if success else 'scan_error' + + def on_device(self, ble, device, rssi, advertisement): + if self.state != 'scan': + return + if device.getName() == self.device_name: + self.device = device + self.state = 'found' + self.ble.stop_scan() + + def on_scan_completed(self, ble): + if self.device: + self.ble.connect_gatt( + self.device, + autoconnect=self.autoconnect, + ) + + def on_connection_state_change(self, ble, status, state): + if status == GATT_SUCCESS: + if state: + self.ble.discover_services() + else: + self.state = 'disconnected' + else: + self.state = 'connection_error' + + def on_services(self, ble, status, services): + if status != GATT_SUCCESS: + self.state = 'services_error' + return + self.state = 'connected' + self.services = services + self.read_test_string(ble) + self.characteristics = { + 'counter_increment': self.services.search( + self.uids['counter_increment']), + 'counter_reset': self.services.search( + self.uids['counter_reset']), + } + + def on_bluetooth_adapter_state_change(self, ble, state): + self.adapter_state = AdapterState(state).name + + def read_rssi(self): + self.rssi = '...' + result = self.ble.update_rssi() + + def on_rssi_updated(self, ble, rssi, status): + self.rssi = str(rssi) if status == GATT_SUCCESS else f"Bad status: {status}" + + def read_test_string(self, ble): + characteristic = self.services.search(self.uids['string']) + if characteristic: + ble.read_characteristic(characteristic) + else: + self.test_string = 'not found' + + def read_remote_counter(self): + characteristic = self.services.search(self.uids['counter_read']) + if characteristic: + self.ble.read_characteristic(characteristic) + else: + self.counter_value = 'error' + + def enable_notifications(self, enable): + if enable: + self.notification_value = '0' + characteristic = self.services.search(self.uids['notifications']) + if characteristic: + self.ble.enable_notifications(characteristic, enable) + else: + self.notification_value = 'error' + + def enable_counter(self, enable): + if enable: + self.counter_state = 'init' + interval = int(self.incremental_interval) * .001 + Clock.schedule_interval(self.counter_next, interval) + else: + Clock.unschedule(self.counter_next) + if self.counter_state != 'stop': + self.counter_state = 'stop' + self.read_remote_counter() + + def counter_next(self, dt): + if self.counter_state == 'init': + self.counter_started_time = time.time() + self.counter_total_time = '' + self.reset_remote_counter() + self.increment_remote_counter() + elif self.counter_state == 'enabled': + if int(self.increment_count_value) < int(self.counter_max): + self.increment_remote_counter() + else: + self.enable_counter(False) + + def reset_remote_counter(self): + self.increment_count_value = '0' + self.counter_value = '' + self.ble.write_characteristic(self.characteristics['counter_reset'], []) + self.counter_state = 'enabled' + + def on_characteristic_read(self, ble, characteristic, status): + uuid = characteristic.getUuid().toString() + if self.uids['string'] in uuid: + self.update_string_value(characteristic, status) + elif self.uids['counter_read'] in uuid: + self.counter_total_time = str( + time.time() - self.counter_started_time) + self.update_counter_value(characteristic, status) + + def update_string_value(self, characteristic, status): + result = 'ERROR' + if status == GATT_SUCCESS: + value = characteristic.getStringValue(0) + if value == 'test': + result = 'OK' + self.test_string = result + + def increment_remote_counter(self): + characteristic = self.characteristics['counter_increment'] + self.ble.write_characteristic(characteristic, []) + prev_value = int(self.increment_count_value) + self.increment_count_value = str(prev_value + 1) + + def update_counter_value(self, characteristic, status): + if status == GATT_SUCCESS: + self.counter_value = characteristic.getStringValue(0) + else: + self.counter_value = 'ERROR' + + def set_queue_settings(self): + self.ble.set_queue_timeout(None if not self.queue_timeout_enabled + else int(self.queue_timeout) * .001) + + def on_characteristic_changed(self, ble, characteristic): + uuid = characteristic.getUuid().toString() + if self.uids['notifications'] in uuid: + prev_value = self.notification_value + value = int(characteristic.getStringValue(0)) + if (prev_value == 'error') or (value != int(prev_value) + 1): + value = 'error' + self.notification_value = str(value) + + +if __name__ == '__main__': + BLETestApp().run() diff --git a/libs/able/testapps/bletest/server.go b/libs/able/testapps/bletest/server.go new file mode 100644 index 0000000..fcb9ced --- /dev/null +++ b/libs/able/testapps/bletest/server.go @@ -0,0 +1,95 @@ +// +build + +// based on https://github.com/paypal/gatt/blob/master/examples/server.go + +package main + +import ( + "fmt" + "log" + "time" + "github.com/paypal/gatt" + "github.com/paypal/gatt/linux/cmd" +) + + +var DefaultServerOptions = []gatt.Option{ + gatt.LnxMaxConnections(1), + gatt.LnxDeviceID(-1, false), + gatt.LnxSetAdvertisingParameters(&cmd.LESetAdvertisingParameters{ + AdvertisingIntervalMin: 0x04ff, + AdvertisingIntervalMax: 0x04ff, + AdvertisingChannelMap: 0x7, + }), +} + + +func NewTestPythonService() *gatt.Service { + n := 0 + s := gatt.NewService(gatt.MustParseUUID("16fe0d00-c111-11e3-b8c8-0002a5d5c51b")) + + s.AddCharacteristic(gatt.MustParseUUID("16fe0d01-c111-11e3-b8c8-0002a5d5c51b")).HandleReadFunc( + func(rsp gatt.ResponseWriter, req *gatt.ReadRequest) { + n = 0 + log.Println("Echo") + fmt.Fprintf(rsp, "test") + }) + s.AddCharacteristic(gatt.MustParseUUID("16fe0d02-c111-11e3-b8c8-0002a5d5c51b")).HandleWriteFunc( + func(r gatt.Request, data []byte) (status byte) { + n = 0 + log.Println("Reset counter") + return gatt.StatusSuccess + }) + s.AddCharacteristic(gatt.MustParseUUID("16fe0d03-c111-11e3-b8c8-0002a5d5c51b")).HandleWriteFunc( + func(r gatt.Request, data []byte) (status byte) { + n++ + log.Println("Increment counter") + return gatt.StatusSuccess + }) + s.AddCharacteristic(gatt.MustParseUUID("16fe0d04-c111-11e3-b8c8-0002a5d5c51b")).HandleReadFunc( + func(rsp gatt.ResponseWriter, req *gatt.ReadRequest) { + log.Println("Response counter: ", n) + fmt.Fprintf(rsp, "%d", n) + }) + + s.AddCharacteristic(gatt.MustParseUUID("16fe0d05-c111-11e3-b8c8-0002a5d5c51b")).HandleNotifyFunc( + func(r gatt.Request, n gatt.Notifier) { + log.Println("Notifications enabled") + cnt := 1 + for !n.Done() { + fmt.Fprintf(n, "%d", cnt) + cnt++ + time.Sleep(100 * time.Millisecond) + } + log.Println("Notifications disabled") + }) + + return s +} + + +func main() { + d, err := gatt.NewDevice(DefaultServerOptions...) + if err != nil { + log.Fatalf("Failed to open device, err: %s", err) + } + + d.Handle( + gatt.CentralConnected(func(c gatt.Central) { fmt.Println("Connect: ", c.ID()) }), + gatt.CentralDisconnected(func(c gatt.Central) { fmt.Println("Disconnect: ", c.ID()) }), + ) + + onStateChanged := func(d gatt.Device, s gatt.State) { + fmt.Printf("State: %s\n", s) + switch s { + case gatt.StatePoweredOn: + s1 := NewTestPythonService() + d.AddService(s1) + d.AdvertiseNameAndServices("KivyBLETest", []gatt.UUID{s1.UUID()}) + default: + } + } + + d.Init(onStateChanged) + select {} +} diff --git a/libs/able/tests/__init__.py b/libs/able/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/libs/able/tests/notebooks/.gitignore b/libs/able/tests/notebooks/.gitignore new file mode 100644 index 0000000..51b09fe --- /dev/null +++ b/libs/able/tests/notebooks/.gitignore @@ -0,0 +1,4 @@ +there.env +.ipynb_checkpoints/ +*.asciidoc +*.ipynb diff --git a/libs/able/tests/notebooks/init.md b/libs/able/tests/notebooks/init.md new file mode 100644 index 0000000..d25939a --- /dev/null +++ b/libs/able/tests/notebooks/init.md @@ -0,0 +1,43 @@ +--- +jupyter: + jupytext: + formats: ipynb,md + text_representation: + extension: .md + format_name: markdown + format_version: '1.3' + jupytext_version: 1.11.2 + kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +```python +from time import sleep +%load_ext pythonhere +%connect-there +``` + +```python +%%there +from dataclasses import dataclass, field +from typing import List + +from jnius import autoclass, cast + +from able.android.dispatcher import ( + BluetoothDispatcher +) + +from able.scan_settings import ( + ScanSettings, + ScanSettingsBuilder +) + +@dataclass +class Results: + started: bool = None + completed: bool = None + devices: List = field(default_factory=lambda: []) +``` diff --git a/libs/able/tests/notebooks/run b/libs/able/tests/notebooks/run new file mode 100755 index 0000000..19d701a --- /dev/null +++ b/libs/able/tests/notebooks/run @@ -0,0 +1,22 @@ +#!/bin/bash +set -ex + +name="$1" +command="${2}" +command="${command:=test}" + + +cat "${name}.md" | + jupytext --execute --to ipynb | + jupyter nbconvert --stdin --no-input --to asciidoc --output "${name}" + +cat "${name}".asciidoc + +if [ "${command}" = "test" ]; then + diff "${name}.asciidoc" "${name}.expected" +elif [ "${command}" = "record" ]; then + cp "${name}".asciidoc "${name}".expected +else + echo "Unknown command: ${command}" + exit 1 +fi diff --git a/libs/able/tests/notebooks/run_all_tests b/libs/able/tests/notebooks/run_all_tests new file mode 100755 index 0000000..7906d87 --- /dev/null +++ b/libs/able/tests/notebooks/run_all_tests @@ -0,0 +1,4 @@ +#!/bin/bash +set -e + +for name in test_*.md; do ./run "${name%%.*}"; done diff --git a/libs/able/tests/notebooks/test_basic.expected b/libs/able/tests/notebooks/test_basic.expected new file mode 100644 index 0000000..bd4bd66 --- /dev/null +++ b/libs/able/tests/notebooks/test_basic.expected @@ -0,0 +1,26 @@ +[[setup]] += Setup + +[[run-ble-devices-scan]] += Run BLE devices scan + + +---- +Started: None Completed: None +---- + +[[check-that-scan-started-and-completed]] += Check that scan started and completed + + +---- +Started: 1 Completed: 1 +---- + +[[check-that-testing-device-was-discovered]] += Check that testing device was discovered + + +---- +True +---- diff --git a/libs/able/tests/notebooks/test_basic.md b/libs/able/tests/notebooks/test_basic.md new file mode 100644 index 0000000..4e16ed9 --- /dev/null +++ b/libs/able/tests/notebooks/test_basic.md @@ -0,0 +1,74 @@ +--- +jupyter: + jupytext: + formats: ipynb,md + text_representation: + extension: .md + format_name: markdown + format_version: '1.3' + jupytext_version: 1.11.2 + kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +# Setup + +```python +%run init.ipynb +``` + +```python +%%there +class BLE(BluetoothDispatcher): + + def on_scan_started(self, success): + results.started = success + + def on_scan_completed(self): + results.completed = 1 + + def on_device(self, device, rssi, advertisement): + results.devices.append(device) + +ble = BLE() +``` + +# Run BLE devices scan + +```python +%%there +results = Results() +print(f"Started: {results.started} Completed: {results.completed}") +ble.start_scan() +``` + +```python +sleep(10) +``` + +```python +%%there +ble.stop_scan() +``` + +```python +sleep(2) +``` + +# Check that scan started and completed + +```python +%%there +print(f"Started: {results.started} Completed: {results.completed}") +``` + +# Check that testing device was discovered + +```python +%%there +print( + "KivyBLETest" in [dev.getName() for dev in results.devices] +) +``` diff --git a/libs/able/tests/notebooks/test_scan_filters.expected b/libs/able/tests/notebooks/test_scan_filters.expected new file mode 100644 index 0000000..165be43 --- /dev/null +++ b/libs/able/tests/notebooks/test_scan_filters.expected @@ -0,0 +1,72 @@ +[[setup]] += Setup + +[[test-device-is-found-with-scan-filters-set]] += Test device is found with scan filters set + + +---- +{'KivyBLETest'} +---- + +[[test-device-is-not-found-filtered-out-by-name]] += Test device is not found: filtered out by name + + +---- +[] +---- + +[[test-scan-filter-mathes]] += Test scan filter mathes + + +---- +EmptyFilter() True +EmptyFilter() True +EmptyFilter() True +---- + + +---- +DeviceAddressFilter(address='AA:AA:AA:AA:AA:AA') True +DeviceAddressFilter(address='AA:AA:AA:AA:AA:AB') False +AA is not a valid Bluetooth address +---- + + +---- +DeviceNameFilter(name='KivyBLETest') True +DeviceNameFilter(name='KivyBLETes') False +---- + + +---- +ManufacturerDataFilter(id=76, data=[], mask=None) False +ManufacturerDataFilter(id=76, data=[], mask=None) True +ManufacturerDataFilter(id=76, data=[2, 21, 141, 166, 131, 214, 229], mask=None) True +ManufacturerDataFilter(id=76, data=[2, 21, 141, 166, 131, 214, 170], mask=None) False +ManufacturerDataFilter(id=76, data=[2, 21, 141, 166, 131, 214, 170], mask=[255, 255, 255, 255, 255, 255, 0]) True +ManufacturerDataFilter(id=76, data=[2, 21, 141, 166, 131, 214, 170], mask=[255, 255, 255, 255, 255, 255, 255]) False +ManufacturerDataFilter(id=76, data=[2, 0, 141, 166, 131], mask=[255, 0, 255, 255, 255]) True +ManufacturerDataFilter(id=76, data=b'\x02\x15', mask=None) True +ManufacturerDataFilter(id=76, data=b'\x02\x16', mask=None) False +---- + + +---- +ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[], mask=None) True +ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fc', data=[], mask=None) False +ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[34], mask=None) True +ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[33], mask=None) False +ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[33], mask=[240]) True +ServiceDataFilter(uid='0000180f-0000-1000-8000-00805f9b34fb', data=[33], mask=[15]) False +---- + + +---- +ServiceUUIDFilter(uid='16fe0d00-c111-11e3-b8c8-0002a5d5c51B', mask=None) True +ServiceUUIDFilter(uid='16fe0d00-c111-11e3-b8c8-0002a5d5c51C', mask=None) False +ServiceUUIDFilter(uid='16fe0d00-c111-11e3-b8c8-0002a5d5c51C', mask='ffffffff-ffff-ffff-ffff-ffffffffffff') False +ServiceUUIDFilter(uid='16fe0d00-c111-11e3-b8c8-0002a5d5c51C', mask='ffffffff-ffff-ffff-ffff-fffffffffff0') True +---- diff --git a/libs/able/tests/notebooks/test_scan_filters.md b/libs/able/tests/notebooks/test_scan_filters.md new file mode 100644 index 0000000..177a6c0 --- /dev/null +++ b/libs/able/tests/notebooks/test_scan_filters.md @@ -0,0 +1,222 @@ +--- +jupyter: + jupytext: + formats: ipynb,md + text_representation: + extension: .md + format_name: markdown + format_version: '1.3' + jupytext_version: 1.11.2 + kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +# Setup + +```python +%run init.ipynb +``` + +```python +%%there +from able.filters import * + +class BLE(BluetoothDispatcher): + + def on_scan_started(self, success): + results.started = success + + def on_scan_completed(self): + results.completed = 1 + + def on_device(self, device, rssi, advertisement): + results.devices.append(device) + +ble = BLE() +``` + +```python +%%there +BluetoothDevice = autoclass("android.bluetooth.BluetoothDevice") +ScanResult = autoclass("android.bluetooth.le.ScanResult") +ScanRecord = autoclass("android.bluetooth.le.ScanRecord") +Parcel = autoclass("android/os/Parcel") +ParcelUuid = autoclass('android.os.ParcelUuid') + +def filter_matches(f, scan_result): + print(f, f.build().matches(scan_result)) + +def mock_device(): + """Return BluetoothDevice instance with address=AA:AA:AA:AA:AA:AA""" + device_data = [17, 0, 0, 0, 65, 0, 65, 0, 58, 0, 65, 0, 65, 0, 58, 0, 65, 0, 65, 0, 58, 0, 65, 0, 65, 0, 58, 0, 65, 0, 65, 0, 58, 0, 65, 0, 65] + p = Parcel.obtain() + p.unmarshall(device_data, 0, len(device_data)) + p.setDataPosition(0) + return BluetoothDevice.CREATOR.createFromParcel(p) + + +def mock_scan_result(record): + return ScanResult(mock_device(), ScanRecord.parseFromBytes(record), -33, 1633954394000) + +def mock_test_app_scan_result(): + return mock_scan_result( + [2, 1, 6, 17, 6, 27, 197, 213, 165, 2, 0, 200, 184, 227, 17, 17, 193, 0, 13, + 254, 22, 12, 9, 75, 105, 118, 121, 66, 76, 69, 84, 101, 115, 116, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ] + ) + +def mock_beacon_scan_result(): + """0x4C, # Apple Manufacturer ID + bytes([ + 0x2, # SubType: Custom Manufacturer Data + 0x15 # Subtype lenth + ]) + + uuid + # UUID of beacon: UUID=8da683d6-e574-4a2e-bb9b-d83f2d05fc12 + bytes([ + 0, 15, # Major value + 0, 1, # Minor value + 10 # RSSI, dBm at 1m + ]) + """ + return mock_scan_result(bytes.fromhex('1AFF4C0002158DA683D6E5744A2EBB9BD83F2D05FC12000F00010A')) + +def mock_battery_scan_result(): + """Battery ("0000180f-0000-1000-8000-00805f9b34fb" or "180f" in short form) + service data: 34% (0x22) + """ + return mock_scan_result(bytes.fromhex('04160F1822')) + +beacon = mock_beacon_scan_result() +battery = mock_battery_scan_result() +testapp = mock_test_app_scan_result() +``` + +# Test device is found with scan filters set + +```python +%%there +results = Results() +ble.start_scan(filters=[ + DeviceNameFilter("KivyBLETest") & ServiceUUIDFilter("16fe0d00-c111-11e3-b8c8-0002a5d5c51b"), +]) +``` + +```python +sleep(10) +``` + +```python +%%there +ble.stop_scan() +``` + +```python +sleep(2) +``` + +```python +%%there +print(set([dev.getName() for dev in results.devices])) +``` + +# Test device is not found: filtered out by name + +```python +%%there +results = Results() +ble.start_scan(filters=[DeviceNameFilter("No-such-device-8458e2e35158")]) +``` + +```python +sleep(10) +``` + +```python +%%there +ble.stop_scan() +``` + +```python +sleep(2) +``` + +```python +%%there +print(results.devices) +``` + +# Test scan filter mathes + +```python +%%there +filter_matches(EmptyFilter(), testapp) +filter_matches(EmptyFilter(), beacon) +filter_matches(EmptyFilter(), battery) +``` + +```python +%%there +filter_matches(DeviceAddressFilter("AA:AA:AA:AA:AA:AA"), testapp) +filter_matches(DeviceAddressFilter("AA:AA:AA:AA:AA:AB"), testapp) +try: + filter_matches(DeviceAddressFilter("AA"), testapp) +except Exception as exc: + print(exc) +``` + +```python +%%there +filter_matches(DeviceNameFilter("KivyBLETest"), testapp) +filter_matches(DeviceNameFilter("KivyBLETes"), testapp) +``` + +```python +%%there +filter_matches(ManufacturerDataFilter(0x4c, []), testapp) +filter_matches(ManufacturerDataFilter(0x4c, []), beacon) +filter_matches(ManufacturerDataFilter(0x4c, [0x2, 0x15, 0x8d, 0xa6, 0x83, 0xd6, 0xe5]), beacon) +filter_matches(ManufacturerDataFilter(0x4c, [0x2, 0x15, 0x8d, 0xa6, 0x83, 0xd6, 0xaa]), beacon) +filter_matches( + ManufacturerDataFilter(0x4c, + [0x2, 0x15, 0x8d, 0xa6, 0x83, 0xd6, 0xaa], + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00]), + beacon +) +filter_matches( + ManufacturerDataFilter(0x4c, + [0x2, 0x15, 0x8d, 0xa6, 0x83, 0xd6, 0xaa], + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), + beacon +) +filter_matches(ManufacturerDataFilter(0x4c, [0x2, 0, 0x8d, 0xa6, 0x83], [0xff, 0, 0xff, 0xff, 0xff]), beacon) +filter_matches(ManufacturerDataFilter(0x4c, b'\x02\x15'), beacon) +filter_matches(ManufacturerDataFilter(0x4c, b'\x02\x16'), beacon) +``` + +```python +%%there +filter_matches(ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", []), battery) +filter_matches(ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fc", []), battery) + +filter_matches(ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", [0x22]), battery) +filter_matches(ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", [0x21]), battery) +filter_matches(ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", [0x21], mask=[0xf0]), battery) +filter_matches(ServiceDataFilter("0000180f-0000-1000-8000-00805f9b34fb", [0x21], mask=[0x0f]), battery) +``` + +```python +%%there +filter_matches(ServiceUUIDFilter("16fe0d00-c111-11e3-b8c8-0002a5d5c51B"), testapp) +filter_matches(ServiceUUIDFilter("16fe0d00-c111-11e3-b8c8-0002a5d5c51C"), testapp) +filter_matches(ServiceUUIDFilter( + "16fe0d00-c111-11e3-b8c8-0002a5d5c51C", + "ffffffff-ffff-ffff-ffff-ffffffffffff" +), testapp) +filter_matches(ServiceUUIDFilter( + "16fe0d00-c111-11e3-b8c8-0002a5d5c51C", + "ffffffff-ffff-ffff-ffff-fffffffffff0" +), testapp) +``` diff --git a/libs/able/tests/notebooks/test_scan_settings.expected b/libs/able/tests/notebooks/test_scan_settings.expected new file mode 100644 index 0000000..8f3caef --- /dev/null +++ b/libs/able/tests/notebooks/test_scan_settings.expected @@ -0,0 +1,27 @@ +[[setup]] += Setup + +[[run-scan_mode_low_power]] += Run SCAN_MODE_LOW_POWER + + +---- +True +---- + +[[run-scan_mode_low_latency]] += Run SCAN_MODE_LOW_LATENCY + + +---- +True +---- + +[[check-that-received-advertisement-count-is-greater-with-scan_mode_low_latency]] += Check that received advertisement count is greater with +SCAN_MODE_LOW_LATENCY + + +---- +True +---- diff --git a/libs/able/tests/notebooks/test_scan_settings.md b/libs/able/tests/notebooks/test_scan_settings.md new file mode 100644 index 0000000..a231bb4 --- /dev/null +++ b/libs/able/tests/notebooks/test_scan_settings.md @@ -0,0 +1,105 @@ +--- +jupyter: + jupytext: + formats: ipynb,md + text_representation: + extension: .md + format_name: markdown + format_version: '1.3' + jupytext_version: 1.11.2 + kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +# Setup + +```python +%run init.ipynb +``` + +```python +%%there +class BLE(BluetoothDispatcher): + + def on_scan_started(self, success): + results.started = success + + def on_scan_completed(self): + results.completed = 1 + + def on_device(self, device, rssi, advertisement): + results.devices.append(device) + +def get_advertisemnt_count(): + return len([dev for dev in results.devices if dev.getName() == "KivyBLETest"]) + +ble = BLE() +``` + +# Run SCAN_MODE_LOW_POWER + +```python +%%there +results = Results() +ble.start_scan( + settings=ScanSettingsBuilder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) +) +``` + +```python +sleep(20) +``` + +```python +%%there +ble.stop_scan() +``` + +```python +sleep(2) +``` + +```python +%%there +low_power_advertisement_count = get_advertisemnt_count() +print(low_power_advertisement_count > 0) +``` + +# Run SCAN_MODE_LOW_LATENCY + +```python +%%there +results = Results() + +ble.start_scan( + settings=ScanSettingsBuilder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) +) +``` + +```python +sleep(20) +``` + +```python +%%there +ble.stop_scan() +``` + +```python +sleep(2) +``` + +```python +%%there +low_latency_advertisement_count = get_advertisemnt_count() +print(low_latency_advertisement_count > 0) +``` + +# Check that received advertisement count is greater with SCAN_MODE_LOW_LATENCY + +```python +%%there +print(low_latency_advertisement_count - low_power_advertisement_count > 2) +``` diff --git a/libs/able/tests/test_adapter.py b/libs/able/tests/test_adapter.py new file mode 100644 index 0000000..7b0f8c0 --- /dev/null +++ b/libs/able/tests/test_adapter.py @@ -0,0 +1,81 @@ +import pytest + +from able.adapter import ( + AdapterManager, + require_bluetooth_enabled, + set_adapter_failure_rollback, +) +from able.android.dispatcher import BluetoothDispatcher + + +@pytest.fixture +def manager(mocker): + return AdapterManager(mocker.Mock(), ..., []) + + +def test_operation_executed(mocker, manager): + operation = mocker.Mock() + logger = mocker.patch("able.adapter.Logger") + + manager.execute(operation) + + operation.assert_called_once() + logger.exception.assert_not_called() + + +def test_operation_failed_as_expected(mocker, manager): + manager.check_permissions = mocker.Mock(return_value=False) + expected = Exception("expected") + operation = mocker.Mock(side_effect=expected) + logger = mocker.patch("able.adapter.Logger") + + manager.execute(operation) + operation.assert_not_called() + + manager.check_permissions = mocker.Mock(return_value=True) + manager.execute_operations() + + operation.assert_called_once() + logger.exception.assert_called_once_with(expected) + + +def test_operations_executed(mocker, manager): + operations = [mocker.Mock(), mocker.Mock()] + manager.operations = operations.copy() + manager.check_permissions = mocker.Mock(return_value=False) + + manager.execute_operations() + + # permissions not granted = > suspended + calls = [operation.call_count for operation in manager.operations] + assert calls == [0, 0] + assert manager.operations == operations + + # one more operation requested + manager.execute(next_operation := mocker.Mock()) + + assert [operation.call_count for operation in manager.operations] == [0, 0, 0] + assert manager.operations == operations + [next_operation] + + manager.check_permissions = mocker.Mock(return_value=True) + manager.execute_operations() + assert not manager.operations + assert [operation.call_count for operation in operations + [next_operation]] == [ + 1, + 1, + 1, + ] + + +def test_rollback_performed(mocker, manager): + handlers = [mocker.Mock(), mocker.Mock()] + operations = [mocker.Mock(), mocker.Mock()] + + manager.operations = operations.copy() + manager.rollback_handlers = handlers.copy() + manager.rollback() + + assert not manager.rollback_handlers + assert not manager.operations + assert [operation.call_count for operation in operations] == [0, 0] + assert [operation.call_count for operation in handlers] == [1, 1] diff --git a/libs/able/tests/test_ble_queue.py b/libs/able/tests/test_ble_queue.py new file mode 100644 index 0000000..a6fcdc8 --- /dev/null +++ b/libs/able/tests/test_ble_queue.py @@ -0,0 +1,34 @@ +import unittest +import mock +from able.queue import ble_task + + +class TestBLETask(unittest.TestCase): + + def setUp(self): + self.queue = mock.Mock() + self.task_called = None + + @ble_task + def increment(self, a=1, b=0): + self.task_called = a + b + + def test_method_not_executed(self): + self.increment() + self.assertEqual(self.task_called, None) + + def test_task_enqued(self): + self.increment() + self.assertTrue(self.queue.enque.called) + + def test_task_default_arguments(self): + self.increment() + task = self.queue.enque.call_args[0][0] + task() + self.assertEqual(self.task_called, 1) + + def test_task_arguments_passed(self): + self.increment(200, 11) + task = self.queue.enque.call_args[0][0] + task() + self.assertEqual(self.task_called, 211) diff --git a/libs/able/tests/test_dispatcher.py b/libs/able/tests/test_dispatcher.py new file mode 100644 index 0000000..637c189 --- /dev/null +++ b/libs/able/tests/test_dispatcher.py @@ -0,0 +1,47 @@ +import pytest + +from able.android.dispatcher import BluetoothDispatcher + + +@pytest.fixture +def ble(mocker): + mocker.patch("able.android.dispatcher.PythonBluetooth") + ble = BluetoothDispatcher() + ble._ble = mocker.Mock() + ble.on_scan_started = mocker.Mock() + return ble + + +def test_adapter_returned(mocker, ble): + manager = ble._adapter_manager + manager.check_permissions = mocker.Mock(return_value=False) + assert not ble.adapter + assert not ble.adapter + + manager.check_permissions = mocker.Mock(return_value=True) + assert ble.adapter + + +def test_start_scan_executed(ble): + manager = ble._adapter_manager + assert manager + + ble.start_scan() + ble._ble.startScan.assert_called_once() + + +def test_start_scan_failed_as_expected(mocker, ble): + manager = ble._adapter_manager + manager.check_permissions = mocker.Mock(return_value=False) + + ble.start_scan() + ble._ble.startScan.assert_not_called() + + assert len(manager.operations) == 1 + assert len(manager.rollback_handlers) == 1 + + manager.on_runtime_permissions(permissions=[...], grant_results=[False]) + + ble.on_scan_started.assert_called_once_with(success=False) + assert len(manager.operations) == 0 + assert len(manager.rollback_handlers) == 0 diff --git a/libs/able/tests/test_filters.py b/libs/able/tests/test_filters.py new file mode 100644 index 0000000..bd2f446 --- /dev/null +++ b/libs/able/tests/test_filters.py @@ -0,0 +1,50 @@ +import pytest + +import able.filters as filters + + +@pytest.fixture +def java_builder(mocker): + instance = mocker.Mock() + mocker.patch("able.filters.ScanFilterBuilder", return_value=instance) + return instance + + +def test_filter_builded(java_builder): + filters.Filter().build() + assert java_builder.build.call_count == 1 + + +def test_builder_method_called(java_builder): + f = filters.DeviceNameFilter("test") + + f.build() + + assert java_builder.method_calls == [ + ("setDeviceName", ("test",)), + ("build", ) + ] + + +def test_filters_combined(java_builder): + f = filters.DeviceNameFilter("test") & ( + filters.DeviceAddressFilter("AA:AA:AA:AA:AA:AA") & + filters.ManufacturerDataFilter("test-id", [1, 2, 3]) + ) + + f.build() + + assert java_builder.method_calls == [ + ("setDeviceName", ("test",)), + ("setDeviceAddress", ("AA:AA:AA:AA:AA:AA",)), + ("setManufacturerData", ("test-id", [1, 2, 3])), + ("build", ) + ] + + +def test_combine_same_type_exception(java_builder): + with pytest.raises(ValueError, match="cannot combine filters of the same type"): + f = filters.DeviceNameFilter("test") & ( + filters.DeviceAddressFilter("AA:AA:AA:AA:AA:AA") & + filters.DeviceNameFilter("test2") + ) diff --git a/libs/able/tests/test_setup.py b/libs/able/tests/test_setup.py new file mode 100644 index 0000000..53dfca3 --- /dev/null +++ b/libs/able/tests/test_setup.py @@ -0,0 +1,30 @@ +from pathlib import Path +import pytest + + +@pytest.fixture +def parser(mocker): + mocker.patch("setuptools.setup") + from setup import PathParser + + return PathParser() + + +@pytest.mark.parametrize( + ("cppflags", "expected"), + [ + ( + "-I/media/able/examples/alert/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/alert_mi/", + "/media/able/examples/alert/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/javaclasses/alert_mi", + ), + ( + "-DANDROID -I/home/user/.buildozer/android/platform/android-ndk-r25b/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include -I/media/able/examples/alert/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/alert_mi/arm64-v8a/include/python3.9", + "/media/able/examples/alert/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/javaclasses/alert_mi", + ), + ], +) +def test_javaclass_dir_found(mocker, parser, cppflags, expected): + mocker.patch("os.environ", {"CPPFLAGS": cppflags}) + mocker.patch("pathlib.Path.exists", return_value=True) + mocker.patch("pathlib.Path.mkdir") + assert parser.javaclass_dir == Path(expected) From 2758b571ff4b948a6aeea1b54ee42a23cac618f9 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 29 Oct 2025 15:45:25 +0100 Subject: [PATCH 116/271] WeaveInterface compatibility on Android --- sbapp/services/sidebandservice.py | 18 +++++- sbapp/sideband/core.py | 94 +++++++++++++++++++++++++------ 2 files changed, 94 insertions(+), 18 deletions(-) diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index f76ccb6..3265023 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -61,7 +61,7 @@ class SidebandService(): 0x0483: [0x5740], # ST CDC 0x2E8A: [0x0005, 0x000A], # Raspberry Pi Pico 0x239A: [0x8029], # Adafruit (RAK4631) - 0x303A: [0x1001], # ESP-32S3 + 0x303A: [0x1001, 0x4001], # ESP-32S3 } def android_notification(self, title="", content="", ticker="", group=None, context_id=None): @@ -380,6 +380,22 @@ class SidebandService(): stat += f"[b]RNode[/b]\n{rs}{bs}\n\n" + if self.sideband.interface_weave != None: + if self.sideband.interface_weave.online: rs = "Connected" + else: rs = "Interface Down" + + # bs = "" + # bat_state = self.sideband.interface_weave.get_battery_state_string() + # bat_percent = self.sideband.interface_weave.get_battery_percent() + # if bat_state != "unknown": + # bs = f"\nBattery at {bat_percent}%" + + np = len(self.sideband.interface_weave.peers) + if np == 1: ws = "1 reachable peer" + else: ws = str(np)+" reachable peers" + + stat += f"[b]Weave[/b]\n{rs}\n{ws}\n\n" + if self.sideband.interface_modem != None: if self.sideband.interface_modem.online: rm = "Connected" diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 4c62d36..5eaeb4f 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -283,6 +283,7 @@ class SidebandCore(): self.last_if_change_announce = 0 self.interface_local_adding = False self.interface_rnode_adding = False + self.interface_weave_adding = False self.next_auto_announce = time.time() + 60*(random.random()*(SidebandCore.AUTO_ANNOUNCE_RANDOM_MAX-SidebandCore.AUTO_ANNOUNCE_RANDOM_MIN)+SidebandCore.AUTO_ANNOUNCE_RANDOM_MIN) try: @@ -685,6 +686,12 @@ class SidebandCore(): self.config["connect_modem_ifac_netname"] = "" if not "connect_modem_ifac_passphrase" in self.config: self.config["connect_modem_ifac_passphrase"] = "" + if not "connect_weave" in self.config: + self.config["connect_weave"] = False + if not "connect_weave_ifac_netname" in self.config: + self.config["connect_weave_ifac_netname"] = "" + if not "connect_weave_ifac_passphrase" in self.config: + self.config["connect_weave_ifac_passphrase"] = "" if not "connect_ifmode_local" in self.config: self.config["connect_ifmode_local"] = "full" @@ -700,6 +707,8 @@ class SidebandCore(): self.config["connect_ifmode_serial"] = "full" if not "connect_ifmode_bluetooth" in self.config: self.config["connect_ifmode_bluetooth"] = "full" + if not "connect_ifmode_weave" in self.config: + self.config["connect_ifmode_weave"] = "full" if not "hw_rnode_frequency" in self.config: self.config["hw_rnode_frequency"] = None @@ -3343,9 +3352,7 @@ class SidebandCore(): def mqtt_handle_telemetry(self, context_dest, telemetry): with self.mqtt_handle_lock: - # TODO: Remove debug if hasattr(self, "last_mqtt_recycle") and time.time() > self.last_mqtt_recycle + 60*4: - # RNS.log("Recycling MQTT handler", RNS.LOG_DEBUG) self.mqtt.stop() self.mqtt.client = None self.mqtt = None @@ -3359,21 +3366,6 @@ class SidebandCore(): self.mqtt.set_auth(self.config["telemetry_mqtt_user"], self.config["telemetry_mqtt_pass"]) self.mqtt.handle(context_dest, telemetry) - # TODO: Remove debug - # if not hasattr(self, "memtr"): - # from pympler import muppy - # from pympler import summary - # import resource - # self.res = resource - # self.ms = summary; self.mp = muppy - # self.memtr = self.ms.summarize(self.mp.get_objects()) - # RNS.log(f"RSS: {RNS.prettysize(self.res.getrusage(self.res.RUSAGE_SELF).ru_maxrss*1000)}") - # else: - # memsum = self.ms.summarize(self.mp.get_objects()) - # memdiff = self.ms.get_diff(self.memtr, memsum) - # self.ms.print_(memdiff) - # RNS.log(f"RSS: {RNS.prettysize(self.res.getrusage(self.res.RUSAGE_SELF).ru_maxrss*1000)}") - def update_telemetry(self): try: try: @@ -3730,6 +3722,18 @@ class SidebandCore(): if self.interface_serial.port != target_device["port"]: RNS.log("Updating serial device to "+str(target_device)) self.interface_serial.port = target_device["port"] + + if self.interface_weave != None and not self.interface_weave.online: + self.owner_app.discover_usb_devices() + last_usb_discovery = time.time() + + if hasattr(self.owner_app, "usb_devices") and self.owner_app.usb_devices != None: + if len(self.owner_app.usb_devices) > 0: + target_device = self.owner_app.usb_devices[0] + if self.interface_weave.port != target_device["port"]: + RNS.log("Updating Weave device to "+str(target_device)) + self.interface_weave.port = target_device["port"] + self.interface_weave.connection.port = target_device["port"] if self.interface_modem != None and not self.interface_modem.online: self.owner_app.discover_usb_devices() @@ -3935,6 +3939,58 @@ class SidebandCore(): self.interface_local = None self.interface_local_adding = False + def __add_weaveinterface(self, delay=None): + self.interface_weave_adding = True + if delay: time.sleep(delay) + try: + RNS.log("Adding Weave Interface...", RNS.LOG_DEBUG) + target_device = None + + # TODO: Add more intelligent selection here + if len(self.owner_app.usb_devices) > 0: target_device = self.owner_app.usb_devices[0] + + if target_device != None: target_port = target_device["port"] + else: target_port = None + + if self.config["connect_weave_ifac_netname"] == "": ifac_netname = None + else: ifac_netname = self.config["connect_weave_ifac_netname"] + + if self.config["connect_weave_ifac_passphrase"] == "": ifac_netkey = None + else: ifac_netkey = self.config["connect_weave_ifac_passphrase"] + + interface_config = { "name": "WeaveInterface", + "port": target_port } + + weaveinterface = RNS.Interfaces.WeaveInterface.WeaveInterface(RNS.Transport, interface_config) + weaveinterface.OUT = True + + if RNS.Reticulum.transport_enabled(): + if_mode = Interface.Interface.MODE_FULL + if self.config["connect_ifmode_weave"] == "gateway": + if_mode = Interface.Interface.MODE_GATEWAY + elif self.config["connect_ifmode_weave"] == "access point": + if_mode = Interface.Interface.MODE_ACCESS_POINT + elif self.config["connect_ifmode_weave"] == "roaming": + if_mode = Interface.Interface.MODE_ROAMING + elif self.config["connect_ifmode_weave"] == "boundary": + if_mode = Interface.Interface.MODE_BOUNDARY + else: + if_mode = None + + self.reticulum._add_interface(weaveinterface, mode = if_mode, ifac_netname = ifac_netname, ifac_netkey = ifac_netkey) + self.interface_weave = weaveinterface + self.interface_weave_adding = False + + if weaveinterface != None: + if len(weaveinterface.hw_errors) > 0: + self.setpersistent("startup.errors.weave", weaveinterface.hw_errors[0]) + + except Exception as e: + RNS.log("Error while adding Weave Interface. The contained exception was: "+str(e)) + RNS.trace_exception(e) + self.interface_weave = None + self.interface_weave_adding = False + def __add_rnodeinterface(self, delay=None): self.interface_rnode_adding = True if delay: @@ -4269,6 +4325,10 @@ class SidebandCore(): self.setstate("init.loadingstate", "Starting RNode") self.__add_rnodeinterface() + if self.config["connect_weave"] or True: + self.setstate("init.loadingstate", "Starting Weave") + self.__add_weaveinterface() + elif self.config["connect_serial"]: self.setstate("init.loadingstate", "Starting Serial Interface") try: From 6802161b4f8d4bda77dc0013c5a3c37d77684b78 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 31 Oct 2025 22:28:08 +0100 Subject: [PATCH 117/271] Updates for LXMF 0.9.0 compatibility --- sbapp/sideband/core.py | 41 ++++++++++++++++++++++++++++++++++------- sbapp/ui/announces.py | 15 +++++++++++++-- sbapp/ui/messages.py | 7 +++++++ 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 5eaeb4f..725c297 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -53,7 +53,7 @@ class PropagationNodeDetector(): if app_data != None and len(app_data) > 0: if pn_announce_data_is_valid(app_data): unpacked = msgpack.unpackb(app_data) - node_active = unpacked[0] + node_active = unpacked[2] emitted = unpacked[1] hops = RNS.Transport.hops_to(destination_hash) @@ -67,10 +67,8 @@ class PropagationNodeDetector(): # age = 0 pass - if self.owner_app != None: - stat_endpoint = self.owner_app.sideband - else: - stat_endpoint = self.owner + 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), @@ -2126,6 +2124,9 @@ class SidebandCore(): elif "get_lxm_stamp_cost" in call: args = call["get_lxm_stamp_cost"] connection.send(self.get_lxm_stamp_cost(args["lxm_hash"])) + elif "get_lxm_propagation_cost" in call: + args = call["get_lxm_propagation_cost"] + connection.send(self.get_lxm_propagation_cost(args["lxm_hash"])) elif "is_tracking" in call: connection.send(self.is_tracking(call["is_tracking"])) elif "start_tracking" in call: @@ -2808,8 +2809,8 @@ class SidebandCore(): announced_name = LXMF.display_name_from_app_data(app_data) announced_cost = self.message_router.get_outbound_stamp_cost(entry[2]) else: - announced_name = None - announced_cost = None + announced_name = LXMF.pn_name_from_app_data(app_data) + announced_cost = LXMF.pn_stamp_cost_from_app_data(app_data) announce = { "dest" : entry[2], "name" : announced_name, @@ -4643,6 +4644,32 @@ class SidebandCore(): RNS.log("An error occurred while getting message transfer stamp cost: "+str(e), RNS.LOG_ERROR) return None + def _service_get_lxm_propagation_cost(self, lxm_hash): + if not RNS.vendor.platformutils.is_android(): return False + else: + if self.is_client: + try: return self.service_rpc_request({"get_lxm_propagation_cost": { "lxm_hash": lxm_hash } }) + except Exception as e: + RNS.log("Error while sending message over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + + else: return False + + def get_lxm_propagation_cost(self, lxm_hash): + if self.allow_service_dispatch and self.is_client: + try: return self._service_get_lxm_propagation_cost(lxm_hash) + except Exception as e: + RNS.log("Error while getting message transfer stamp cost: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + + else: + try: return self.message_router.get_outbound_lxm_propagation_stamp_cost(lxm_hash) + except Exception as e: + RNS.log("An error occurred while getting message propagation 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 diff --git a/sbapp/ui/announces.py b/sbapp/ui/announces.py index f9bc28d..52ed461 100644 --- a/sbapp/ui/announces.py +++ b/sbapp/ui/announces.py @@ -127,7 +127,16 @@ class Announces(): ad_text = "[size=22dp]LXMF Peer[/size]\n\n[b]Received[/b] "+ts+"\n[b]Address[/b] "+RNS.prettyhexrep(dest)+"\n[b]Name[/b] "+name+"\n[b]Stamp Cost[/b] "+cost+link_extras if dtype == "lxmf.propagation": - ad_text = "[size=22dp]LXMF Propagation Node[/size]\n\n[b]Received[/b] "+ts+"\n[b]Address[/b] "+RNS.prettyhexrep(dest)+link_extras + if a_name: + disp_name = multilingual_markup(escape_markup(str(a_name)).encode("utf-8")).decode("utf-8") + disp_name = f"\n[b]Name[/b] {disp_name}" + else: disp_name = "" + if a_cost: + disp_cost = str(a_cost) + disp_cost = f"\n[b]Stamp Cost[/b] {disp_cost}" + else: disp_cost = "" + + ad_text = f"[size=22dp]LXMF Propagation Node[/size]\n\n[b]Received[/b] {ts}\n[b]Address[/b] {RNS.prettyhexrep(dest)+link_extras}{disp_name}{disp_cost}" dialog = MDDialog( text=ad_text, @@ -150,7 +159,9 @@ class Announces(): iconl = IconLeftWidget(icon=trust_icon) elif dest_type == "lxmf.propagation": - disp_name = "Propagation Node "+RNS.prettyhexrep(context_dest) + if a_name: disp_name = multilingual_markup(escape_markup(str(a_name)).encode("utf-8")).decode("utf-8") + else: disp_name = f"Propagation Node" + disp_name = f"{disp_name} {RNS.prettyhexrep(context_dest)}" iconl = IconLeftWidget(icon="upload-network") else: diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 80f82a5..6c54704 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -336,9 +336,16 @@ class Messages(): prgstr = ", "+str(round(prg*100, 1))+"% done" if prg <= 0.00: stamp_cost = self.app.sideband.get_lxm_stamp_cost(msg["hash"]) + prop_cost = self.app.sideband.get_lxm_propagation_cost(msg["hash"]) if stamp_cost: sphrase = f"Generating stamp with cost {stamp_cost}" prgstr = "" + elif prop_cost: + sphrase = f"Generating propagation stamp with cost {prop_cost}" + prgstr = "" + elif stamp_cost and prop_cost: + sphrase = f"Generating stamps with cost {stamp_cost} and {prop_cost}" + prgstr = "" else: sphrase = "Waiting for path" elif prg <= 0.01: From 42d859f96e8a343e13506cb0d4bb8abb2467fe73 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 1 Nov 2025 00:03:24 +0100 Subject: [PATCH 118/271] Improved audio processing for voice optimizaiton. Fixes #82. --- sbapp/sideband/audioproc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/sideband/audioproc.py b/sbapp/sideband/audioproc.py index fcca182..c973342 100644 --- a/sbapp/sideband/audioproc.py +++ b/sbapp/sideband/audioproc.py @@ -105,7 +105,7 @@ def voice_processing(input_path): ffmpeg = None ffmpeg = sh.ffmpeg if ffmpeg: - filters = "highpass=f=250, lowpass=f=3000,speechnorm=e=12.5:r=0.0001:l=1" + filters = "atrim=start=0.075, afade=t=in:st=0:d=0.085, highpass=f=250, lowpass=f=3000, speechnorm=e=12.5:r=0.0001:l=1" output_bitrate = "12k" opus_apptype = "audio" output_path = input_path.replace(".ogg","")+".p.ogg" From 9a3cda077cf345c78ab6ee88ba4e1b4737b85dd1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 1 Nov 2025 23:33:49 +0100 Subject: [PATCH 119/271] Implemented workaround for Kivy/SDL bug where on_resume is not dispatched on Android --- sbapp/Makefile | 5 + sbapp/main.py | 43 +- sbapp/patches/PythonActivity.java | 646 ++++++++++++++++++++++++++++++ sbapp/sideband/core.py | 3 +- sbapp/ui/conversations.py | 1 + sbapp/ui/layouts.py | 16 +- 6 files changed, 698 insertions(+), 16 deletions(-) create mode 100644 sbapp/patches/PythonActivity.java diff --git a/sbapp/Makefile b/sbapp/Makefile index 943ac9d..a95c081 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -28,6 +28,11 @@ patchsdl: cp patches/PythonService.java .buildozer/android/platform/build-arm64-v8a/build/bootstrap_builds/sdl2/src/main/java/org/kivy/android/PythonService.java cp patches/PythonService.java .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/java/org/kivy/android/PythonService.java + # Pach python activity + cp patches/PythonActivity.java .buildozer/android/platform/python-for-android/pythonforandroid/bootstraps/sdl2/build/src/main/java/org/kivy/android/PythonActivity.java + cp patches/PythonActivity.java .buildozer/android/platform/build-arm64-v8a/build/bootstrap_builds/sdl2/src/main/java/org/kivy/android/PythonActivity.java + cp patches/PythonActivity.java .buildozer/android/platform/build-arm64-v8a/dists/sideband/src/main/java/org/kivy/android/PythonActivity.java + patchpycodec2: patchelf --replace-needed libcodec2.so.1.2 libcodec2.so .buildozer/android/platform/build-arm64-v8a/dists/sideband/_python_bundle__arm64-v8a/_python_bundle/site-packages/pycodec2/pycodec2.so # patchelf --replace-needed libcodec2.so.1.2 libcodec2.so .buildozer/android/platform/build-arm64-v8a/dists/sideband/_python_bundle__armeabi-v7a/_python_bundle/site-packages/pycodec2/pycodec2.so diff --git a/sbapp/main.py b/sbapp/main.py index 8039d64..a188bf7 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -405,6 +405,7 @@ class SidebandApp(MDApp): self.icon = self.sideband.asset_dir+"/icon.png" self.notification_icon = self.sideband.asset_dir+"/notification_icon.png" + self.resume_event_scheduler = None self.connectivity_updater = None self.last_map_update = 0 self.last_telemetry_received = 0 @@ -830,16 +831,18 @@ class SidebandApp(MDApp): def on_pause(self): if self.sideband: RNS.log("App pausing...", RNS.LOG_DEBUG) + + if RNS.vendor.platformutils.is_android(): + if self.resume_event_scheduler == None: + self.resume_event_scheduler = Clock.schedule_interval(self.perform_paused_check, 0.1) + self.sideband.setstate("app.running", True) self.sideband.setstate("app.foreground", False) self.app_state = SidebandApp.PAUSED self.sideband.should_persist_data() - if self.conversations_view != None: - self.conversations_view.ids.conversations_scrollview.effect_cls = ScrollEffect - self.conversations_view.ids.conversations_scrollview.scroll = 1 - RNS.log("App paused", RNS.LOG_DEBUG) return True + else: return True @@ -850,17 +853,10 @@ class SidebandApp(MDApp): self.sideband.setstate("app.foreground", True) self.sideband.setstate("wants.clear_notifications", True) self.app_state = SidebandApp.ACTIVE - if self.conversations_view != None: - self.conversations_view.ids.conversations_scrollview.effect_cls = ScrollEffect - self.conversations_view.ids.conversations_scrollview.scroll = 1 - - else: - RNS.log("Conversations view did not exist", RNS.LOG_DEBUG) def ui_update_job(): time.sleep(0.05) - def cb(dt): - self.perform_wake_update() + def cb(dt): self.perform_wake_update() Clock.schedule_once(cb, 0.1) threading.Thread(target=ui_update_job, daemon=True).start() @@ -879,6 +875,29 @@ class SidebandApp(MDApp): else: return False + def perform_paused_check(self, delta_time): + # This workaround mitigates yet another bug in Kivy + # on Android, where the JNI/Python bridge now for + # Lord knows whatever reason fails to dispatch the + # onResume event from the Android app lifecycle + # management API. So we have to resort to this hack + # of scheduling a manual check that reads a patched- + # in property on the JNI side of the app activity, + # and then "manually" dispatch on_resume. + if self.app_state == SidebandApp.PAUSED: + # Oh hai, we're running, but we should really + # be paused? What gives? Must mean we've been + # woken up again, but someone forgot to inform + # us about that. Let's have a look, shall we... + activity = autoclass('org.kivy.android.PythonActivity').mActivity + if activity.activityPaused == False: + # Who would have thought, the activity was + # resumed! Good thing we can play event- + # dispatch pretend ourselves. + Clock.unschedule(self.resume_event_scheduler) + self.resume_event_scheduler = None + self.on_resume() + def perform_wake_update(self): # This workaround mitigates a bug in Kivy on Android # which causes the UI to turn black on app resume, diff --git a/sbapp/patches/PythonActivity.java b/sbapp/patches/PythonActivity.java new file mode 100644 index 0000000..fc58960 --- /dev/null +++ b/sbapp/patches/PythonActivity.java @@ -0,0 +1,646 @@ +package org.kivy.android; + +import java.io.InputStream; +import java.io.FileWriter; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Color; +import android.graphics.PixelFormat; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.PowerManager; +import android.util.Log; +import android.view.inputmethod.InputMethodManager; +import android.view.SurfaceView; +import android.view.ViewGroup; +import android.view.View; +import android.widget.ImageView; +import android.widget.Toast; +import android.content.res.Resources.NotFoundException; + +import org.libsdl.app.SDLActivity; + +import org.kivy.android.launcher.Project; + +import org.renpy.android.ResourceManager; + + +public class PythonActivity extends SDLActivity { + private static final String TAG = "PythonActivity"; + + public static PythonActivity mActivity = null; + public boolean activityPaused = false; + + private ResourceManager resourceManager = null; + private Bundle mMetaData = null; + private PowerManager.WakeLock mWakeLock = null; + + public String getAppRoot() { + String app_root = getFilesDir().getAbsolutePath() + "/app"; + return app_root; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + Log.v(TAG, "PythonActivity onCreate running"); + resourceManager = new ResourceManager(this); + + Log.v(TAG, "About to do super onCreate"); + super.onCreate(savedInstanceState); + Log.v(TAG, "Did super onCreate"); + + this.mActivity = this; + this.showLoadingScreen(this.getLoadingScreen()); + + new UnpackFilesTask().execute(getAppRoot()); + } + + public void loadLibraries() { + String app_root = new String(getAppRoot()); + File app_root_file = new File(app_root); + PythonUtil.loadLibraries(app_root_file, + new File(getApplicationInfo().nativeLibraryDir)); + } + + /** + * Show an error using a toast. (Only makes sense from non-UI + * threads.) + */ + public void toastError(final String msg) { + + final Activity thisActivity = this; + + runOnUiThread(new Runnable () { + public void run() { + Toast.makeText(thisActivity, msg, Toast.LENGTH_LONG).show(); + } + }); + + // Wait to show the error. + synchronized (this) { + try { + this.wait(1000); + } catch (InterruptedException e) { + } + } + } + + private class UnpackFilesTask extends AsyncTask { + @Override + protected String doInBackground(String... params) { + File app_root_file = new File(params[0]); + Log.v(TAG, "Ready to unpack"); + PythonUtil.unpackAsset(mActivity, "private", app_root_file, true); + PythonUtil.unpackPyBundle(mActivity, getApplicationInfo().nativeLibraryDir + "/" + "libpybundle", app_root_file, false); + return null; + } + + @Override + protected void onPostExecute(String result) { + // Figure out the directory where the game is. If the game was + // given to us via an intent, then we use the scheme-specific + // part of that intent to determine the file to launch. We + // also use the android.txt file to determine the orientation. + // + // Otherwise, we use the public data, if we have it, or the + // private data if we do not. + mActivity.finishLoad(); + + // finishLoad called setContentView with the SDL view, which + // removed the loading screen. However, we still need it to + // show until the app is ready to render, so pop it back up + // on top of the SDL view. + mActivity.showLoadingScreen(getLoadingScreen()); + + String app_root_dir = getAppRoot(); + if (getIntent() != null && getIntent().getAction() != null && + getIntent().getAction().equals("org.kivy.LAUNCH")) { + File path = new File(getIntent().getData().getSchemeSpecificPart()); + + Project p = Project.scanDirectory(path); + String entry_point = getEntryPoint(p.dir); + SDLActivity.nativeSetenv("ANDROID_ENTRYPOINT", p.dir + "/" + entry_point); + SDLActivity.nativeSetenv("ANDROID_ARGUMENT", p.dir); + SDLActivity.nativeSetenv("ANDROID_APP_PATH", p.dir); + + if (p != null) { + if (p.landscape) { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + } else { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } + } + + // Let old apps know they started. + try { + FileWriter f = new FileWriter(new File(path, ".launch")); + f.write("started"); + f.close(); + } catch (IOException e) { + // pass + } + } else { + String entry_point = getEntryPoint(app_root_dir); + SDLActivity.nativeSetenv("ANDROID_ENTRYPOINT", entry_point); + SDLActivity.nativeSetenv("ANDROID_ARGUMENT", app_root_dir); + SDLActivity.nativeSetenv("ANDROID_APP_PATH", app_root_dir); + } + + String mFilesDirectory = mActivity.getFilesDir().getAbsolutePath(); + Log.v(TAG, "Setting env vars for start.c and Python to use"); + SDLActivity.nativeSetenv("ANDROID_PRIVATE", mFilesDirectory); + SDLActivity.nativeSetenv("ANDROID_UNPACK", app_root_dir); + SDLActivity.nativeSetenv("PYTHONHOME", app_root_dir); + SDLActivity.nativeSetenv("PYTHONPATH", app_root_dir + ":" + app_root_dir + "/lib"); + SDLActivity.nativeSetenv("PYTHONOPTIMIZE", "2"); + + try { + Log.v(TAG, "Access to our meta-data..."); + mActivity.mMetaData = mActivity.getPackageManager().getApplicationInfo( + mActivity.getPackageName(), PackageManager.GET_META_DATA).metaData; + + PowerManager pm = (PowerManager) mActivity.getSystemService(Context.POWER_SERVICE); + if ( mActivity.mMetaData.getInt("wakelock") == 1 ) { + mActivity.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "Screen On"); + mActivity.mWakeLock.acquire(); + } + if ( mActivity.mMetaData.getInt("surface.transparent") != 0 ) { + Log.v(TAG, "Surface will be transparent."); + getSurface().setZOrderOnTop(true); + getSurface().getHolder().setFormat(PixelFormat.TRANSPARENT); + } else { + Log.i(TAG, "Surface will NOT be transparent"); + } + } catch (PackageManager.NameNotFoundException e) { + } + + // Launch app if that hasn't been done yet: + if (mActivity.mHasFocus && ( + // never went into proper resume state: + mActivity.mCurrentNativeState == NativeState.INIT || + ( + // resumed earlier but wasn't ready yet + mActivity.mCurrentNativeState == NativeState.RESUMED && + mActivity.mSDLThread == null + ))) { + // Because sometimes the app will get stuck here and never + // actually run, ensure that it gets launched if we're active: + mActivity.resumeNativeThread(); + } + } + + @Override + protected void onPreExecute() { + } + + @Override + protected void onProgressUpdate(Void... values) { + } + } + + public static ViewGroup getLayout() { + return mLayout; + } + + public static SurfaceView getSurface() { + return mSurface; + } + + //---------------------------------------------------------------------------- + // Listener interface for onNewIntent + // + + public interface NewIntentListener { + void onNewIntent(Intent intent); + } + + private List newIntentListeners = null; + + public void registerNewIntentListener(NewIntentListener listener) { + if ( this.newIntentListeners == null ) + this.newIntentListeners = Collections.synchronizedList(new ArrayList()); + this.newIntentListeners.add(listener); + } + + public void unregisterNewIntentListener(NewIntentListener listener) { + if ( this.newIntentListeners == null ) + return; + this.newIntentListeners.remove(listener); + } + + @Override + protected void onNewIntent(Intent intent) { + if ( this.newIntentListeners == null ) + return; + this.onResume(); + synchronized ( this.newIntentListeners ) { + Iterator iterator = this.newIntentListeners.iterator(); + while ( iterator.hasNext() ) { + (iterator.next()).onNewIntent(intent); + } + } + } + + //---------------------------------------------------------------------------- + // Listener interface for onActivityResult + // + + public interface ActivityResultListener { + void onActivityResult(int requestCode, int resultCode, Intent data); + } + + private List activityResultListeners = null; + + public void registerActivityResultListener(ActivityResultListener listener) { + if ( this.activityResultListeners == null ) + this.activityResultListeners = Collections.synchronizedList(new ArrayList()); + this.activityResultListeners.add(listener); + } + + public void unregisterActivityResultListener(ActivityResultListener listener) { + if ( this.activityResultListeners == null ) + return; + this.activityResultListeners.remove(listener); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent intent) { + if ( this.activityResultListeners == null ) + return; + this.onResume(); + synchronized ( this.activityResultListeners ) { + Iterator iterator = this.activityResultListeners.iterator(); + while ( iterator.hasNext() ) + (iterator.next()).onActivityResult(requestCode, resultCode, intent); + } + } + + public static void start_service( + String serviceTitle, + String serviceDescription, + String pythonServiceArgument + ) { + _do_start_service( + serviceTitle, serviceDescription, pythonServiceArgument, true + ); + } + + public static void start_service_not_as_foreground( + String serviceTitle, + String serviceDescription, + String pythonServiceArgument + ) { + _do_start_service( + serviceTitle, serviceDescription, pythonServiceArgument, false + ); + } + + public static void _do_start_service( + String serviceTitle, + String serviceDescription, + String pythonServiceArgument, + boolean showForegroundNotification + ) { + Intent serviceIntent = new Intent(PythonActivity.mActivity, PythonService.class); + String argument = PythonActivity.mActivity.getFilesDir().getAbsolutePath(); + String app_root_dir = PythonActivity.mActivity.getAppRoot(); + String entry_point = PythonActivity.mActivity.getEntryPoint(app_root_dir + "/service"); + serviceIntent.putExtra("androidPrivate", argument); + serviceIntent.putExtra("androidArgument", app_root_dir); + serviceIntent.putExtra("serviceEntrypoint", "service/" + entry_point); + serviceIntent.putExtra("pythonName", "python"); + serviceIntent.putExtra("pythonHome", app_root_dir); + serviceIntent.putExtra("pythonPath", app_root_dir + ":" + app_root_dir + "/lib"); + serviceIntent.putExtra("serviceStartAsForeground", + (showForegroundNotification ? "true" : "false") + ); + serviceIntent.putExtra("serviceTitle", serviceTitle); + serviceIntent.putExtra("serviceDescription", serviceDescription); + serviceIntent.putExtra("pythonServiceArgument", pythonServiceArgument); + PythonActivity.mActivity.startService(serviceIntent); + } + + public static void stop_service() { + Intent serviceIntent = new Intent(PythonActivity.mActivity, PythonService.class); + PythonActivity.mActivity.stopService(serviceIntent); + } + + /** Loading screen view **/ + public static ImageView mImageView = null; + public static View mLottieView = null; + /** Whether main routine/actual app has started yet **/ + protected boolean mAppConfirmedActive = false; + /** Timer for delayed loading screen removal. **/ + protected Timer loadingScreenRemovalTimer = null; + + // Overridden since it's called often, to check whether to remove the + // loading screen: + @Override + protected boolean sendCommand(int command, Object data) { + boolean result = super.sendCommand(command, data); + considerLoadingScreenRemoval(); + return result; + } + + /** Confirm that the app's main routine has been launched. + **/ + @Override + public void appConfirmedActive() { + if (!mAppConfirmedActive) { + Log.v(TAG, "appConfirmedActive() -> preparing loading screen removal"); + mAppConfirmedActive = true; + considerLoadingScreenRemoval(); + } + } + + /** This is called from various places to check whether the app's main + * routine has been launched already, and if it has, then the loading + * screen will be removed. + **/ + public void considerLoadingScreenRemoval() { + if (loadingScreenRemovalTimer != null) + return; + runOnUiThread(new Runnable() { + public void run() { + if (((PythonActivity)PythonActivity.mSingleton).mAppConfirmedActive && + loadingScreenRemovalTimer == null) { + // Remove loading screen but with a delay. + // (app can use p4a's android.loadingscreen module to + // do it quicker if it wants to) + // get a handler (call from main thread) + // this will run when timer elapses + TimerTask removalTask = new TimerTask() { + @Override + public void run() { + // post a runnable to the handler + runOnUiThread(new Runnable() { + @Override + public void run() { + PythonActivity activity = + ((PythonActivity)PythonActivity.mSingleton); + if (activity != null) + activity.removeLoadingScreen(); + } + }); + } + }; + loadingScreenRemovalTimer = new Timer(); + loadingScreenRemovalTimer.schedule(removalTask, 5000); + } + } + }); + } + + public void removeLoadingScreen() { + runOnUiThread(new Runnable() { + public void run() { + View view = mLottieView != null ? mLottieView : mImageView; + if (view != null && view.getParent() != null) { + ((ViewGroup)view.getParent()).removeView(view); + mLottieView = null; + mImageView = null; + } + } + }); + } + + public String getEntryPoint(String search_dir) { + /* Get the main file (.pyc|.py) depending on if we + * have a compiled version or not. + */ + List entryPoints = new ArrayList(); + entryPoints.add("main.pyc"); // python 3 compiled files + for (String value : entryPoints) { + File mainFile = new File(search_dir + "/" + value); + if (mainFile.exists()) { + return value; + } + } + return "main.py"; + } + + protected void showLoadingScreen(View view) { + try { + if (mLayout == null) { + setContentView(view); + } else if (view.getParent() == null) { + mLayout.addView(view); + } + } catch (IllegalStateException e) { + // The loading screen can be attempted to be applied twice if app + // is tabbed in/out, quickly. + // (Gives error "The specified child already has a parent. + // You must call removeView() on the child's parent first.") + } + } + + protected void setBackgroundColor(View view) { + /* + * Set the presplash loading screen background color + * https://developer.android.com/reference/android/graphics/Color.html + * Parse the color string, and return the corresponding color-int. + * If the string cannot be parsed, throws an IllegalArgumentException exception. + * Supported formats are: #RRGGBB #AARRGGBB or one of the following names: + * 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', + * 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', + * 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'. + */ + String backgroundColor = resourceManager.getString("presplash_color"); + if (backgroundColor != null) { + try { + view.setBackgroundColor(Color.parseColor(backgroundColor)); + } catch (IllegalArgumentException e) {} + } + } + + protected View getLoadingScreen() { + // If we have an mLottieView or mImageView already, then do + // nothing because it will have already been made the content + // view or added to the layout. + if (mLottieView != null || mImageView != null) { + // we already have a splash screen + return mLottieView != null ? mLottieView : mImageView; + } + + // first try to load the lottie one + try { + mLottieView = getLayoutInflater().inflate( + this.resourceManager.getIdentifier("lottie", "layout"), + mLayout, + false + ); + try { + if (mLayout == null) { + setContentView(mLottieView); + } else if (PythonActivity.mLottieView.getParent() == null) { + mLayout.addView(mLottieView); + } + } catch (IllegalStateException e) { + // The loading screen can be attempted to be applied twice if app + // is tabbed in/out, quickly. + // (Gives error "The specified child already has a parent. + // You must call removeView() on the child's parent first.") + } + setBackgroundColor(mLottieView); + return mLottieView; + } + catch (NotFoundException e) { + Log.v("SDL", "couldn't find lottie layout or animation, trying static splash"); + } + + // no lottie asset, try to load the static image then + int presplashId = this.resourceManager.getIdentifier("presplash", "drawable"); + InputStream is = this.getResources().openRawResource(presplashId); + Bitmap bitmap = null; + try { + bitmap = BitmapFactory.decodeStream(is); + } finally { + try { + is.close(); + } catch (IOException e) {}; + } + + mImageView = new ImageView(this); + mImageView.setImageBitmap(bitmap); + setBackgroundColor(mImageView); + + mImageView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT)); + mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); + return mImageView; + } + + @Override + protected void onPause() { + if (this.mWakeLock != null && mWakeLock.isHeld()) { + this.mWakeLock.release(); + } + + this.activityPaused = true; + Log.v(TAG, "onPause()"); + try { + super.onPause(); + } catch (UnsatisfiedLinkError e) { + // Catch pause while still in loading screen failing to + // call native function (since it's not yet loaded) + } + } + + @Override + protected void onResume() { + if (this.mWakeLock != null) { + this.mWakeLock.acquire(); + } + this.activityPaused = false; + Log.v(TAG, "onResume() in PythonActivity"); + try { + super.onResume(); + } catch (UnsatisfiedLinkError e) { + // Catch resume while still in loading screen failing to + // call native function (since it's not yet loaded) + } + considerLoadingScreenRemoval(); + } + + @Override + public void onWindowFocusChanged(boolean hasFocus) { + try { + super.onWindowFocusChanged(hasFocus); + } catch (UnsatisfiedLinkError e) { + // Catch window focus while still in loading screen failing to + // call native function (since it's not yet loaded) + } + considerLoadingScreenRemoval(); + } + + /** + * Used by android.permissions p4a module to register a call back after + * requesting runtime permissions + **/ + public interface PermissionsCallback { + void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); + } + + private PermissionsCallback permissionCallback; + private boolean havePermissionsCallback = false; + + public void addPermissionsCallback(PermissionsCallback callback) { + permissionCallback = callback; + havePermissionsCallback = true; + Log.v(TAG, "addPermissionsCallback(): Added callback for onRequestPermissionsResult"); + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + Log.v(TAG, "onRequestPermissionsResult()"); + if (havePermissionsCallback) { + Log.v(TAG, "onRequestPermissionsResult passed to callback"); + permissionCallback.onRequestPermissionsResult(requestCode, permissions, grantResults); + } + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + } + + /** + * Used by android.permissions p4a module to check a permission + **/ + public boolean checkCurrentPermission(String permission) { + if (android.os.Build.VERSION.SDK_INT < 23) + return true; + + try { + java.lang.reflect.Method methodCheckPermission = + Activity.class.getMethod("checkSelfPermission", String.class); + Object resultObj = methodCheckPermission.invoke(this, permission); + int result = Integer.parseInt(resultObj.toString()); + if (result == PackageManager.PERMISSION_GRANTED) + return true; + } catch (IllegalAccessException | NoSuchMethodException | + InvocationTargetException e) { + } + return false; + } + + /** + * Used by android.permissions p4a module to request runtime permissions + **/ + public void requestPermissionsWithRequestCode(String[] permissions, int requestCode) { + if (android.os.Build.VERSION.SDK_INT < 23) + return; + try { + java.lang.reflect.Method methodRequestPermission = + Activity.class.getMethod("requestPermissions", + String[].class, int.class); + methodRequestPermission.invoke(this, permissions, requestCode); + } catch (IllegalAccessException | NoSuchMethodException | + InvocationTargetException e) { + } + } + + public void requestPermissions(String[] permissions) { + requestPermissionsWithRequestCode(permissions, 1); + } + + public static void changeKeyboard(int inputType) { + if (SDLActivity.keyboardInputType != inputType){ + SDLActivity.keyboardInputType = inputType; + InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.restartInput(mTextEdit); + } + } +} diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 725c297..5aa22ac 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -4204,6 +4204,7 @@ class SidebandCore(): self.interface_tcp = None self.interface_i2p = None self.interface_rnode = None + self.interface_weave = None self.interface_modem = None self.interface_serial = None @@ -4326,7 +4327,7 @@ class SidebandCore(): self.setstate("init.loadingstate", "Starting RNode") self.__add_rnodeinterface() - if self.config["connect_weave"] or True: + if self.config["connect_weave"]: self.setstate("init.loadingstate", "Starting Weave") self.__add_weaveinterface() diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index e2491fc..8dd7a21 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -489,6 +489,7 @@ Builder.load_string(""" icon: "dots-vertical" : + id: conversations_scrollview viewclass: "ConversationEntry" effect_cls: "ScrollEffect" diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index f144eb5..9f55656 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -163,9 +163,9 @@ MDNavigationLayout: OneLineIconListItem: - text: "Encryption Keys" + text: "Backup & Keys" on_release: root.ids.screen_manager.app.keys_action(self) - + IconLeftWidget: icon: "key-chain" on_release: root.ids.screen_manager.app.keys_action(self) @@ -1131,7 +1131,7 @@ MDScreen: orientation: "vertical" MDTopAppBar: - title: "Encryption Keys" + title: "Backup & Keys" anchor_title: "left" elevation: 0 left_action_items: @@ -1160,6 +1160,16 @@ MDScreen: text_size: self.width, None height: self.texture_size[1] + MDRectangleFlatIconButton: + id: keys_backup + icon: "home-export-outline" + text: "Backup Sideband Profile" + 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.app.profile_backup_action(self) + MDRectangleFlatIconButton: id: keys_display icon: "eye" From 0a1be10411301bd0a6b686134404f8d3c1b9a474 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 2 Nov 2025 00:00:38 +0100 Subject: [PATCH 120/271] Implemented profile backup and export. Implemented window size following UI scaling factor. --- sbapp/main.py | 83 ++++++++++++++++++++++++++++++++------------- sbapp/ui/layouts.py | 21 +++++++++++- 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index a188bf7..2e1c205 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -177,27 +177,6 @@ if not args.daemon: local = os.path.dirname(__file__) sys.path.append(local) - if not RNS.vendor.platformutils.is_android(): - model = None - max_width = WINDOW_DEFAULT_WIDTH - max_height = WINDOW_DEFAULT_HEIGHT - - try: - if os.path.isfile("/sys/firmware/devicetree/base/model"): - with open("/sys/firmware/devicetree/base/model", "r") as mf: - model = mf.read() - except: pass - - if model: - if model.startswith("Raspberry Pi "): max_height = 625 - - window_width = min(WINDOW_DEFAULT_WIDTH, max_width) - window_height = min(WINDOW_DEFAULT_HEIGHT, max_height) - - from kivy.config import Config - Config.set("graphics", "width", str(window_width)) - Config.set("graphics", "height", str(window_height)) - if args.daemon: from .sideband.core import SidebandCore class DaemonElement(): @@ -220,6 +199,34 @@ if args.daemon: else: apply_ui_scale() + if not RNS.vendor.platformutils.is_android(): + scaling_factor = 1.0 + try: scaling_factor = float(os.environ["KIVY_METRICS_DENSITY"]) + except Exception as e: pass + + if scaling_factor < 0.75: scaling_factor = 0.75 + if scaling_factor > 2: scaling_factor = 2 + + model = None + max_width = WINDOW_DEFAULT_WIDTH*scaling_factor + max_height = WINDOW_DEFAULT_HEIGHT*scaling_factor + + try: + if os.path.isfile("/sys/firmware/devicetree/base/model"): + with open("/sys/firmware/devicetree/base/model", "r") as mf: + model = mf.read() + except: pass + + if model: + if model.startswith("Raspberry Pi "): max_height = 625 + + window_width = int(min(WINDOW_DEFAULT_WIDTH*scaling_factor, max_width)) + window_height = int(min(WINDOW_DEFAULT_HEIGHT*scaling_factor, max_height)) + + from kivy.config import Config + Config.set("graphics", "width", str(window_width)) + Config.set("graphics", "height", str(window_height)) + from kivymd.app import MDApp app_superclass = MDApp from kivy.core.window import Window @@ -5209,12 +5216,14 @@ 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. 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." + info1 = "[size=18dp][b]Encryption Keys[/b][/size][size=5dp]\n \n[/size]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." + info2 = "[size=18dp][b]Backup & Restore[/b][/size][size=5dp]\n \n[/size]You can backup your entire Sideband profile for import on a computer or other device. The exported backup archive will be saved in the downloads folder of your device. Please note that the exported archive contains all your messages, data and encryption keys. Take extreme care to keep this archive secure." if not RNS.vendor.platformutils.get_platform() == "android": self.widget_hide(self.keys_screen.ids.keys_share) - self.keys_screen.ids.keys_info.text = info + self.keys_screen.ids.keys_info.text = info1 + self.keys_screen.ids.backup_info.text = info2 def keys_open(self, sender=None, direction="left", no_transition=False): if no_transition: @@ -5234,6 +5243,34 @@ class SidebandApp(MDApp): def close_keys_action(self, sender=None): self.open_conversations(direction="right") + def _profile_backup_job(self): + import tarfile + from ui.helpers import file_ts_format + output_path = plyer.storagepath.get_downloads_dir() + time_str = time.strftime(file_ts_format, time.localtime(time.time())) + target_file = f"{output_path}/sideband_backup_{time_str}.tar.gz" + tar = tarfile.open(target_file, "w:gz") + tar.add(f"{self.sideband.app_dir}/app_storage", arcname="Sideband Backup") + tar.close() + + def job(dt): + self.keys_screen.ids.keys_backup.disabled = False + toast("Backup done") + ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog(text=f"Backup has been saved to {target_file}", + buttons=[ok_button]) + def dl_yes(s): dialog.dismiss() + + ok_button.bind(on_release=dl_yes) + dialog.open() + + Clock.schedule_once(job, 0.3) + + def profile_backup_action(self, sender=None): + self.keys_screen.ids.keys_backup.disabled = True + toast("Creating backup...") + threading.Thread(target=self._profile_backup_job, daemon=True).start() + def identity_display_action(self, sender=None): yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 9f55656..1b14ebb 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -1153,7 +1153,7 @@ MDScreen: MDLabel: - id: keys_info + id: backup_info markup: True text: "" size_hint_y: None @@ -1170,6 +1170,25 @@ MDScreen: size_hint: [1.0, None] on_release: root.app.profile_backup_action(self) + MDRectangleFlatIconButton: + id: keys_restore + icon: "home-import-outline" + text: "Restore Sideband Profile" + disabled: True + 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.app.profile_backup_action(self) + + MDLabel: + id: keys_info + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + MDRectangleFlatIconButton: id: keys_display icon: "eye" From 9bd7a5970c15a67da441af0ab1c184cfa0f33aaa Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 2 Nov 2025 00:27:57 +0100 Subject: [PATCH 121/271] Implemented getting and displaying backend service log on Android --- sbapp/sideband/core.py | 30 ++++++++++++++++++++++++++++++ sbapp/ui/utilities.py | 27 ++++++++++++++++++++++----- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 5aa22ac..7bfef1d 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2135,6 +2135,8 @@ class SidebandCore(): elif "stop_tracking" in call: args = call["stop_tracking"] connection.send(self.stop_tracking(object_addr=args["object_addr"])) + elif "get_service_log" in call: + connection.send(self.get_service_log()) else: connection.send(None) @@ -4156,6 +4158,34 @@ class SidebandCore(): def get_log(self): return "\n".join(self.log_deque) + def _service_get_service_log(self): + if not RNS.vendor.platformutils.is_android(): + return False + else: + if self.is_client: + try: return self.service_rpc_request({"get_service_log": True }) + except Exception as e: + RNS.log("Error while sending message over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + else: + return False + + def get_service_log(self): + if self.allow_service_dispatch and self.is_client: + try: return self._service_get_service_log() + + except Exception as e: + RNS.log("Error while getting service log: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + + else: + try: return "\n".join(self.log_deque) + except Exception as e: + RNS.log("An error occurred while getting message transfer stamp cost: "+str(e), RNS.LOG_ERROR) + return None + def __start_jobs_immediate(self): if self.log_quiet: selected_level = 0 diff --git a/sbapp/ui/utilities.py b/sbapp/ui/utilities.py index d3adcc7..80dd163 100644 --- a/sbapp/ui/utilities.py +++ b/sbapp/ui/utilities.py @@ -182,14 +182,23 @@ class Utilities(): threading.Thread(target=self.update_logviewer_job, daemon=True).start() def update_logviewer_job(self, sender=None): - try: - output = self.app.sideband.get_log() - except Exception as e: - output = f"An error occurred while retrieving log entries:\n{e}" + try: output = self.app.sideband.get_log() + except Exception as e: output = f"An error occurred while retrieving log entries:\n{e}" + + if not RNS.vendor.platformutils.is_android(): service_output = None + else: + try: service_output = self.app.sideband.get_service_log() + except Exception as e: service_output = f"An error occurred while retrieving log entries:\n{e}" + self.logviewer_screen.log_contents = output def cb(dt): - self.logviewer_screen.ids.logviewer_output.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]{output}[/size][/font]" + if not RNS.vendor.platformutils.is_android(): + self.logviewer_screen.ids.logviewer_output.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]{output}[/size][/font]" + else: + self.logviewer_screen.ids.logviewer_output.text = f"[size=18dp][b]Frontend Log[/b][/size][size=5dp]\n \n[font=RobotoMono-Regular][size={int(dp(12))}]{output}[/size][/font]" + self.logviewer_screen.ids.slogviewer_output.text = f"\n[size=18dp][b]Service Log[/b][/size][size=5dp]\n \n[font=RobotoMono-Regular][size={int(dp(12))}]{service_output}[/size][/font]" + self.logviewer_screen.log_contents += f"\n\n{service_output}" Clock.schedule_once(cb, 0.2) if self.app.root.ids.screen_manager.current == "logviewer_screen": @@ -377,6 +386,14 @@ MDScreen: size_hint_y: None text_size: self.width, None height: self.texture_size[1] + + MDLabel: + id: slogviewer_output + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] """ layout_advanced_screen = """ From 2eec1d0a5042c43ae27315dab9d45a9cd1f2d909 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 2 Nov 2025 00:39:11 +0100 Subject: [PATCH 122/271] Updated dependencies --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index cf15e6b..bc5700e 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.0.0", - "lxmf>=0.8.0", + "rns>=1.0.1", + "lxmf>=0.9.0", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 9a11bfded2abb561b47387e2a9db8a7192731dcc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 2 Nov 2025 02:57:51 +0100 Subject: [PATCH 123/271] Various UI improvements --- sbapp/main.py | 6 +++++- sbapp/sideband/core.py | 12 +++++++++--- sbapp/ui/conversations.py | 14 ++------------ sbapp/ui/messages.py | 8 ++++---- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 2e1c205..dd8a6b6 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1787,7 +1787,7 @@ class SidebandApp(MDApp): def conversation_index_action(self, index): if self.conversations_view != None and self.conversations_view.list != None: i = index-1 - c = self.conversations_view.list.children + c = self.conversations_view.list.children[0].children if len(c) > i: item = c[(len(c)-1)-i] self.conversation_action(item) @@ -5466,6 +5466,10 @@ class SidebandApp(MDApp): perm_ok = True path = self.sideband.config["command_plugins_path"] + if not os.path.isdir(path): + if not RNS.vendor.platformutils.is_android(): path = os.path.expanduser("~") + else: path = primary_external_storage_path() + if perm_ok and path != None: try: self.file_manager = MDFileManager( diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 7bfef1d..0568853 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5472,11 +5472,17 @@ class SidebandCore(): elif self.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_FAILED: return "Sync failed" elif self.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_COMPLETE: - new_msgs = self.message_router.propagation_transfer_last_result + msgs_dld = self.message_router.propagation_transfer_last_result + duplicates = self.message_router.propagation_transfer_last_duplicates or 0 + new_msgs = msgs_dld-duplicates + nms = "" if new_msgs == 1 else "s" + dms = "" if duplicates == 1 else "s" if new_msgs == 0: - return "Done, no new messages" + if duplicates == 0: return f"Done, no new messages" + else: return f"Done, no new messages\nDiscarded {duplicates} existing message{dms}" else: - return "Downloaded "+str(new_msgs)+" messages" + if duplicates == 0: return f"Downloaded {new_msgs} new message{nms}" + else: return f"Downloaded {new_msgs} new message{nms}\nDiscarded {duplicates} existing message{dms}" else: return "Unknown" diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index 8dd7a21..54694a2 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -250,7 +250,7 @@ class Conversations(): self.app = app self.context_dests = [] self.added_item_dests = [] - # self.list = None + self.list = None self.conversation_list = None self.ids = None @@ -268,17 +268,6 @@ class Conversations(): self.update() - def reload(self): - self.clear_list() - self.update() - - def clear_list(self): - if self.list != None: - self.list.clear_widgets() - - self.context_dests = [] - self.added_item_dests = [] - def update(self): self.context_dests = self.app.sideband.list_conversations(conversations=self.app.include_conversations, objects=self.app.include_objects) @@ -435,6 +424,7 @@ class Conversations(): RNS.log("Updating conversation list widgets", RNS.LOG_DEBUG) if self.conversation_list == None: self.conversation_list = ConversationList() + self.list = self.conversation_list self.ids.conversation_list_container.add_widget(self.conversation_list) self.update_conversation_list() diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 6c54704..d945783 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -337,15 +337,15 @@ class Messages(): if prg <= 0.00: stamp_cost = self.app.sideband.get_lxm_stamp_cost(msg["hash"]) prop_cost = self.app.sideband.get_lxm_propagation_cost(msg["hash"]) - if stamp_cost: + if stamp_cost and prop_cost: + sphrase = f"Generating stamps with cost {stamp_cost} and {prop_cost}" + prgstr = "" + elif stamp_cost: sphrase = f"Generating stamp with cost {stamp_cost}" prgstr = "" elif prop_cost: sphrase = f"Generating propagation stamp with cost {prop_cost}" prgstr = "" - elif stamp_cost and prop_cost: - sphrase = f"Generating stamps with cost {stamp_cost} and {prop_cost}" - prgstr = "" else: sphrase = "Waiting for path" elif prg <= 0.01: From a2c2de49fecd5897722277280c284e43053cfca2 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 2 Nov 2025 03:03:28 +0100 Subject: [PATCH 124/271] Fixed missing none check --- sbapp/sideband/mqtt.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py index b035f8a..57efe00 100644 --- a/sbapp/sideband/mqtt.py +++ b/sbapp/sideband/mqtt.py @@ -81,8 +81,9 @@ class MQTT(): def disconnect(self): RNS.log("Disconnecting from MQTT server", RNS.LOG_EXTREME) # TODO: Remove debug - self.client.disconnect() - self.client.loop_stop() + if self.client: + self.client.disconnect() + self.client.loop_stop() self.is_connected = False def post_message(self, topic, data): From ef0aed51a2d1f711e17c4a14add8923efe82a142 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 2 Nov 2025 18:35:35 +0100 Subject: [PATCH 125/271] Cleanup --- sbapp/buildozer.spec | 2 +- sbapp/ui/messages.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 4c437e2..4be4d78 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -29,7 +29,7 @@ android.presplash_color = #00000000 orientation = portrait fullscreen = 0 -android.permissions = INTERNET,POST_NOTIFICATIONS,WAKE_LOCK,FOREGROUND_SERVICE,CHANGE_WIFI_MULTICAST_STATE,BLUETOOTH_SCAN,BLUETOOTH_ADVERTISE,BLUETOOTH_CONNECT,ACCESS_NETWORK_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,MANAGE_EXTERNAL_STORAGE,ACCESS_BACKGROUND_LOCATION,RECORD_AUDIO,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,FOREGROUND_SERVICE_CONNECTED_DEVICE +android.permissions = INTERNET,POST_NOTIFICATIONS,WAKE_LOCK,FOREGROUND_SERVICE,CHANGE_WIFI_MULTICAST_STATE,BLUETOOTH_SCAN,BLUETOOTH_ADVERTISE,BLUETOOTH_CONNECT,ACCESS_NETWORK_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,MANAGE_EXTERNAL_STORAGE,ACCESS_BACKGROUND_LOCATION,RECORD_AUDIO,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,FOREGROUND_SERVICE_CONNECTED_DEVICE,MODIFY_AUDIO_SETTINGS android.api = 33 android.minapi = 24 diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index d945783..acf8230 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -344,7 +344,7 @@ class Messages(): sphrase = f"Generating stamp with cost {stamp_cost}" prgstr = "" elif prop_cost: - sphrase = f"Generating propagation stamp with cost {prop_cost}" + sphrase = f"Generating PN stamp with cost {prop_cost}" prgstr = "" else: sphrase = "Waiting for path" From fc9e1bf86fede090efc520821656594ba182da41 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 13:37:48 +0100 Subject: [PATCH 126/271] Added call confirm dialog --- sbapp/main.py | 22 ++++++++++++++++++++-- sbapp/sideband/core.py | 3 +++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index dd8a6b6..7853fb8 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1802,8 +1802,26 @@ class SidebandApp(MDApp): elif sender.conv_type == self.sideband.CONV_VOICE: identity_hash = sender.sb_uid - def cb(dt): self.dial_action(identity_hash) - Clock.schedule_once(cb, 0.15) + if not self.sideband.config["confirm_calls"]: + def cb(dt): self.dial_action(identity_hash) + Clock.schedule_once(cb, 0.15) + else: + call_dialog_text = f"[b]Initiate Voice Call?[/b]\n\nDestination Identity:\n{RNS.prettyhexrep(identity_hash)}?" + if hasattr(self, "confirm_call_dialog"): self.confirm_call_dialog.text = call_dialog_text + else: + yes_button = MDRectangleFlatButton(text="Call",font_size=dp(18), theme_text_color="Custom", line_color=self.color_accept, text_color=self.color_accept) + no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) + self.confirm_call_dialog = MDDialog(text=call_dialog_text, buttons=[ no_button, yes_button ]) + def dl_no(s): self.confirm_call_dialog.dismiss() + def dl_yes(s): + self.confirm_call_dialog.dismiss() + def cb(dt): self.dial_action(self.confirm_call_dialog.dest_identity_hash) + Clock.schedule_once(cb, 0.15) + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + self.confirm_call_dialog.dest_identity_hash = identity_hash + self.confirm_call_dialog.open() def open_conversation(self, context_dest, direction="left"): self.rec_dialog_is_open = False diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 0568853..b653492 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -475,6 +475,7 @@ class SidebandCore(): self.config["lxm_limit_1mb"] = True self.config["trusted_markup_only"] = False self.config["compose_in_markdown"] = False + self.config["confirm_calls"] = True # Connectivity self.config["connect_transport"] = False @@ -652,6 +653,8 @@ class SidebandCore(): self.config["trusted_markup_only"] = False if not "compose_in_markdown" in self.config: self.config["compose_in_markdown"] = False + if not "confirm_calls" in self.config: + self.config["confirm_calls"] = True if not "input_language" in self.config: self.config["input_language"] = None From 2fe1527ba20f0e460f99eced16e51c85e074d5b3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 14:09:49 +0100 Subject: [PATCH 127/271] Consistent pane close event handling --- sbapp/main.py | 99 +++++++++++++++---------------------------- sbapp/ui/utilities.py | 9 +++- 2 files changed, 42 insertions(+), 66 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 7853fb8..5decc71 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1409,6 +1409,24 @@ class SidebandApp(MDApp): self.root.ids.nav_scrollview.effect_cls = ScrollEffect Clock.schedule_once(self.start_core, 0.25) + def close_handler(self): + if self.root.ids.screen_manager.current == "conversations_screen": + if self.include_conversations and not self.include_objects: self.quit_action(self) + else: self.conversations_action(direction="right") + elif self.root.ids.screen_manager.current == "hardware_rnode_screen": self.close_sub_hardware_action() + elif self.root.ids.screen_manager.current == "hardware_modem_screen": self.close_sub_hardware_action() + elif self.root.ids.screen_manager.current == "hardware_serial_screen": self.close_sub_hardware_action() + elif self.root.ids.screen_manager.current == "map_settings_screen": self.close_sub_map_action() + elif self.root.ids.screen_manager.current == "object_details_screen": self.object_details_screen.close_action() + elif self.root.ids.screen_manager.current == "sensors_screen": self.close_sub_telemetry_action() + elif self.root.ids.screen_manager.current == "icons_screen": self.close_sub_telemetry_action() + elif self.root.ids.screen_manager.current == "utilities_screen": self.close_any_action() + elif self.root.ids.screen_manager.current == "rnstatus_screen": self.utilities_screen.close_rnstatus_action() + elif self.root.ids.screen_manager.current == "logviewer_screen": self.close_sub_utilities_action() + elif self.root.ids.screen_manager.current == "advanced_screen": self.close_sub_utilities_action() + elif self.root.ids.screen_manager.current == "voice_settings_screen": self.close_sub_voice_action() + else: self.close_any_action() + def keyup_event(self, instance, keyboard, keycode): if self.keyboard_enabled: if self.root.ids.screen_manager.current == "messages_screen": @@ -1490,25 +1508,8 @@ class SidebandApp(MDApp): if text == "q": self.quit_action(self) - if text == "w": - if self.root.ids.screen_manager.current == "conversations_screen": - if self.include_conversations and not self.include_objects: - self.quit_action(self) - else: - self.conversations_action(direction="right") - elif self.root.ids.screen_manager.current == "map_settings_screen": - self.close_sub_map_action() - elif self.root.ids.screen_manager.current == "object_details_screen": - self.object_details_screen.close_action() - elif self.root.ids.screen_manager.current == "sensors_screen": - self.close_sub_telemetry_action() - elif self.root.ids.screen_manager.current == "icons_screen": - self.close_sub_telemetry_action() - elif self.root.ids.screen_manager.current == "utilities_screen": - self.close_sub_utilities_action() - else: - self.open_conversations(direction="right") - + if text == "w": self.close_handler() + if text == "s" or text == "d": if self.root.ids.screen_manager.current == "messages_screen": self.message_send_action() @@ -1594,38 +1595,12 @@ class SidebandApp(MDApp): # Handle escape/back if key == 27: if self.root.ids.screen_manager.current == "conversations_screen": - if not self.include_conversations and self.include_objects: - self.conversations_action(direction="right") + if not self.include_conversations and self.include_objects: self.conversations_action(direction="right") else: - if time.time() - self.last_exit_event < 2: - self.quit_action(self) - else: - self.last_exit_event = time.time() - - else: - if self.root.ids.screen_manager.current == "hardware_rnode_screen": - self.close_sub_hardware_action() - elif self.root.ids.screen_manager.current == "hardware_modem_screen": - self.close_sub_hardware_action() - elif self.root.ids.screen_manager.current == "hardware_serial_screen": - self.close_sub_hardware_action() - elif self.root.ids.screen_manager.current == "object_details_screen": - self.object_details_screen.close_action() - elif self.root.ids.screen_manager.current == "map_settings_screen": - self.close_sub_map_action() - elif self.root.ids.screen_manager.current == "sensors_screen": - self.close_sub_telemetry_action() - elif self.root.ids.screen_manager.current == "icons_screen": - self.close_sub_telemetry_action() - elif self.root.ids.screen_manager.current == "rnstatus_screen": - self.close_sub_utilities_action() - elif self.root.ids.screen_manager.current == "logviewer_screen": - self.close_sub_utilities_action() - elif self.root.ids.screen_manager.current == "voice_settings_screen": - self.close_sub_voice_action() - else: - self.open_conversations(direction="right") + if time.time() - self.last_exit_event < 2: self.quit_action(self) + else: self.last_exit_event = time.time() + else: self.close_handler() return True def widget_hide(self, w, hide=True): @@ -2782,20 +2757,17 @@ class SidebandApp(MDApp): dialog = MDDialog( title="Connectivity Status", text=str(self.get_connectivity_text()), - buttons=[full_button, yes_button], - # elevation=0, - ) - def cs_updater(dt): - dialog.text = str(self.get_connectivity_text()) + buttons=[full_button, yes_button]) + def cs_updater(dt): dialog.text = str(self.get_connectivity_text()) + def dl_yes(s): dialog.dismiss() - if self.connectivity_updater != None: - self.connectivity_updater.cancel() + if self.connectivity_updater != None: self.connectivity_updater.cancel() + def cb_rns(sender): dialog.dismiss() - if self.connectivity_updater != None: - self.connectivity_updater.cancel() - self.rnstatus_action() + if self.connectivity_updater != None: self.connectivity_updater.cancel() + self.rnstatus_action(from_conversations=True) yes_button.bind(on_release=dl_yes) full_button.bind(on_release=cb_rns) @@ -2807,12 +2779,11 @@ class SidebandApp(MDApp): self.connectivity_updater = Clock.schedule_interval(cs_updater, 2.0) else: - self.rnstatus_action() + self.rnstatus_action(from_conversations=True) - def rnstatus_action(self, sender=None): - if not self.utilities_ready: - self.utilities_init() - self.utilities_screen.rnstatus_action() + def rnstatus_action(self, sender=None, from_conversations=False): + if not self.utilities_ready: self.utilities_init() + self.utilities_screen.rnstatus_action(from_conversations=from_conversations) def ingest_lxm_action(self, sender): def cb(dt): diff --git a/sbapp/ui/utilities.py b/sbapp/ui/utilities.py index 80dd163..aa8da1b 100644 --- a/sbapp/ui/utilities.py +++ b/sbapp/ui/utilities.py @@ -81,13 +81,14 @@ class Utilities(): ### rnstatus screen ###################################### - def rnstatus_action(self, sender=None): + def rnstatus_action(self, sender=None, from_conversations=False): if not self.app.root.ids.screen_manager.has_screen("rnstatus_screen"): self.rnstatus_screen = Builder.load_string(layout_rnstatus_screen) self.rnstatus_screen.app = self.app self.rnstatus_screen.delegate = self self.app.root.ids.screen_manager.add_widget(self.rnstatus_screen) + self.rnstatus_screen.from_conversations = from_conversations self.app.root.ids.screen_manager.transition.direction = "left" self.app.root.ids.screen_manager.current = "rnstatus_screen" self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) @@ -97,6 +98,10 @@ class Utilities(): def update_rnstatus(self, sender=None): threading.Thread(target=self.update_rnstatus_job, daemon=True).start() + def close_rnstatus_action(self, sender=None): + if not self.rnstatus_screen.from_conversations: self.app.close_sub_utilities_action() + else: self.app.close_any_action() + def update_rnstatus_job(self, sender=None): if self.rnstatus_instance == None: import RNS.Utilities.rnstatus as rnstatus @@ -319,7 +324,7 @@ MDScreen: right_action_items: [ # ['refresh', lambda x: root.delegate.update_rnstatus()], - ['close', lambda x: root.app.close_sub_utilities_action(self)], + ['close', lambda x: root.delegate.close_rnstatus_action(self)], ] MDScrollView: From f3b0c71c7b4673f5183ab323d23bcd0ecbf3f1b2 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 14:25:41 +0100 Subject: [PATCH 128/271] Added Weave interface to connectivity settings --- sbapp/main.py | 22 ++++++++++++++++++++++ sbapp/ui/layouts.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/sbapp/main.py b/sbapp/main.py index 5decc71..66de30d 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3640,6 +3640,7 @@ class SidebandApp(MDApp): self.widget_hide(self.connectivity_screen.ids.connectivity_enable_transport) self.widget_hide(self.connectivity_screen.ids.connectivity_serial_label) self.widget_hide(self.connectivity_screen.ids.connectivity_use_serial) + self.widget_hide(self.connectivity_screen.ids.connectivity_use_weave) self.widget_hide(self.connectivity_screen.ids.connectivity_serial_fields) self.widget_hide(self.connectivity_screen.ids.connectivity_share_instance) self.widget_hide(self.connectivity_screen.ids.connectivity_shared_access) @@ -3679,6 +3680,10 @@ class SidebandApp(MDApp): # self.widget_hide(self.connectivity_screen.ids.connectivity_serial_fields, collapse) pass + def con_collapse_weave(collapse=True): + # self.widget_hide(self.connectivity_screen.ids.connectivity_serial_fields, collapse) + pass + def con_collapse_transport(collapse=True): # self.widget_hide(self.connectivity_screen.ids.connectivity_transport_fields, collapse) pass @@ -3707,6 +3712,10 @@ class SidebandApp(MDApp): self.sideband.config["connect_serial_ifac_netname"] = self.connectivity_screen.ids.connectivity_serial_ifac_netname.text self.sideband.config["connect_serial_ifac_passphrase"] = self.connectivity_screen.ids.connectivity_serial_ifac_passphrase.text + self.sideband.config["connect_weave"] = self.connectivity_screen.ids.connectivity_use_weave.active + self.sideband.config["connect_weave_ifac_netname"] = self.connectivity_screen.ids.connectivity_weave_ifac_netname.text + self.sideband.config["connect_weave_ifac_passphrase"] = self.connectivity_screen.ids.connectivity_weave_ifac_passphrase.text + self.sideband.config["connect_modem"] = self.connectivity_screen.ids.connectivity_use_modem.active self.sideband.config["connect_modem_ifac_netname"] = self.connectivity_screen.ids.connectivity_modem_ifac_netname.text self.sideband.config["connect_modem_ifac_passphrase"] = self.connectivity_screen.ids.connectivity_modem_ifac_passphrase.text @@ -3724,6 +3733,7 @@ class SidebandApp(MDApp): con_collapse_rnode(collapse=not self.connectivity_screen.ids.connectivity_use_rnode.active) con_collapse_modem(collapse=not self.connectivity_screen.ids.connectivity_use_modem.active) con_collapse_serial(collapse=not self.connectivity_screen.ids.connectivity_use_serial.active) + con_collapse_weave(collapse=not self.connectivity_screen.ids.connectivity_use_weave.active) con_collapse_transport(collapse=not self.sideband.config["connect_transport"]) self.sideband.save_configuration() @@ -3749,13 +3759,16 @@ class SidebandApp(MDApp): self.connectivity_screen.ids.connectivity_use_rnode.unbind(active=serial_connectivity_save) self.connectivity_screen.ids.connectivity_use_modem.unbind(active=serial_connectivity_save) self.connectivity_screen.ids.connectivity_use_serial.unbind(active=serial_connectivity_save) + self.connectivity_screen.ids.connectivity_use_weave.unbind(active=serial_connectivity_save) self.connectivity_screen.ids.connectivity_use_rnode.active = False self.connectivity_screen.ids.connectivity_use_modem.active = False self.connectivity_screen.ids.connectivity_use_serial.active = False + self.connectivity_screen.ids.connectivity_use_weave.active = False sender.active = True self.connectivity_screen.ids.connectivity_use_rnode.bind(active=serial_connectivity_save) self.connectivity_screen.ids.connectivity_use_modem.bind(active=serial_connectivity_save) self.connectivity_screen.ids.connectivity_use_serial.bind(active=serial_connectivity_save) + self.connectivity_screen.ids.connectivity_use_weave.bind(active=serial_connectivity_save) save_connectivity(sender, event) def focus_save(sender=None, event=None): @@ -3840,6 +3853,11 @@ class SidebandApp(MDApp): self.connectivity_screen.ids.connectivity_serial_ifac_netname.text = self.sideband.config["connect_serial_ifac_netname"] self.connectivity_screen.ids.connectivity_serial_ifac_passphrase.text = self.sideband.config["connect_serial_ifac_passphrase"] + self.connectivity_screen.ids.connectivity_use_weave.active = self.sideband.config["connect_weave"] + con_collapse_weave(collapse=not self.connectivity_screen.ids.connectivity_use_weave.active) + self.connectivity_screen.ids.connectivity_weave_ifac_netname.text = self.sideband.config["connect_weave_ifac_netname"] + self.connectivity_screen.ids.connectivity_weave_ifac_passphrase.text = self.sideband.config["connect_weave_ifac_passphrase"] + self.connectivity_screen.ids.connectivity_enable_transport.active = self.sideband.config["connect_transport"] con_collapse_transport(collapse=not self.sideband.config["connect_transport"]) self.connectivity_screen.ids.connectivity_enable_transport.bind(active=save_connectivity) @@ -3882,6 +3900,10 @@ class SidebandApp(MDApp): self.connectivity_screen.ids.connectivity_serial_ifac_netname.bind(focus=focus_save) self.connectivity_screen.ids.connectivity_serial_ifac_passphrase.bind(focus=focus_save) + self.connectivity_screen.ids.connectivity_use_weave.bind(active=serial_connectivity_save) + self.connectivity_screen.ids.connectivity_weave_ifac_netname.bind(focus=focus_save) + self.connectivity_screen.ids.connectivity_weave_ifac_passphrase.bind(focus=focus_save) + self.connectivity_screen.ids.connectivity_local_ifmode.bind(focus=ifmode_validate) self.connectivity_screen.ids.connectivity_tcp_ifmode.bind(focus=ifmode_validate) self.connectivity_screen.ids.connectivity_i2p_ifmode.bind(focus=ifmode_validate) diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 1b14ebb..07557da 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -626,6 +626,44 @@ MDScreen: font_size: dp(24) + MDBoxLayout: + orientation: "horizontal" + padding: [0,0,dp(24),0] + size_hint_y: None + height: dp(24) + + MDLabel: + id: connectivity_weave_label + text: "Connect via Weave" + font_style: "H6" + disabled: False + + MDSwitch: + id: connectivity_use_weave + active: False + pos_hint: {"center_y": 0.3} + disabled: False + + MDBoxLayout: + id: connectivity_weave_fields + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [0, 0, 0, dp(32)] + + MDTextField: + id: connectivity_weave_ifac_netname + hint_text: "Optional IFAC network name" + text: "" + font_size: dp(24) + + MDTextField: + id: connectivity_weave_ifac_passphrase + hint_text: "Optional IFAC passphrase" + text: "" + font_size: dp(24) + + # MDBoxLayout: # orientation: "horizontal" # padding: [0,0,dp(24),0] From b3057dabf88350db7bf7ffe2f92d52759083dcac Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 14:31:54 +0100 Subject: [PATCH 129/271] Cleanup --- sbapp/main.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 66de30d..212e161 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1467,15 +1467,12 @@ class SidebandApp(MDApp): if not self.messages_view.ids.message_text.focus: self.messages_view.ids.message_text.write_tab = False self.messages_view.ids.message_text.focus = True - def tab_job(delta): - self.messages_view.ids.message_text.write_tab = True + def tab_job(delta): self.messages_view.ids.message_text.write_tab = True Clock.schedule_once(tab_job, 0.15) elif len(modifiers) == 0 and self.rec_dialog != None and self.rec_dialog_is_open: - if text == " ": - self.msg_rec_a_rec(None) - elif keycode == 40: - self.msg_rec_a_save(None) + if text == " ": self.msg_rec_a_rec(None) + elif keycode == 40: self.msg_rec_a_save(None) elif len(modifiers) == 0 and not self.rec_dialog_is_open and not self.messages_view.ids.message_text.focus and self.messages_view.ptt_enabled and keycode == 44: if not self.key_ptt_down: @@ -1488,12 +1485,9 @@ class SidebandApp(MDApp): self.attach_path = None self.attach_type = None self.update_message_widgets() - if text == "a": - clear_att(); self.message_attachment_action(None) - if text == "i": - clear_att(); self.message_attach_action(attach_type="defimg") - if text == "f": - clear_att(); self.message_attach_action(attach_type="file") + if text == "a": clear_att(); self.message_attachment_action(None) + if text == "i": clear_att(); self.message_attach_action(attach_type="defimg") + if text == "f": clear_att(); self.message_attach_action(attach_type="file") if text == "v": clear_att() self.audio_msg_mode = LXMF.AM_OPUS_OGG From b7e24d8813abfbc240c637dc0b26b84878314abc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 15:05:55 +0100 Subject: [PATCH 130/271] 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 4be4d78..c13c85b 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 = 20251027 +android.numeric_version = 20251103 requirements = kivy==2.3.0,libbz2,sqlite3,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 From 1bb61c10097053b81a8caf8b739296f885bb0fda Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 15:06:08 +0100 Subject: [PATCH 131/271] Added Able to credits --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 212e161..a0a021e 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2997,7 +2997,7 @@ class SidebandApp(MDApp): str_comps = " - [b]Reticulum[/b] (Reticulum License)\n - [b]LXMF[/b] (Reticulum 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)" + str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]Able[/b] (MIT License)\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 8b191784f30befc78333737fc2e40602f2a9f86a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 16:20:39 +0100 Subject: [PATCH 132/271] Updated Raspberry Pi install instructions --- README.md | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 4bc11d3..5209582 100644 --- a/README.md +++ b/README.md @@ -133,34 +133,40 @@ python3 -m sbapp.main ## On Raspberry Pi -You can install Sideband on all Raspberry Pi models that support 64-bit operating systems, and can run at least Python version 3.11. Since some of Sideband's dependencies don't have pre-built packages ready for 64-bit ARM processors yet, you'll need to install a few extra packages, that will allow building these while installing. +You can install Sideband on all Raspberry Pi models that support 64-bit operating systems, and can run at least Python version 3.11. -Aditionally, the `pycodec2` package needs to be installed manually. I have provided a pre-built version, that you can download and install with a single command, or if you don't want to trust my pre-built version, you can [build and install it from source yourself](https://github.com/gregorias/pycodec2/blob/main/DEV.md). +The install instructions below assume that you are installing Sideband on 64-bit Raspberry Pi OS (based on Debian 13 "Trixie" or later). If you're running something else on your Pi, you might need to modify some commands slightly. -The install instructions below assume that you are installing Sideband on 64-bit Raspberry Pi OS (based on Debian Bookworm or later). If you're running something else on your Pi, you might need to modify some commands slightly. To install Sideband on Raspberry Pi with full support for voice calls, audio messages and Codec2, follow these steps: +To install Sideband on Raspberry Pi with full support for voice calls, audio messages and Codec2, follow these steps: ```bash -# First of all, install the required dependencies: -sudo apt install python3-pip python3-pyaudio python3-dev python3-cryptography build-essential libopusfile0 libsdl2-dev libavcodec-dev libavdevice-dev libavfilter-dev portaudio19-dev codec2 libcodec2-1.0 xclip xsel - -# If you don't want to compile pycodec2 yourself, -# download the pre-compiled package provided here: -wget https://raw.githubusercontent.com/markqvist/Sideband/main/docs/utilities/pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl - -# And install it: -pip install ./pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl --break-system-packages +# First of all, install the dependencies required +# for audio processing and voice calls. +# +# On Raspberry Pi OS "Trixie" (based on Debian 13) +# or newer, install these packages: +sudo apt install python3-pyaudio codec2 xclip xsel # You can now install Sideband pip install sbapp --break-system-packages -# Restart your Raspberry Pi +# Restart your Raspberry Pi to ensure the program +# is available in your PATH and application menus: sudo reboot # Everything is ready! You can now run Sideband -# from the terminal, or from the application menu +# from the terminal, or from the application menu: sideband ``` +If you're using an older version of Raspberry Pi OS, you will need to install these dependencies instead, before installing Sideband: + +```bash +# Package dependencies for Raspberry Pi OS based +# on Debian 12 Bookworm +sudo apt install python3-pip python3-pyaudio python3-dev python3-cryptography build-essential libopusfile0 libsdl2-dev libavcodec-dev libavdevice-dev libavfilter-dev portaudio19-dev codec2 libcodec2-1.0 xclip xsel +``` + If you do not already have Reticulum connectivity set up on your computer or local network, you will probably want to edit the Reticulum configuration file at `~/.reticulum/config` and [add any interfaces](https://reticulum.network/manual/interfaces.html) you need for connectivity. ## On macOS From 4daf4ef40a76f06850b99f3e25ffe0a396441813 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 16:27:18 +0100 Subject: [PATCH 133/271] Updated Linux install instructions --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 5209582..e6dc951 100644 --- a/README.md +++ b/README.md @@ -46,28 +46,31 @@ After the application is installed on your Android device, it is also possible t ## On Linux -On all Linux-based operating systems, Sideband is available as a `pipx`/`pip` package. This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. +On all Linux-based operating systems, Sideband is available as a `pip`/`pipx` package. This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. #### Basic Installation You will first need to install a few dependencies for voice calls, audio messaging and Codec2 support to work: ```bash +# For Debian (13+) and derivatives +sudo apt install python3-pyaudio codec2 xclip xsel + # For Debian (12+), Ubuntu (22.04+) and derivatives -sudo apt install pipx python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel +sudo apt install python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel # For Manjaro and derivatives -pamac install python-pipx python-pyaudio base-devel codec2 xclip xsel +pamac install python-pyaudio codec2 xclip xsel # For Arch and derivatives -sudo pacman -Sy python-pipx python-pyaudio base-devel codec2 xclip xsel +sudo pacman -Sy python-pyaudio codec2 xclip xsel ``` Once those are installed, install the Sideband application itself: ```bash -# Finally, install Sideband using pipx: -pipx install sbapp +# Finally, install Sideband using pip: +pip install sbapp --break-system-packages ``` After installation, you can now run Sideband in a number of different ways: @@ -106,11 +109,8 @@ If you do not already have Reticulum connectivity set up on your computer or loc You can also install Sideband in various alternative ways: ```bash -# Install Sideband via pip instead of pipx: -pip install sbapp - -# Or, if pip is externally managed: -pip install sbapp --break-system-packages +# Install Sideband via pipx instead of pip: +pipx install sbapp # Or, if you intend to run Sideband in headless # daemon mode, you can also install it without From 36af5d805dcc065c0836eb84f949a76ffe89bfbc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 16:29:04 +0100 Subject: [PATCH 134/271] Updated Linux install instructions --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e6dc951..c290360 100644 --- a/README.md +++ b/README.md @@ -52,10 +52,10 @@ On all Linux-based operating systems, Sideband is available as a `pip`/`pipx` pa You will first need to install a few dependencies for voice calls, audio messaging and Codec2 support to work: ```bash -# For Debian (13+) and derivatives +# For Debian 13+, Ubuntu 24.04+ and derivatives sudo apt install python3-pyaudio codec2 xclip xsel -# For Debian (12+), Ubuntu (22.04+) and derivatives +# For Debian 12+, Ubuntu 22.04+ and derivatives sudo apt install python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel # For Manjaro and derivatives From 14436bce086d673b6076024ffc5bb99c32d9d11e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 20:09:54 +0100 Subject: [PATCH 135/271] Go home Windows, you're drunk. Only apply UI scaling factor to window size on Linux. --- sbapp/main.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index a0a021e..e09bd4c 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -201,8 +201,9 @@ else: if not RNS.vendor.platformutils.is_android(): scaling_factor = 1.0 - try: scaling_factor = float(os.environ["KIVY_METRICS_DENSITY"]) - except Exception as e: pass + if not RNS.vendor.platformutils.is_windows() and not RNS.vendor.platformutils.is_darwin() + try: scaling_factor = float(os.environ["KIVY_METRICS_DENSITY"]) + except Exception as e: pass if scaling_factor < 0.75: scaling_factor = 0.75 if scaling_factor > 2: scaling_factor = 2 From c94e177405ee2df7a7cbf0e9f66c76db448a892f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 20:10:11 +0100 Subject: [PATCH 136/271] Updated makefile --- sbapp/Makefile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index a95c081..18f4c82 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -64,11 +64,11 @@ endif fetchshare: -(rm ./share/pkg/*) -(rm ./share/mirrors/* -r) - cp ../../dist_archive/rns-*-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/rnspure-*-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/lxmf-*-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/nomadnet-*-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/rnsh-*-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rns-1.0.1-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rnspure-1.0.1-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/lxmf-0.9.0-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/nomadnet-0.9.0-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rnsh-0.1.7-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/RNode_Firmware_*_Source.zip ./share/pkg/ zip --junk-paths ./share/pkg/example_plugins.zip ../docs/example_plugins/*.py cp -r ../../dist_archive/reticulum.network ./share/mirrors/ From 8cd00f29d9ab90fe62fe8667ad9a2c091be0d2c2 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 20:10:25 +0100 Subject: [PATCH 137/271] Updated Linux install instructions --- README.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c290360..4298051 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,10 @@ You will first need to install a few dependencies for voice calls, audio messagi ```bash # For Debian 13+, Ubuntu 24.04+ and derivatives -sudo apt install python3-pyaudio codec2 xclip xsel +sudo apt install python3-pip python3-pyaudio libopusfile0 codec2 xclip xsel # For Debian 12+, Ubuntu 22.04+ and derivatives -sudo apt install python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel +sudo apt install python3-pip python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel # For Manjaro and derivatives pamac install python-pyaudio codec2 xclip xsel @@ -71,17 +71,16 @@ Once those are installed, install the Sideband application itself: ```bash # Finally, install Sideband using pip: pip install sbapp --break-system-packages + +# If Sideband does not show up in your application menu +# or as an executable command in your terminal, reboot +# your computer. +sudo reboot ``` After installation, you can now run Sideband in a number of different ways: ```bash -# If this is the first time installing something with pipx, -# you may need to use the following command, to make your -# installed applications available. You'll probably need -# to close and reopen your terminal after this. -pipx ensurepath - # The first time you run Sideband, you will need to do it # from the terminal, for the application launcher item to # show up. On some distros you may also need to log out From 017a1c1b28b6b519a8f1b2c81df9c2481919fb18 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 20:16:41 +0100 Subject: [PATCH 138/271] Cleanup --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index e09bd4c..3a16105 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -201,7 +201,7 @@ else: if not RNS.vendor.platformutils.is_android(): scaling_factor = 1.0 - if not RNS.vendor.platformutils.is_windows() and not RNS.vendor.platformutils.is_darwin() + if not RNS.vendor.platformutils.is_windows() and not RNS.vendor.platformutils.is_darwin(): try: scaling_factor = float(os.environ["KIVY_METRICS_DENSITY"]) except Exception as e: pass From ef53318d29bbf7448452a76b6e3276586c1566a4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 21:20:53 +0100 Subject: [PATCH 139/271] Fixed potential race configuration in first config init --- sbapp/sideband/core.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index b653492..c09633b 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -292,6 +292,8 @@ class SidebandCore(): try: self.__load_config() except Exception as e: + RNS.log(f"An error occurred while loading existing Sideband configuration: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) self.__init_config() self.__load_config() self.first_run = False @@ -308,7 +310,8 @@ class SidebandCore(): self.clear_exports_dir() except Exception as e: - RNS.log("Error while configuring Sideband: "+str(e), RNS.LOG_ERROR) + RNS.log(f"Error while configuring Sideband: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) if load_config_only: return @@ -541,6 +544,8 @@ class SidebandCore(): self.config["telemetry_icon"] = SidebandCore.DEFAULT_APPEARANCE[0] self.config["telemetry_send_to_trusted"] = False self.config["telemetry_send_to_collector"] = False + self.config["telemetry_allow_requests_from_anyone"] = False + self.config["telemetry_allow_requests_from_trusted"] = False # Voice self.config["voice_enabled"] = False @@ -556,7 +561,7 @@ class SidebandCore(): self._db_inittelemetry() self._db_upgradetables() - self.__save_config() + self.__save_config(no_thread=True) def clear_map_cache(self): for entry in os.scandir(self.map_cache): @@ -929,7 +934,7 @@ class SidebandCore(): RNS.log("Error while reloading configuration: "+str(e), RNS.LOG_ERROR) RNS.trace_exception(e) - def __save_config(self): + def __save_config(self, no_thread=False): RNS.log("Saving Sideband configuration...", RNS.LOG_DEBUG) def save_function(): while self.saving_configuration: @@ -943,7 +948,8 @@ class SidebandCore(): self.saving_configuration = False RNS.log("Error while saving Sideband configuration: "+str(e), RNS.LOG_ERROR) - threading.Thread(target=save_function, daemon=True).start() + if no_thread: save_function() + else: threading.Thread(target=save_function, daemon=True).start() if self.is_client: self.setstate("wants.settings_reload", True) From 88e8db6118a9e5f65e04578c0062209117779e15 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 3 Nov 2025 22:35:22 +0100 Subject: [PATCH 140/271] Updated required LXMF to 0.9.1 --- sbapp/Makefile | 4 ++-- setup.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index 18f4c82..5508d19 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -66,8 +66,8 @@ fetchshare: -(rm ./share/mirrors/* -r) cp ../../dist_archive/rns-1.0.1-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/rnspure-1.0.1-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/lxmf-0.9.0-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/nomadnet-0.9.0-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/lxmf-0.9.1-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/nomadnet-0.9.1-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/rnsh-0.1.7-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/RNode_Firmware_*_Source.zip ./share/pkg/ zip --junk-paths ./share/pkg/example_plugins.zip ../docs/example_plugins/*.py diff --git a/setup.py b/setup.py index bc5700e..0147dfe 100644 --- a/setup.py +++ b/setup.py @@ -115,7 +115,7 @@ setuptools.setup( }, install_requires=[ "rns>=1.0.1", - "lxmf>=0.9.0", + "lxmf>=0.9.1", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From 00b95174586aa329574cd0f0b95f13f422522986 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 4 Nov 2025 14:19:46 +0100 Subject: [PATCH 141/271] Implemented window size and position persistence --- sbapp/main.py | 165 ++++++++++++++++++++++++++++++++++++----- sbapp/sideband/core.py | 1 + 2 files changed, 149 insertions(+), 17 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 3a16105..371ce5f 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -29,13 +29,51 @@ import RNS.vendor.umsgpack as msgpack WINDOW_DEFAULT_WIDTH = 494 WINDOW_DEFAULT_HEIGHT = 800 +WINDOW_HEIGHT_MARGIN = 0 + +WINDOW_MIN_WIDTH = 415 +WINDOW_MIN_HEIGHT = 550 + +app_ui_scaling_path = None +app_ui_wcfg_path = None +app_ui_window_config = None +app_ui_dsp_width = None +app_ui_dsp_height = None +app_init_window_state = "normal" + +def get_display_res(): + global app_ui_dsp_width, app_ui_dsp_height + if not RNS.vendor.platformutils.is_linux(): return None, None + else: + try: + import subprocess + cmd_xrandr = subprocess.Popen(['xrandr'], stdout=subprocess.PIPE) + cmd_grep = subprocess.Popen(['grep', '*'], stdin=cmd_xrandr.stdout, stdout=subprocess.PIPE) + cmd_xrandr.stdout.close(); res_bytes, _ = cmd_grep.communicate() + resolution = res_bytes.split()[0] + width, height = resolution.split(b'x') + app_ui_dsp_width = int(width) + app_ui_dsp_height = int(height) + return app_ui_dsp_width, app_ui_dsp_height + except Exception as e: + RNS.log(f"Could not get display resolution: {e}", RNS.LOG_WARNING) + RNS.trace_exception(e) + return None, None + -app_ui_scaling_path = None def apply_ui_scale(): global app_ui_scaling_path + global app_ui_wcfg_path + global app_ui_window_config default_scale = os.environ["KIVY_METRICS_DENSITY"] if "KIVY_METRICS_DENSITY" in os.environ else "unknown" - config_path = None + config_path = None ui_scale_path = None + ui_wcfg_path = None + res_ident = "" + dsp_width, dsp_height = get_display_res() + if dsp_width and dsp_height: + RNS.log(f"Got display res: {dsp_width}x{dsp_height}", RNS.LOG_DEBUG) + res_ident = f"_{dsp_width}_{dsp_height}" try: if RNS.vendor.platformutils.is_android(): @@ -50,7 +88,12 @@ def apply_ui_scale(): else: ui_scale_path = config_path+"/app_storage/ui_scale" + if ui_scale_path: + ui_scale_path = f"{ui_scale_path}{res_ident}" + ui_wcfg_path = f"{ui_scale_path}_windowcfg" + app_ui_scaling_path = ui_scale_path + app_ui_wcfg_path = ui_wcfg_path except Exception as e: RNS.log(f"Error while locating UI scale file: {e}", RNS.LOG_ERROR) @@ -58,11 +101,10 @@ def apply_ui_scale(): if ui_scale_path != None: RNS.log("Default scaling factor on this platform is "+str(default_scale), RNS.LOG_NOTICE) try: - RNS.log("Looking for scaling info in "+str(ui_scale_path)) + RNS.log("Looking for scaling info in "+str(ui_scale_path), RNS.LOG_NOTICE) if os.path.isfile(ui_scale_path): scale_factor = None - with open(ui_scale_path, "r") as sf: - scale_factor = float(sf.readline()) + with open(ui_scale_path, "r") as sf: scale_factor = float(sf.readline()) if scale_factor != None: if scale_factor >= 0.3 and scale_factor <= 5.0: @@ -75,6 +117,22 @@ def apply_ui_scale(): except Exception as e: RNS.log(f"Error while reading UI scaling factor: {e}", RNS.LOG_ERROR) + if ui_scale_path != None: + try: + RNS.log("Looking for saved window configuration in "+str(ui_wcfg_path), RNS.LOG_NOTICE) + if os.path.isfile(ui_wcfg_path): + scale_factor = None + with open(ui_wcfg_path, "r") as sf: window_config = sf.readline().split() + + if window_config != None: + RNS.log(f"READ SAVED WINDOW CONFIGURATION: {window_config}") + if type(window_config) == list and len(window_config) == 5: + app_ui_window_config = window_config + + + except Exception as e: + RNS.log(f"Error while reading saved window configuration: {e}", RNS.LOG_ERROR) + if args.export_settings: from .sideband.core import SidebandCore sideband = SidebandCore( @@ -200,33 +258,85 @@ else: apply_ui_scale() if not RNS.vendor.platformutils.is_android(): - scaling_factor = 1.0 + # Set default scaling factor and position + scaling_factor = 1.0 + window_target_x = None + window_target_y = None + window_state = "normal" + + # Attempt to read configured scaling factor + # from environment variable if not RNS.vendor.platformutils.is_windows() and not RNS.vendor.platformutils.is_darwin(): try: scaling_factor = float(os.environ["KIVY_METRICS_DENSITY"]) except Exception as e: pass + # Bound scaling factor to reasonable values if scaling_factor < 0.75: scaling_factor = 0.75 if scaling_factor > 2: scaling_factor = 2 - - model = None - max_width = WINDOW_DEFAULT_WIDTH*scaling_factor - max_height = WINDOW_DEFAULT_HEIGHT*scaling_factor + # Get reasonable maximum window bounds + if app_ui_dsp_width and app_ui_dsp_height: + # Use display resolution if available + max_width = app_ui_dsp_width + max_height = app_ui_dsp_height-WINDOW_HEIGHT_MARGIN + else: + # Assume bounds from default size * scaling + max_width = WINDOW_DEFAULT_WIDTH*scaling_factor + max_height = WINDOW_DEFAULT_HEIGHT*scaling_factor + + # Try to find device model to apply reasonable + # bounds on window sizes + model = None try: if os.path.isfile("/sys/firmware/devicetree/base/model"): with open("/sys/firmware/devicetree/base/model", "r") as mf: model = mf.read() except: pass + # Apply window sizing based on model if model: - if model.startswith("Raspberry Pi "): max_height = 625 + # Decrease default height for Raspberry Pi + # if screen resolution is unavailable, to + # avoid overflow on small screens + if model.startswith("Raspberry Pi ") and not app_ui_dsp_height: max_height = 625 - window_width = int(min(WINDOW_DEFAULT_WIDTH*scaling_factor, max_width)) - window_height = int(min(WINDOW_DEFAULT_HEIGHT*scaling_factor, max_height)) + # Initialize size to defaults + window_width_target = int(WINDOW_DEFAULT_WIDTH) + window_height_target = int(WINDOW_DEFAULT_HEIGHT) + + # But use saved window configuration if possible + if type(app_ui_window_config) == list and len(app_ui_window_config) == 5: + RNS.log(f"USING SAVED WINDOW CONFIGURATION: {app_ui_window_config}", RNS.LOG_NOTICE) + window_width_target = int(app_ui_window_config[0]) + window_height_target = int(app_ui_window_config[1]) + window_target_x = int(app_ui_window_config[2]) + window_target_y = int(app_ui_window_config[3]) + window_state = app_ui_window_config[4] + + if not window_state in ["maximized", "minimized", "normal"]: window_state = "normal" + if window_target_x < 0: window_target_x = 0 + if window_target_y < 0: window_target_y = 0 + + # Calculate final window size + window_width = int(max(min(window_width_target, max_width), WINDOW_MIN_WIDTH)) + window_height = int(max(min(window_height_target, max_height), WINDOW_MIN_HEIGHT)) + + if app_ui_dsp_width and app_ui_dsp_height and window_target_x and window_target_y: + if window_target_x > (app_ui_dsp_width - window_width): window_target_x = app_ui_dsp_width - window_width + if window_target_y > (app_ui_dsp_height - window_height): window_target_y = app_ui_dsp_height - window_height from kivy.config import Config Config.set("graphics", "width", str(window_width)) Config.set("graphics", "height", str(window_height)) + + if window_target_x and window_target_y: + Config.set('graphics', 'position', 'custom') + Config.set("graphics", "left", str(window_target_x)) + Config.set("graphics", "top", str(window_target_y)) + + if window_state == "maximized": + Config.set("graphics", "window_state", "maximized") + app_init_window_state = window_state from kivymd.app import MDApp app_superclass = MDApp @@ -410,6 +520,7 @@ class SidebandApp(MDApp): self.key_ptt_down = False Window.softinput_mode = "below_target" + self.window_state = app_init_window_state self.icon = self.sideband.asset_dir+"/icon.png" self.notification_icon = self.sideband.asset_dir+"/notification_icon.png" @@ -709,6 +820,18 @@ class SidebandApp(MDApp): self.apply_eink_mods() self.set_bars_colors() + def save_window_config(self): + try: + if not RNS.vendor.platformutils.is_android(): + wcfg = f"{Window.width} {Window.height} {Window.left} {Window.top} {self.window_state}" + if app_ui_wcfg_path == None: RNS.log("No path to UI window config file could be found, cannot save window config", RNS.LOG_ERROR) + else: + try: + with open(app_ui_wcfg_path, "w") as sfile: sfile.write(str(wcfg)) + RNS.log(f"Saved window config to {app_ui_wcfg_path}", RNS.LOG_DEBUG) + except Exception as e: RNS.log(f"Error while saving window config to {app_ui_wcfg_path}: {e}", RNS.LOG_ERROR) + except Exception as e: RNS.log("Error while saving window configuration: {e}", RNS.LOG_ERROR) + def update_ui_theme(self): if self.sideband.config["dark_ui"]: self.theme_cls.theme_style = "Dark" @@ -877,11 +1000,15 @@ class SidebandApp(MDApp): self.app_state = SidebandApp.STOPPING RNS.log("App stopped", RNS.LOG_DEBUG) + def on_maximize(self, sender): self.window_state = "maximized" + + def on_minimize(self, sender): self.window_state = "minimized" + + def on_restore(self, sender): self.window_state = "normal" + def is_in_foreground(self): - if self.app_state == SidebandApp.ACTIVE: - return True - else: - return False + if self.app_state == SidebandApp.ACTIVE: return True + else: return False def perform_paused_check(self, delta_time): # This workaround mitigates yet another bug in Kivy @@ -1400,6 +1527,10 @@ class SidebandApp(MDApp): Window.bind(on_request_close=self.close_requested) Window.bind(on_drop_file=self.file_dropped) + Window.bind(on_maximize=self.on_maximize) + Window.bind(on_minimize=self.on_minimize) + Window.bind(on_restore=self.on_restore) + if __variant__ != "": variant_str = " "+__variant__ else: diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index c09633b..c927a1a 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1032,6 +1032,7 @@ class SidebandCore(): def save_configuration(self): self.__save_config() + if self.is_standalone: self.owner_app.save_window_config() def set_active_propagation_node(self, dest): if dest == None: From e5dfa81b0a3e83d457e6e3087e74f58ae92b0f26 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 4 Nov 2025 15:26:00 +0100 Subject: [PATCH 142/271] Implemented Kivy/SDL2 workaround for slow window resize updates on Linux --- sbapp/main.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/sbapp/main.py b/sbapp/main.py index 371ce5f..e128ec6 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -133,6 +133,36 @@ def apply_ui_scale(): except Exception as e: RNS.log(f"Error while reading saved window configuration: {e}", RNS.LOG_ERROR) +################################################### +# Kivy/SDL2 run-time patch to fix horribly slow +# window resize updates on Linux. For more info: +# https://github.com/kivy/kivy/issues/9106 +# +_sdl2_window_event_filter_original = None +_sdl2_window_event_filter_instance = None +def _sdl2_window_event_filter_proxy(action, *largs): + global _sdl2_window_event_filter_original + global _sdl2_window_event_filter_instance + if not action == 'windowresized': return _sdl2_window_event_filter_original(action, *largs) + else: + _sdl2_window_event_filter_instance._size = largs + _sdl2_window_event_filter_instance._win.resize_window(*_sdl2_window_event_filter_instance._size) + # The only change this patched method makes is to + # remove the offending "EventLoop.idle()" statement + # EventLoop.idle() + return 0 + +def patch_sdl_window_events(patch_target): + if RNS.vendor.platformutils.is_linux(): + global _sdl2_window_event_filter_original + global _sdl2_window_event_filter_instance + _sdl2_window_event_filter_original = patch_target._event_filter + _sdl2_window_event_filter_instance = patch_target + patch_target._event_filter = _sdl2_window_event_filter_proxy + patch_target._win.set_event_filter(patch_target._event_filter) +# +# End of Kivy/SDL2 patch ########################## + if args.export_settings: from .sideband.core import SidebandCore sideband = SidebandCore( @@ -1531,6 +1561,8 @@ class SidebandApp(MDApp): Window.bind(on_minimize=self.on_minimize) Window.bind(on_restore=self.on_restore) + patch_sdl_window_events(Window) + if __variant__ != "": variant_str = " "+__variant__ else: From 7d0c9e8c4d5bb2f80954188d67e5a96a33860853 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 6 Nov 2025 09:17:12 +0100 Subject: [PATCH 143/271] Enabled LXST voice calls on Android --- sbapp/buildozer.spec | 4 ++-- sbapp/main.py | 20 +++++++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index c13c85b..5d5af68 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -4,8 +4,8 @@ package.name = sideband package.domain = io.unsigned source.dir = . -source.include_exts = py,png,jpg,jpeg,webp,ttf,kv,pyi,typed,so,0,1,2,3,atlas,frag,html,css,js,whl,zip,gz,woff2,pdf,epub,pgm -source.include_patterns = assets/*,assets/fonts/*,share/* +source.include_exts = py,png,jpg,jpeg,webp,ttf,kv,pyi,typed,so,0,1,2,3,atlas,frag,html,css,js,whl,zip,gz,woff2,pdf,epub,pgm,opus +source.include_patterns = assets/*,assets/fonts/*,assets/audio/notifications/*,share/* source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements,precompiled/*,parked/*,./setup.py,Makef*,./Makefile,Makefile,bin/*,build/*,dist/*,__pycache__/* version.regex = __version__ = ['"](.*)['"] diff --git a/sbapp/main.py b/sbapp/main.py index e128ec6..7aaa07a 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1831,6 +1831,25 @@ class SidebandApp(MDApp): Clock.schedule_once(final_exit, 0.85) + # def test_audio_action(self, sender=None): + # if not hasattr(self, "audiotestrunning") or self.audiotestrunning == False: + # RNS.log("LXST audio backend test starting", RNS.LOG_DEBUG) + # self.audiotestrunning = True + # import LXST + # ringtone_path = os.path.join(self.sideband.asset_dir, "audio", "notifications", "soft1.opus") + # target_frame_ms = 40 + # selected_source = LXST.Sources.OpusFileSource(ringtone_path, loop=True, target_frame_ms=target_frame_ms) + # line_sink = LXST.Sinks.LineSink() + # loopback = LXST.Sources.Loopback() + # raw = LXST.Codecs.Raw() + # self.input_pipeline = LXST.Pipeline(source=selected_source, codec=raw, sink=loopback) + # self.output_pipeline = LXST.Pipeline(source=loopback, codec=raw, sink=line_sink) + # self.input_pipeline.start(); self.output_pipeline.start() + # else: + # RNS.log("LXST audio backend test stopping", RNS.LOG_DEBUG) + # self.input_pipeline.stop() + # self.audiotestrunning = False + def announce_now_action(self, sender=None): self.sideband.lxmf_announce() if self.sideband.telephone: self.sideband.telephone.announce() @@ -3684,7 +3703,6 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_voice_enabled.active = self.sideband.config["voice_enabled"] self.settings_screen.ids.settings_voice_enabled.bind(active=save_voice_enabled) - if RNS.vendor.platformutils.is_android(): self.settings_screen.ids.settings_voice_enabled.disabled = True self.settings_screen.ids.settings_debug.active = self.sideband.config["debug"] self.settings_screen.ids.settings_debug.bind(active=save_debug) From cf0d64a746ba0b25c658871f298ab730ac4758e6 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 6 Nov 2025 12:11:54 +0100 Subject: [PATCH 144/271] Implemented voice call support on Android --- sbapp/main.py | 23 +++++---- sbapp/sideband/core.py | 105 ++++++++++++++++++++++++++++------------ sbapp/sideband/voice.py | 33 ++++++++++++- 3 files changed, 119 insertions(+), 42 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 7aaa07a..ef304dc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1385,9 +1385,8 @@ class SidebandApp(MDApp): dialog = MDDialog( title="Error", text=info_text, - buttons=[ ok_button ], - # elevation=0, - ) + buttons=[ ok_button ]) + def dl_ok(s): dialog.dismiss() self.quit_action(s) @@ -1434,10 +1433,16 @@ class SidebandApp(MDApp): self.hw_error_dialog.open() self.hw_error_dialog.is_open = True + if RNS.vendor.platformutils.is_android(): + service_voice_running = self.sideband.service_voice_running() + if service_voice_running: self.sideband.voice_running = True + else: self.sideband.voice_running = False + incoming_call = self.sideband.getstate("voice.incoming_call") if incoming_call: self.sideband.setstate("voice.incoming_call", None) - toast(f"Call from {incoming_call}", duration=7) + if RNS.vendor.platformutils.is_android(): toast(f"Call from {incoming_call}") + else: toast(f"Call from {incoming_call}", duration=7) if self.root.ids.screen_manager.current == "messages_screen": self.messages_view.update() @@ -3521,10 +3526,8 @@ class SidebandApp(MDApp): self.sideband.config["voice_enabled"] = self.settings_screen.ids.settings_voice_enabled.active self.sideband.save_configuration() - if self.sideband.config["voice_enabled"] == True: - self.sideband.start_voice() - else: - self.sideband.stop_voice() + if self.sideband.config["voice_enabled"] == True: self.sideband.start_voice() + else: self.sideband.stop_voice() def save_print_command(sender=None, event=None): if not sender.focus: @@ -5784,7 +5787,9 @@ class SidebandApp(MDApp): def voice_answer_action(self, sender=None): if self.sideband.voice_running: - if self.sideband.telephone.is_ringing: self.sideband.telephone.answer() + if self.sideband.telephone.is_ringing: + self.sideband.telephone.answer() + toast("Call answered") def voice_reject_action(self, sender=None): if self.sideband.voice_running: diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index c927a1a..78825dd 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1767,6 +1767,9 @@ class SidebandCore(): def gui_conversation(self): return self.getstate("app.active_conversation") + def service_voice_running(self): + return self.getstate("voice.running") + def setstate(self, prop, val): with self.state_lock: if not self.service_stopped: @@ -2083,16 +2086,6 @@ class SidebandCore(): elif "set_ui_recording" in call: self.service_rpc_set_ui_recording(call["set_ui_recording"]) connection.send(True) - elif "get_plugins_info" in call: - connection.send(self._get_plugins_info()) - elif "get_destination_establishment_rate" in call: - connection.send(self._get_destination_establishment_rate(call["get_destination_establishment_rate"])) - elif "get_destination_mtu" in call: - connection.send(self._get_destination_mtu(call["get_destination_mtu"])) - elif "get_destination_edr" in call: - connection.send(self._get_destination_edr(call["get_destination_edr"])) - elif "get_destination_lmd" in call: - connection.send(self._get_destination_lmd(call["get_destination_lmd"])) elif "send_message" in call: args = call["send_message"] send_result = self.send_message( @@ -2128,25 +2121,32 @@ class SidebandCore(): is_authorized_telemetry_request=args["is_authorized_telemetry_request"] ) connection.send(send_result) - elif "get_lxm_progress" in call: - args = call["get_lxm_progress"] - connection.send(self.get_lxm_progress(args["lxm_hash"])) - elif "get_lxm_stamp_cost" in call: - args = call["get_lxm_stamp_cost"] - connection.send(self.get_lxm_stamp_cost(args["lxm_hash"])) - elif "get_lxm_propagation_cost" in call: - args = call["get_lxm_propagation_cost"] - connection.send(self.get_lxm_propagation_cost(args["lxm_hash"])) - elif "is_tracking" in call: - connection.send(self.is_tracking(call["is_tracking"])) - elif "start_tracking" in call: - args = call["start_tracking"] - connection.send(self.start_tracking(object_addr=args["object_addr"], interval=args["interval"], duration=args["duration"])) - elif "stop_tracking" in call: - args = call["stop_tracking"] - connection.send(self.stop_tracking(object_addr=args["object_addr"])) - elif "get_service_log" in call: - connection.send(self.get_service_log()) + elif "get_plugins_info" in call: connection.send(self._get_plugins_info()) + elif "get_destination_establishment_rate" in call: connection.send(self._get_destination_establishment_rate(call["get_destination_establishment_rate"])) + elif "get_destination_mtu" in call: connection.send(self._get_destination_mtu(call["get_destination_mtu"])) + elif "get_destination_edr" in call: connection.send(self._get_destination_edr(call["get_destination_edr"])) + elif "get_destination_lmd" in call: connection.send(self._get_destination_lmd(call["get_destination_lmd"])) + elif "get_lxm_progress" in call: connection.send(self.get_lxm_progress(call["get_lxm_progress"]["lxm_hash"])) + elif "get_lxm_stamp_cost" in call: connection.send(self.get_lxm_stamp_cost(call["get_lxm_stamp_cost"]["lxm_hash"])) + elif "get_lxm_propagation_cost" in call: connection.send(self.get_lxm_propagation_cost(call["get_lxm_propagation_cost"]["lxm_hash"])) + elif "is_tracking" in call: connection.send(self.is_tracking(call["is_tracking"])) + elif "start_tracking" in call: connection.send(self.start_tracking(object_addr=call["start_tracking"]["object_addr"], interval=args["interval"], duration=args["duration"])) + elif "stop_tracking" in call: connection.send(self.stop_tracking(object_addr=call["stop_tracking"]["object_addr"])) + elif "get_service_log" in call: connection.send(self.get_service_log()) + elif "start_voice" in call: connection.send(self.start_voice()) + elif "stop_voice" in call: connection.send(self.stop_voice()) + elif "telephone_is_available" in call: connection.send(self.telephone.is_available) if self.telephone else False + elif "telephone_is_in_call" in call: connection.send(self.telephone.is_in_call) if self.telephone else False + elif "telephone_call_is_connecting" in call: connection.send(self.telephone.call_is_connecting) if self.telephone else False + elif "telephone_is_ringing" in call: connection.send(self.telephone.is_ringing) if self.telephone else False + elif "telephone_caller_info" in call: connection.send(self.telephone.caller.hash) if self.telephone and self.telephone.caller else None + elif "telephone_set_busy" in call: connection.send(self.telephone.set_busy(call["telephone_set_busy"])) if self.telephone else False + elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"])) if self.telephone else False + elif "telephone_hangup" in call: connection.send(self.telephone.hangup()) if self.telephone else False + elif "telephone_answer" in call: connection.send(self.telephone.answer()) if self.telephone else False + elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"])) if self.telephone else False + elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"])) if self.telephone else False + elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"])) if self.telephone else False else: connection.send(None) @@ -3896,8 +3896,14 @@ class SidebandCore(): if self.is_standalone or self.is_client: if self.config["telemetry_enabled"]: self.run_telemetry() - if self.config["voice_enabled"]: self.start_voice() + if self.config["voice_enabled"]: + if not RNS.vendor.platformutils.is_android(): self.start_voice() + else: + from .voice import ReticulumTelephoneProxy + self.telephone = ReticulumTelephoneProxy(owner=self) + elif self.is_service: + if self.config["voice_enabled"]: self.start_voice() self.run_service_telemetry() def __add_localinterface(self, delay=None): @@ -5501,22 +5507,40 @@ class SidebandCore(): if not self.reticulum.is_connected_to_shared_instance: RNS.Transport.detach_interfaces() - def start_voice(self): + def _start_voice(self): try: if not self.voice_running: RNS.log("Starting voice service", RNS.LOG_DEBUG) self.voice_running = True + self.setstate("voice.running", self.voice_running) from .voice import ReticulumTelephone self.telephone = ReticulumTelephone(self.identity, owner=self, speaker=self.config["voice_output"], microphone=self.config["voice_input"], ringer=self.config["voice_ringer"]) ringtone_path = os.path.join(self.asset_dir, "audio", "notifications", "soft1.opus") self.telephone.set_ringtone(ringtone_path) + return True except Exception as e: self.voice_running = False RNS.log(f"An error occurred while starting voice services, the contained exception was: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) + return False - def stop_voice(self): + def start_voice(self): + if not RNS.vendor.platformutils.is_android(): return self._start_voice() + else: + if self.is_service: return self._start_voice() + else: + try: + if self.service_rpc_request({"start_voice": True}): + from .voice import ReticulumTelephoneProxy + self.telephone = ReticulumTelephoneProxy(owner=self) + self.voice_running = True + + except Exception as e: + RNS.log("Error while starting voice service over RPC: "+str(e), RNS.LOG_DEBUG) + return False + + def _stop_voice(self): try: if self.voice_running: RNS.log("Stopping voice service", RNS.LOG_DEBUG) @@ -5526,10 +5550,27 @@ class SidebandCore(): self.telephone = None self.voice_running = False + self.setstate("voice.running", self.voice_running) + return True except Exception as e: RNS.log(f"An error occurred while stopping voice services, the contained exception was: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) + return False + + def stop_voice(self): + if not RNS.vendor.platformutils.is_android(): return self._stop_voice() + else: + if self.is_service: return self._stop_voice() + else: + try: + if self.service_rpc_request({"stop_voice": True}): + self.telephone = None + self.voice_running = False + + except Exception as e: + RNS.log("Error while stopping voice service over RPC: "+str(e), RNS.LOG_DEBUG) + return False def incoming_call(self, remote_identity): display_name = self.voice_display_name(remote_identity.hash) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 67a91ca..44cb758 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -44,7 +44,7 @@ class ReticulumTelephone(): self.aliases = {} self.names = {} - self.telephone = Telephone(self.identity, ring_time=self.RING_TIME, wait_time=self.WAIT_TIME) + self.telephone = Telephone(self.identity, ring_time=self.RING_TIME, wait_time=self.WAIT_TIME) self.telephone.set_ringing_callback(self.ringing) self.telephone.set_established_callback(self.call_established) self.telephone.set_ended_callback(self.call_ended) @@ -169,3 +169,34 @@ class ReticulumTelephone(): return False else: return True + +class CallerProxy(): + def __init__(self, hash=None): + self.hash = hash + +class ReticulumTelephoneProxy(): + PATH_TIME = ReticulumTelephone.PATH_TIME + def __init__(self, owner=None): self.owner = owner + + @property + def is_available(self): return self.owner.service_rpc_request({"telephone_is_available": True }) + + @property + def is_in_call(self): return self.owner.service_rpc_request({"telephone_is_in_call": True }) + + @property + def call_is_connecting(self): return self.owner.service_rpc_request({"telephone_call_is_connecting": True }) + + @property + def is_ringing(self): return self.owner.service_rpc_request({"telephone_is_ringing": True }) + + @property + def caller(self): return CallerProxy(hash=self.owner.service_rpc_request({"telephone_caller_info": True })) + + def set_busy(self, busy): return self.owner.service_rpc_request({"telephone_set_busy": busy }) + def dial(self, dial_target): return self.owner.service_rpc_request({"telephone_dial": dial_target }) + def hangup(self): return self.owner.service_rpc_request({"telephone_hangup": True }) + def answer(self): return self.owner.service_rpc_request({"telephone_answer": True }) + def set_speaker(self, speaker): return self.owner.service_rpc_request({"telephone_set_speaker": speaker }) + def set_microphone(self, microphone): return self.owner.service_rpc_request({"telephone_set_microphone": microphone }) + def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) \ No newline at end of file From 6b09c6b26295196d41b72d9e1e421e57e6e3ab87 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 6 Nov 2025 17:07:00 +0100 Subject: [PATCH 145/271] Added voice call notifications --- sbapp/main.py | 7 +- sbapp/services/sidebandservice.py | 124 ++++++++++++++++-------------- sbapp/sideband/core.py | 2 + 3 files changed, 75 insertions(+), 58 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index ef304dc..643b9f1 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1274,8 +1274,11 @@ class SidebandApp(MDApp): data = extras.getString("intent_action", "undefined") if data.startswith("conversation."): conv_hexhash = bytes.fromhex(data.replace("conversation.", "")) - def cb(dt): - self.open_conversation(conv_hexhash) + def cb(dt): self.open_conversation(conv_hexhash) + Clock.schedule_once(cb, 0.2) + + elif data.startswith("incoming_call"): + def cb(dt): self.voice_action() Clock.schedule_once(cb, 0.2) except Exception as e: diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index 3265023..f52a809 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -65,71 +65,83 @@ class SidebandService(): } def android_notification(self, title="", content="", ticker="", group=None, context_id=None): - if android_api_version < 26: - return - else: - package_name = "io.unsigned.sideband" - - if not self.notification_service: - self.notification_service = cast(NotificationManager, self.app_context.getSystemService( - Context.NOTIFICATION_SERVICE - )) - - channel_id = package_name - group_id = "" - if group != None: - channel_id += "."+str(group) - group_id += str(group) - if context_id != None: - channel_id += "."+str(context_id) - group_id += "."+str(context_id) - - if not title or title == "": - channel_name = "Sideband" + try: + if android_api_version < 26: return else: - channel_name = title + package_name = "io.unsigned.sideband" + silent_contexts = ["incoming_call"] - self.notification_channel = NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_DEFAULT) - self.notification_channel.enableVibration(True) - self.notification_channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), None) - self.notification_channel.setShowBadge(True) - self.notification_service.createNotificationChannel(self.notification_channel) + if not self.notification_service: + self.notification_service = cast(NotificationManager, self.app_context.getSystemService(Context.NOTIFICATION_SERVICE)) - notification = NotificationBuilder(self.app_context, channel_id) - notification.setContentTitle(title) - notification.setContentText(AndroidString(content)) - notification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) - - # if group != None: - # notification.setGroup(group_id) + channel_id = package_name + group_id = "" + if group != None: + channel_id += "."+str(group) + group_id += str(group) + if context_id != None: + channel_id += "."+str(context_id) + group_id += "."+str(context_id) - if not self.notification_small_icon: - # path = self.sideband.notification_icon - path = self.sideband.notif_icon_black - bitmap = BitmapFactory.decodeFile(path) - self.notification_small_icon = Icon.createWithBitmap(bitmap) + if not title or title == "": channel_name = "Sideband" + else: channel_name = title - notification.setSmallIcon(self.notification_small_icon) - # notification.setLargeIcon(self.notification_small_icon) + if context_id in silent_contexts: silent = True + else: silent = False - # large_icon_path = self.sideband.icon - # bitmap_icon = BitmapFactory.decodeFile(large_icon_path) - # notification.setLargeIcon(bitmap_icon) + self.notification_channel = NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_DEFAULT) + self.notification_channel.enableVibration(True) + if not silent: self.notification_channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), None) + else: self.notification_channel.setSound(None, None) + self.notification_channel.setShowBadge(True) + self.notification_service.createNotificationChannel(self.notification_channel) - notification_intent = Intent(self.app_context, python_act) - notification_intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) - notification_intent.setAction(Intent.ACTION_MAIN) - notification_intent.addCategory(Intent.CATEGORY_LAUNCHER) - if context_id != None: - cstr = f"conversation.{context_id}" - notification_intent.putExtra(JString("intent_action"), JString(cstr)) - self.notification_intent = PendingIntent.getActivity(self.app_context, 0, notification_intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT) + notification = NotificationBuilder(self.app_context, channel_id) + notification.setContentTitle(title) + notification.setContentText(AndroidString(content)) + + if not silent: notification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) + else: notification.setSound(None, None) + + # if group != None: + # notification.setGroup(group_id) - notification.setContentIntent(self.notification_intent) - notification.setAutoCancel(True) + if not self.notification_small_icon: + # path = self.sideband.notification_icon + path = self.sideband.notif_icon_black + bitmap = BitmapFactory.decodeFile(path) + self.notification_small_icon = Icon.createWithBitmap(bitmap) - built_notification = notification.build() - self.notification_service.notify(0, built_notification) + notification.setSmallIcon(self.notification_small_icon) + # notification.setLargeIcon(self.notification_small_icon) + + # large_icon_path = self.sideband.icon + # bitmap_icon = BitmapFactory.decodeFile(large_icon_path) + # notification.setLargeIcon(bitmap_icon) + + notification_intent = Intent(self.app_context, python_act) + notification_intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) + notification_intent.setAction(Intent.ACTION_MAIN) + notification_intent.addCategory(Intent.CATEGORY_LAUNCHER) + if context_id != None: + if context_id == "incoming_call": + cstr = context_id + notification_intent.putExtra(JString("intent_action"), JString(cstr)) + else: + cstr = f"conversation.{context_id}" + notification_intent.putExtra(JString("intent_action"), JString(cstr)) + + self.notification_intent = PendingIntent.getActivity(self.app_context, 0, notification_intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT) + + notification.setContentIntent(self.notification_intent) + notification.setAutoCancel(True) + + built_notification = notification.build() + self.notification_service.notify(0, built_notification) + + except Exception as e: + RNS.log(f"Error while creating notification: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) def check_permission(self, permission): if RNS.vendor.platformutils.is_android(): diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 78825dd..e0abe85 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5575,6 +5575,8 @@ class SidebandCore(): def incoming_call(self, remote_identity): display_name = self.voice_display_name(remote_identity.hash) self.setstate("voice.incoming_call", display_name) + if self.gui_foreground(): RNS.log("Squelching call notification since GUI is in foreground", RNS.LOG_DEBUG) + else: self.notify(title="Incoming voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") rns_config = """# This template is used to generate a # running configuration for Sideband's From 829ccc6df959c6d35ac4c850af4aadcea0e2b8ec Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 6 Nov 2025 17:07:48 +0100 Subject: [PATCH 146/271] Cleanup --- sbapp/services/sidebandservice.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index f52a809..75796a8 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -103,9 +103,6 @@ class SidebandService(): if not silent: notification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) else: notification.setSound(None, None) - # if group != None: - # notification.setGroup(group_id) - if not self.notification_small_icon: # path = self.sideband.notification_icon path = self.sideband.notif_icon_black From 0112f85d343b6c541b22ff3fff764b8554d9d8e1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 6 Nov 2025 22:46:22 +0100 Subject: [PATCH 147/271] Added low-latency output mode configuration option for LXST voice calls --- sbapp/sideband/core.py | 4 ++++ sbapp/sideband/voice.py | 4 +++- sbapp/ui/voice.py | 31 +++++++++++++++++++++++++++---- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index e0abe85..76414fe 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -906,6 +906,8 @@ class SidebandCore(): self.config["voice_ringer"] = None if not "voice_trusted_only" in self.config: self.config["voice_trusted_only"] = False + if not "voice_low_latency" in self.config: + self.config["voice_low_latency"] = False # Make sure we have a database if not os.path.isfile(self.db_path): @@ -2147,6 +2149,7 @@ class SidebandCore(): elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"])) if self.telephone else False elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"])) if self.telephone else False elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"])) if self.telephone else False + elif "telephone_set_low_latency_output" in call: connection.send(self.telephone.set_low_latency_output(call["telephone_set_low_latency_output"])) if self.telephone else False else: connection.send(None) @@ -5517,6 +5520,7 @@ class SidebandCore(): self.telephone = ReticulumTelephone(self.identity, owner=self, speaker=self.config["voice_output"], microphone=self.config["voice_input"], ringer=self.config["voice_ringer"]) ringtone_path = os.path.join(self.asset_dir, "audio", "notifications", "soft1.opus") self.telephone.set_ringtone(ringtone_path) + self.telephone.set_low_latency_output(self.config["voice_low_latency"]) return True except Exception as e: diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 44cb758..07bbb48 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -111,6 +111,7 @@ class ReticulumTelephone(): def hangup(self): self.telephone.hangup() def answer(self): self.telephone.answer(self.caller) def set_busy(self, busy): self.telephone.set_busy(busy) + def set_low_latency_output(self, enabled): self.telephone.set_low_latency_output(enabled) def dial(self, identity_hash): self.last_dialled_identity_hash = identity_hash @@ -199,4 +200,5 @@ class ReticulumTelephoneProxy(): def answer(self): return self.owner.service_rpc_request({"telephone_answer": True }) def set_speaker(self, speaker): return self.owner.service_rpc_request({"telephone_set_speaker": speaker }) def set_microphone(self, microphone): return self.owner.service_rpc_request({"telephone_set_microphone": microphone }) - def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) \ No newline at end of file + def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) + def set_low_latency_output(self, enabled): return self.owner.service_rpc_request({"telephone_set_low_latency_output": enabled}) \ No newline at end of file diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 60d19fd..b0f8e9a 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -202,8 +202,10 @@ class Voice(): def update_settings_screen(self, sender=None): self.voice_settings_screen.ids.voice_trusted_only.active = self.app.sideband.config["voice_trusted_only"] self.voice_settings_screen.ids.voice_trusted_only.bind(active=self.settings_save_action) + self.voice_settings_screen.ids.voice_low_latency.active = self.app.sideband.config["voice_low_latency"] + self.voice_settings_screen.ids.voice_low_latency.bind(active=self.settings_save_action) - bp = 6; ml = 45; fs = 16; ics = 14 + bp = 6; ml = 38; fs = 16; ics = 14 self.update_devices() # Output devices @@ -216,7 +218,8 @@ class Voice(): for device in self.output_devices: if not device in self.listed_output_devices: - label = device if len(device) < ml else device[:ml-3]+"..." + device_str = device.replace("[", "").replace("]", "") + label = device_str if len(device_str) < ml else device_str[:ml-3]+"..." device_button = MDRectangleFlatIconButton(text=label, font_size=dp(fs), icon_size=dp(ics), on_release=self.output_device_action) device_button.padding = [dp(bp), dp(bp), dp(bp), dp(bp)]; device_button.size_hint = [1.0, None] if self.app.sideband.config["voice_output"] == device: device_button.icon = "check" @@ -234,7 +237,8 @@ class Voice(): for device in self.input_devices: if not device in self.listed_input_devices: - label = device if len(device) < ml else device[:ml-3]+"..." + device_str = device.replace("[", "").replace("]", "") + label = device_str if len(device_str) < ml else device_str[:ml-3]+"..." device_button = MDRectangleFlatIconButton(text=label, font_size=dp(fs), icon_size=dp(ics), on_release=self.input_device_action) device_button.padding = [dp(bp), dp(bp), dp(bp), dp(bp)]; device_button.size_hint = [1.0, None] if self.app.sideband.config["voice_input"] == device: device_button.icon = "check" @@ -252,7 +256,8 @@ class Voice(): for device in self.output_devices: if not device in self.listed_ringer_devices: - label = device if len(device) < ml else device[:ml-3]+"..." + device_str = device.replace("[", "").replace("]", "") + label = device_str if len(device_str) < ml else device_str[:ml-3]+"..." device_button = MDRectangleFlatIconButton(text=label, font_size=dp(fs), icon_size=dp(ics), on_release=self.ringer_device_action) device_button.padding = [dp(bp), dp(bp), dp(bp), dp(bp)]; device_button.size_hint = [1.0, None] if self.app.sideband.config["voice_ringer"] == device: device_button.icon = "check" @@ -262,7 +267,10 @@ class Voice(): def settings_save_action(self, sender=None, event=None): self.app.sideband.config["voice_trusted_only"] = self.voice_settings_screen.ids.voice_trusted_only.active + self.app.sideband.config["voice_low_latency"] = self.voice_settings_screen.ids.voice_low_latency.active self.app.sideband.save_configuration() + if self.app.sideband.telephone: + self.app.sideband.telephone.set_low_latency_output(self.app.sideband.config["voice_low_latency"]) def output_device_action(self, sender=None): self.app.sideband.config["voice_output"] = sender.device @@ -415,6 +423,21 @@ MDScreen: pos_hint: {"center_y": 0.3} active: False + MDBoxLayout: + orientation: "horizontal" + padding: [0,0,dp(24),0] + size_hint_y: None + height: dp(48) + + MDLabel: + text: "Low-latency output" + font_style: "H6" + + MDSwitch: + id: voice_low_latency + pos_hint: {"center_y": 0.3} + active: False + MDLabel: text: "Audio Devices" font_style: "H6" From 3754f3bfa974df706c88a9a1930aaccb24f97119 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 6 Nov 2025 22:52:35 +0100 Subject: [PATCH 148/271] Updated LXST dependency --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 0147dfe..4766856 100644 --- a/setup.py +++ b/setup.py @@ -123,7 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy>=2.0.0", - "lxst>=0.3.0", + "lxst>=0.4.0", "mistune>=3.0.2", "beautifulsoup4", "pycodec2>=4.1.0;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From 92635ea1f2e2dd4478b0190d61013019fa83bbc1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 7 Nov 2025 10:24:26 +0100 Subject: [PATCH 149/271] Fixed missing telephone announce handler in frontend/service proxy on Android --- sbapp/sideband/core.py | 1 + sbapp/sideband/voice.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 76414fe..a83d121 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2150,6 +2150,7 @@ class SidebandCore(): elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"])) if self.telephone else False elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"])) if self.telephone else False elif "telephone_set_low_latency_output" in call: connection.send(self.telephone.set_low_latency_output(call["telephone_set_low_latency_output"])) if self.telephone else False + elif "telephone_announce" in call: connection.send(self.telephone.announce()) if self.telephone else False else: connection.send(None) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 07bbb48..72ad879 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -201,4 +201,5 @@ class ReticulumTelephoneProxy(): def set_speaker(self, speaker): return self.owner.service_rpc_request({"telephone_set_speaker": speaker }) def set_microphone(self, microphone): return self.owner.service_rpc_request({"telephone_set_microphone": microphone }) def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) - def set_low_latency_output(self, enabled): return self.owner.service_rpc_request({"telephone_set_low_latency_output": enabled}) \ No newline at end of file + def set_low_latency_output(self, enabled): return self.owner.service_rpc_request({"telephone_set_low_latency_output": enabled}) + def announce(self): return self.owner.service_rpc_request({"telephone_announce": True}) \ No newline at end of file From dce43bdcfc08a6c4ee888e87d2d09171941678bf Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 7 Nov 2025 10:43:26 +0100 Subject: [PATCH 150/271] Updated version --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 643b9f1..8b320e3 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.8.0" +__version__ = "1.8.1" __variant__ = "" import sys From 0c965d92592db897e67f97823a9107adeabab9d3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 7 Nov 2025 23:15:23 +0100 Subject: [PATCH 151/271] Ensure RNS exit handlers are executed on service shutdown, in case OS event is not sent. Fixes #90. --- sbapp/sideband/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index a83d121..76627c0 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5509,7 +5509,7 @@ class SidebandCore(): def cleanup(self): if RNS.vendor.platformutils.get_platform() == "android": if not self.reticulum.is_connected_to_shared_instance: - RNS.Transport.detach_interfaces() + RNS.Reticulum.exit_handler() def _start_voice(self): try: From 4ee9623033a1a08a5ebd36f18ecf5a74b2cecf31 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 8 Nov 2025 00:14:57 +0100 Subject: [PATCH 152/271] Request microphone permission on voice calls enable --- sbapp/main.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 8b320e3..aabe9ab 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3529,8 +3529,10 @@ class SidebandApp(MDApp): self.sideband.config["voice_enabled"] = self.settings_screen.ids.settings_voice_enabled.active self.sideband.save_configuration() - if self.sideband.config["voice_enabled"] == True: self.sideband.start_voice() - else: self.sideband.stop_voice() + if self.sideband.config["voice_enabled"] == True: + self.request_microphone_permission() + self.sideband.start_voice() + else: self.sideband.stop_voice() def save_print_command(sender=None, event=None): if not sender.focus: From a6618da2294af249467e089ae2ec78aae9c08526 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 8 Nov 2025 13:59:23 +0100 Subject: [PATCH 153/271] Fixed missing location permission check for scanning and pairing BLE RNodes --- sbapp/main.py | 130 ++++++++++++++++++++++++++++++-------------- sbapp/ui/layouts.py | 2 +- 2 files changed, 90 insertions(+), 42 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index aabe9ab..e8b0432 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -65,8 +65,11 @@ def apply_ui_scale(): global app_ui_scaling_path global app_ui_wcfg_path global app_ui_window_config + + if args.config != None: config_path = os.path.expanduser(args.config) + else: config_path = None + default_scale = os.environ["KIVY_METRICS_DENSITY"] if "KIVY_METRICS_DENSITY" in os.environ else "unknown" - config_path = None ui_scale_path = None ui_wcfg_path = None res_ident = "" @@ -125,7 +128,6 @@ def apply_ui_scale(): with open(ui_wcfg_path, "r") as sf: window_config = sf.readline().split() if window_config != None: - RNS.log(f"READ SAVED WINDOW CONFIGURATION: {window_config}") if type(window_config) == list and len(window_config) == 5: app_ui_window_config = window_config @@ -336,7 +338,6 @@ else: # But use saved window configuration if possible if type(app_ui_window_config) == list and len(app_ui_window_config) == 5: - RNS.log(f"USING SAVED WINDOW CONFIGURATION: {app_ui_window_config}", RNS.LOG_NOTICE) window_width_target = int(app_ui_window_config[0]) window_height_target = int(app_ui_window_config[1]) window_target_x = int(app_ui_window_config[2]) @@ -1077,6 +1078,16 @@ class SidebandApp(MDApp): self.root.ids.nav_drawer.set_state("closed") Clock.schedule_once(cb, 0) + def has_location_permissions(self): + if RNS.vendor.platformutils.is_android(): + if RNS.vendor.platformutils.is_android(): + if check_permission("android.permission.ACCESS_COARSE_LOCATION") and check_permission("android.permission.ACCESS_FINE_LOCATION"): return True + else: return False + + def request_location_permissions(self): + if not self.has_location_permissions(): + RNS.log("Requesting location permission", RNS.LOG_DEBUG) + request_permissions(["android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"]) def check_bluetooth_permissions(self): if RNS.vendor.platformutils.get_platform() == "android": @@ -1208,25 +1219,46 @@ class SidebandApp(MDApp): RNS.log(f"Updated bonded devices: {self.bt_bonded_devices}", RNS.LOG_DEBUG) def bluetooth_scan_action(self, sender=None): - toast("Starting Bluetooth scan...") self.start_bluetooth_scan() def start_bluetooth_scan(self): - self.check_bluetooth_permissions() - if not self.sideband.getpersistent("permissions.bluetooth"): - self.request_bluetooth_permissions() + if not self.has_location_permissions(): + if not hasattr(self, "permission_dialog") or self.permission_dialog == None: + permission_dialog_text = "[b]Missing Permissions[/b]\n\nOn this version of Android, location permission is required to scan for Bluetooth devices. Yes, this is silly, but there's no way around it.\n\nIf you don't want Sideband to have location access, you can disable this permission after scanning and pairing your RNode, and everything will still work, as it is only the scanning process that requires this." + yes_button = MDRectangleFlatButton(text="Grant Permission",font_size=dp(18), theme_text_color="Custom", line_color=self.color_accept, text_color=self.color_accept) + no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) + self.permission_dialog = MDDialog(text=permission_dialog_text, buttons=[ no_button, yes_button ]) + def dl_no(s): self.permission_dialog.dismiss() + def dl_yes(s): + self.permission_dialog.dismiss() + def cb(dt): self.request_location_permissions() + Clock.schedule_once(cb, 0.15) + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + self.permission_dialog.open() + else: - RNS.log("Starting bluetooth scan", RNS.LOG_DEBUG) - self.discovered_bt_devices = {} + self.check_bluetooth_permissions() + if not self.sideband.getpersistent("permissions.bluetooth"): self.request_bluetooth_permissions() + else: + if self.root.ids.screen_manager.has_screen("hardware_rnode_screen") and hasattr(self, "hardware_rnode_screen") and self.hardware_rnode_screen != None: + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Scanning..." - BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') - self.bt_found_action = BluetoothDevice.ACTION_FOUND - self.broadcast_receiver = BroadcastReceiver(self.on_broadcast, actions=[self.bt_found_action]) - self.broadcast_receiver.start() + toast("Starting Bluetooth scan...") + RNS.log("Starting bluetooth scan", RNS.LOG_DEBUG) + self.discovered_bt_devices = {} + threading.Thread(target=self.hardware_rnode_scan_job, daemon=True).start() - self.bt_adapter = BluetoothAdapter.getDefaultAdapter() - self.bluetooth_update_bonded_devices() - self.bt_adapter.startDiscovery() + BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') + self.bt_found_action = BluetoothDevice.ACTION_FOUND + self.broadcast_receiver = BroadcastReceiver(self.on_broadcast, actions=[self.bt_found_action]) + self.broadcast_receiver.start() + + self.bt_adapter = BluetoothAdapter.getDefaultAdapter() + self.bluetooth_update_bonded_devices() + self.bt_adapter.startDiscovery() def stop_bluetooth_scan(self): RNS.log("Stopping bluetooth scan", RNS.LOG_DEBUG) @@ -1238,25 +1270,30 @@ class SidebandApp(MDApp): self.bt_adapter.cancelDiscovery() def on_broadcast(self, context, intent): - BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') - action = intent.getAction() - extras = intent.getExtras() + try: + BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') + action = intent.getAction() + extras = intent.getExtras() - if str(action) == "android.bluetooth.device.action.FOUND": - if extras: - try: - if android_api_version < 33: device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE") - else: device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE", BluetoothDevice) - dev_name = device.getName() - dev_addr = device.getAddress() - if dev_name.startswith("RNode "): - dev_rssi = extras.getShort("android.bluetooth.device.extra.RSSI", -9999) - discovered_device = {"name": dev_name, "address": dev_addr, "rssi": dev_rssi, "discovered": time.time()} - self.discovered_bt_devices[dev_addr] = discovered_device - RNS.log(f"Discovered RNode: {discovered_device}", RNS.LOG_DEBUG) - - except Exception as e: - RNS.log(f"Error while mapping discovered device: {e}", RNS.LOG_ERROR) + if str(action) == "android.bluetooth.device.action.FOUND": + if extras: + try: + if android_api_version < 33: device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE") + else: device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE", BluetoothDevice) + dev_name = device.getName() + dev_addr = device.getAddress() + if dev_name.startswith("RNode "): + dev_rssi = extras.getShort("android.bluetooth.device.extra.RSSI", -9999) + discovered_device = {"name": dev_name, "address": dev_addr, "rssi": dev_rssi, "discovered": time.time()} + self.discovered_bt_devices[dev_addr] = discovered_device + RNS.log(f"Discovered RNode: {discovered_device}", RNS.LOG_DEBUG) + + except Exception as e: + RNS.log(f"Error while mapping discovered device: {e}", RNS.LOG_ERROR) + + except Exception as e: + RNS.log(f"An error occurred while receiving Android broadcast intent: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) def on_new_intent(self, intent): intent_action = intent.getAction() @@ -2551,7 +2588,7 @@ class SidebandApp(MDApp): def a_rec_action(sender): if not self.rec_dialog.recording: self.sideband.ui_started_recording() - RNS.log("Starting recording...") # TODO: Remove + # RNS.log("Starting recording...") # TODO: Remove self.rec_dialog.recording = True el = self.rec_dialog.rec_item.children[0].children[0] el.ttc = el.theme_text_color; el.tc = el.text_color @@ -2565,7 +2602,7 @@ class SidebandApp(MDApp): else: self.sideband.ui_stopped_recording() - RNS.log("Stopping recording...") # TODO: Remove + # RNS.log("Stopping recording...") # TODO: Remove self.rec_dialog.recording = False self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Start Recording[/size]" el = self.rec_dialog.rec_item.children[0].children[0] @@ -4545,8 +4582,11 @@ class SidebandApp(MDApp): def add_job(dt): pair_addr = add_device["address"] btn_text = "Pair "+add_device["name"] - def run_pair(sender): self.hardware_rnode_pair_device_action(pair_addr) - # device_button = MDRectangleFlatButton(text=btn_text,font_size=dp(16)) + def run_pair(sender): + self.hardware_rnode_pair_device_action(pair_addr) + def job(): self.hardware_rnode_pair_check_job(pair_addr, add_device["name"]) + threading.Thread(target=job, daemon=True).start() + device_button = MDRectangleFlatButton(text=btn_text, font_size=dp(16), padding=[dp(0), dp(14), dp(0), dp(14)], size_hint=[1.0, None]) device_button.bind(on_release=run_pair) self.hardware_rnode_screen.ids.rnode_scan_results.add_widget(device_button) @@ -4565,6 +4605,17 @@ class SidebandApp(MDApp): def job(dt): toast("No unpaired RNodes discovered") Clock.schedule_once(job, 0.2) + def hardware_rnode_pair_check_job(self, pair_addr, device_name): + timeout = time.time()+45 + pairing_confirmed = False + while not pairing_confirmed and time.time() < timeout: + time.sleep(2) + self.bluetooth_update_bonded_devices() + if pair_addr in self.bt_bonded_devices: + pairing_confirmed = True + RNS.log(f"Pairing with {device_name} ({pair_addr}) successful", RNS.LOG_NOTICE) + toast(f"Paired with {device_name}") + def hardware_rnode_pair_device_action(self, pair_addr): RNS.log(f"Pair action for {pair_addr}", RNS.LOG_DEBUG) self.stop_bluetooth_scan() @@ -4578,14 +4629,11 @@ class SidebandApp(MDApp): def hardware_rnode_bt_scan_action(self, sender=None): self.discovered_bt_devices = {} - self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Scanning..." rw = [] for child in self.hardware_rnode_screen.ids.rnode_scan_results.children: rw.append(child) for w in rw: self.hardware_rnode_screen.ids.rnode_scan_results.remove_widget(w) Clock.schedule_once(self.bluetooth_scan_action, 0.5) - threading.Thread(target=self.hardware_rnode_scan_job, daemon=True).start() def hardware_rnode_bt_on_action(self, sender=None): self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 07557da..e457b64 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -2646,7 +2646,7 @@ MDScreen: MDLabel: id: hardware_rnode_info markup: True - text: "You must first pair the RNode with your device for this to work. To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode.You can then pair the device using the Bluetooth settings of your device, or by pressing the pairing button below. The in-app scanning and pairing is supported on Android 12+. If it doesn't work, use the Bluetooth settings of your device to scan and pair.\\n" + text: "You must first pair the RNode with your device for this to work. To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode.You can then pair the device using the Bluetooth settings of your device, or by pressing the pairing button below. On older Android versions, the in-app scanning and pairing may not work. In this case, use the Bluetooth settings of your device to scan and pair.\\n" size_hint_y: None text_size: self.width, None height: self.texture_size[1] From 5d7a83a39cac5718214ec5999344c56bee8c99aa Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 8 Nov 2025 20:10:26 +0100 Subject: [PATCH 154/271] Fixed regression in service RPC signature. Added service RPC connection re-init if connection drops unexpectedly. --- sbapp/sideband/core.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 76627c0..59cb1da 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1854,6 +1854,7 @@ class SidebandCore(): except Exception as e: if not type(e) == ConnectionRefusedError: + self.rpc_connection = None RNS.log(f"An error occurred while executing the service RPC request: {request}", RNS.LOG_ERROR) RNS.log(f"The contained exception was: {e}", RNS.LOG_ERROR) @@ -2132,7 +2133,7 @@ class SidebandCore(): elif "get_lxm_stamp_cost" in call: connection.send(self.get_lxm_stamp_cost(call["get_lxm_stamp_cost"]["lxm_hash"])) elif "get_lxm_propagation_cost" in call: connection.send(self.get_lxm_propagation_cost(call["get_lxm_propagation_cost"]["lxm_hash"])) elif "is_tracking" in call: connection.send(self.is_tracking(call["is_tracking"])) - elif "start_tracking" in call: connection.send(self.start_tracking(object_addr=call["start_tracking"]["object_addr"], interval=args["interval"], duration=args["duration"])) + elif "start_tracking" in call: connection.send(self.start_tracking(object_addr=call["start_tracking"]["object_addr"], interval=call["start_tracking"]["interval"], duration=call["start_tracking"]["duration"])) elif "stop_tracking" in call: connection.send(self.stop_tracking(object_addr=call["stop_tracking"]["object_addr"])) elif "get_service_log" in call: connection.send(self.get_service_log()) elif "start_voice" in call: connection.send(self.start_voice()) From 09400ec863b3a81c1b32ee0efd118d49839b2c48 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Nov 2025 11:36:45 +0100 Subject: [PATCH 155/271] Cache Android activity launch intent dropped by Kivy and retrieve for handling after UI init --- sbapp/main.py | 159 +++++++++++++++++------------- sbapp/patches/PythonActivity.java | 5 + 2 files changed, 95 insertions(+), 69 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e8b0432..b58ef11 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -679,6 +679,25 @@ class SidebandApp(MDApp): return True + def check_launch_intent(self): + try: + if RNS.vendor.platformutils.is_android(): + # Check for pending start intent + if not hasattr(mActivity, "startIntent"): RNS.log("Could not access pending intent from Android activity", RNS.LOG_ERROR) + else: + try: + pending_intent = mActivity.startIntent + RNS.log(f"Passing intent {pending_intent} to intent handler...", RNS.LOG_DEBUG) + self.on_new_intent(pending_intent) + + except Exception as e: + RNS.log("An error occurred while getting pending intent on activity launch: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + except Exception as e: + RNS.log(f"An error occurred while checking Android launch intent: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + def start_final(self): # Start local core instance self.sideband.start() @@ -753,7 +772,10 @@ class SidebandApp(MDApp): self.hw_error_dialog.open() self.hw_error_dialog.is_open = True + def check_intent(dt): self.check_launch_intent() + Clock.schedule_once(check_errors, 1.5) + Clock.schedule_once(check_intent, 0.1) ################################################# @@ -1296,84 +1318,86 @@ class SidebandApp(MDApp): RNS.trace_exception(e) def on_new_intent(self, intent): - intent_action = intent.getAction() - action = None - data = None + try: + intent_action = intent.getAction() + action = None + data = None - RNS.log(f"Received intent: {intent_action}", RNS.LOG_DEBUG) + RNS.log(f"Received intent: {intent_action}", RNS.LOG_DEBUG) - if intent_action == "android.intent.action.MAIN": - JString = autoclass('java.lang.String') - Intent = autoclass("android.content.Intent") - try: - extras = intent.getExtras() - if extras: - data = extras.getString("intent_action", "undefined") - if data.startswith("conversation."): - conv_hexhash = bytes.fromhex(data.replace("conversation.", "")) - def cb(dt): self.open_conversation(conv_hexhash) - Clock.schedule_once(cb, 0.2) - - elif data.startswith("incoming_call"): - def cb(dt): self.voice_action() - Clock.schedule_once(cb, 0.2) - - except Exception as e: - RNS.log(f"Error while getting intent action data: {e}", RNS.LOG_ERROR) - RNS.trace_exception(e) - - if intent_action == "android.intent.action.WEB_SEARCH": - SearchManager = autoclass('android.app.SearchManager') - data = intent.getStringExtra(SearchManager.QUERY) - - if data.lower().startswith(LXMF.LXMessage.URI_SCHEMA): - action = "lxm_uri" - - if intent_action == "android.intent.action.VIEW": - data = intent.getData().toString() - if data.lower().startswith(LXMF.LXMessage.URI_SCHEMA): - action = "lxm_uri" - - if intent_action == "android.intent.action.SEND": - try: + if intent_action == "android.intent.action.MAIN": + JString = autoclass('java.lang.String') Intent = autoclass("android.content.Intent") - extras = intent.getExtras() - target = extras.get(Intent.EXTRA_STREAM) - mime_types = extras.get(Intent.EXTRA_MIME_TYPES) - target_uri = target.toString() - target_path = target.getPath() - target_filename = target.getLastPathSegment() + try: + extras = intent.getExtras() + if extras: + data = extras.getString("intent_action", "undefined") + if data.startswith("conversation."): + conv_hexhash = bytes.fromhex(data.replace("conversation.", "")) + def cb(dt): self.open_conversation(conv_hexhash) + Clock.schedule_once(cb, 0.2) - RNS.log(f"Received share intent: {target_uri} / {target_path} / {target_filename}", RNS.LOG_DEBUG) - for cf in os.listdir(self.sideband.share_cache): - rt = os.path.join(self.sideband.share_cache, cf) - os.unlink(rt) - RNS.log("Removed previously cached data: "+str(rt), RNS.LOG_DEBUG) + elif data.startswith("incoming_call"): + def cb(dt): self.voice_action() + Clock.schedule_once(cb, 0.2) - ContentResolver = autoclass("android.content.ContentResolver") - cr = mActivity.getContentResolver() - cache_path = os.path.join(self.sideband.share_cache, target_filename) - input_stream = cr.openInputStream(target) - with open(cache_path, "wb") as cache_file: - cache_file.write(bytes(input_stream.readAllBytes())) - RNS.log("Cached shared data from Android intent", RNS.LOG_DEBUG) + except Exception as e: + RNS.log(f"Error while getting intent action data: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) - action = "shared_data" - data = {"filename": target_filename, "data_path": cache_path} + if intent_action == "android.intent.action.WEB_SEARCH": + SearchManager = autoclass('android.app.SearchManager') + data = intent.getStringExtra(SearchManager.QUERY) + + if data.lower().startswith(LXMF.LXMessage.URI_SCHEMA): action = "lxm_uri" - except Exception as e: - RNS.log(f"Error while getting intent action data: {e}", RNS.LOG_ERROR) - RNS.trace_exception(e) + if intent_action == "android.intent.action.VIEW": + data = intent.getData().toString() + if data.lower().startswith(LXMF.LXMessage.URI_SCHEMA): action = "lxm_uri" - if action != None: - self.handle_action(action, data) + if intent_action == "android.intent.action.SEND": + try: + Intent = autoclass("android.content.Intent") + extras = intent.getExtras() + target = extras.get(Intent.EXTRA_STREAM) + mime_types = extras.get(Intent.EXTRA_MIME_TYPES) + target_uri = target.toString() + target_path = target.getPath() + target_filename = target.getLastPathSegment() + + RNS.log(f"Received share intent: {target_uri} / {target_path} / {target_filename}", RNS.LOG_DEBUG) + for cf in os.listdir(self.sideband.share_cache): + rt = os.path.join(self.sideband.share_cache, cf) + os.unlink(rt) + RNS.log("Removed previously cached data: "+str(rt), RNS.LOG_DEBUG) + + ContentResolver = autoclass("android.content.ContentResolver") + cr = mActivity.getContentResolver() + cache_path = os.path.join(self.sideband.share_cache, target_filename) + input_stream = cr.openInputStream(target) + with open(cache_path, "wb") as cache_file: + cache_file.write(bytes(input_stream.readAllBytes())) + RNS.log("Cached shared data from Android intent", RNS.LOG_DEBUG) + + action = "shared_data" + data = {"filename": target_filename, "data_path": cache_path} + + except Exception as e: + RNS.log(f"Error while getting intent action data: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + if action != None: self.handle_action(action, data) + + except Exception as e: + RNS.log(f"Error while handling received intent: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) def handle_action(self, action, data): if action == "lxm_uri": self.ingest_lxm_uri(data) if action == "shared_data": - RNS.log("Got shared data: "+str(data)) + RNS.log("Got shared data from Android intent", RNS.LOG_DEBUG) def cb(dt): try: self.shared_attachment_action(data) @@ -1608,10 +1632,8 @@ class SidebandApp(MDApp): patch_sdl_window_events(Window) - if __variant__ != "": - variant_str = " "+__variant__ - else: - variant_str = "" + if __variant__ != "": variant_str = " "+__variant__ + else: variant_str = "" self.root.ids.screen_manager.app = self self.root.ids.app_version_info.text = "Sideband v"+__version__+variant_str @@ -2056,7 +2078,6 @@ class SidebandApp(MDApp): self.update_message_widgets() self.messages_view.ids.message_text.disabled = False - self.root.ids.screen_manager.current = "messages_screen" self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) diff --git a/sbapp/patches/PythonActivity.java b/sbapp/patches/PythonActivity.java index fc58960..649a302 100644 --- a/sbapp/patches/PythonActivity.java +++ b/sbapp/patches/PythonActivity.java @@ -50,6 +50,8 @@ public class PythonActivity extends SDLActivity { private Bundle mMetaData = null; private PowerManager.WakeLock mWakeLock = null; + public Intent startIntent = null; + public String getAppRoot() { String app_root = getFilesDir().getAbsolutePath() + "/app"; return app_root; @@ -57,6 +59,9 @@ public class PythonActivity extends SDLActivity { @Override protected void onCreate(Bundle savedInstanceState) { + try { this.startIntent = getIntent(); } + catch { Log.e(TAG, "Failed to get pending intent on activity create"); } + Log.v(TAG, "PythonActivity onCreate running"); resourceManager = new ResourceManager(this); From 8121de96d760c376582728fd547705ec14465f55 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Nov 2025 13:58:40 +0100 Subject: [PATCH 156/271] Added simple call log to voice call screen --- sbapp/patches/PythonActivity.java | 2 +- sbapp/sideband/core.py | 41 +++--- sbapp/sideband/voice.py | 74 ++++++++++- sbapp/ui/helpers.py | 1 + sbapp/ui/voice.py | 203 ++++++++++++++++++++++++------ 5 files changed, 264 insertions(+), 57 deletions(-) diff --git a/sbapp/patches/PythonActivity.java b/sbapp/patches/PythonActivity.java index 649a302..41b9460 100644 --- a/sbapp/patches/PythonActivity.java +++ b/sbapp/patches/PythonActivity.java @@ -60,7 +60,7 @@ public class PythonActivity extends SDLActivity { @Override protected void onCreate(Bundle savedInstanceState) { try { this.startIntent = getIntent(); } - catch { Log.e(TAG, "Failed to get pending intent on activity create"); } + catch (Exception e) { Log.e(TAG, "Failed to get pending intent on activity create"); } Log.v(TAG, "PythonActivity onCreate running"); resourceManager = new ResourceManager(this); diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 59cb1da..38d7feb 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2138,20 +2138,21 @@ class SidebandCore(): elif "get_service_log" in call: connection.send(self.get_service_log()) elif "start_voice" in call: connection.send(self.start_voice()) elif "stop_voice" in call: connection.send(self.stop_voice()) - elif "telephone_is_available" in call: connection.send(self.telephone.is_available) if self.telephone else False - elif "telephone_is_in_call" in call: connection.send(self.telephone.is_in_call) if self.telephone else False - elif "telephone_call_is_connecting" in call: connection.send(self.telephone.call_is_connecting) if self.telephone else False - elif "telephone_is_ringing" in call: connection.send(self.telephone.is_ringing) if self.telephone else False - elif "telephone_caller_info" in call: connection.send(self.telephone.caller.hash) if self.telephone and self.telephone.caller else None - elif "telephone_set_busy" in call: connection.send(self.telephone.set_busy(call["telephone_set_busy"])) if self.telephone else False - elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"])) if self.telephone else False - elif "telephone_hangup" in call: connection.send(self.telephone.hangup()) if self.telephone else False - elif "telephone_answer" in call: connection.send(self.telephone.answer()) if self.telephone else False - elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"])) if self.telephone else False - elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"])) if self.telephone else False - elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"])) if self.telephone else False - elif "telephone_set_low_latency_output" in call: connection.send(self.telephone.set_low_latency_output(call["telephone_set_low_latency_output"])) if self.telephone else False - elif "telephone_announce" in call: connection.send(self.telephone.announce()) if self.telephone else False + elif "telephone_is_available" in call: connection.send(self.telephone.is_available if self.telephone else False) + elif "telephone_is_in_call" in call: connection.send(self.telephone.is_in_call if self.telephone else False) + elif "telephone_call_is_connecting" in call: connection.send(self.telephone.call_is_connecting if self.telephone else False) + elif "telephone_is_ringing" in call: connection.send(self.telephone.is_ringing if self.telephone else False) + elif "telephone_caller_info" in call: connection.send(self.telephone.caller.hash if self.telephone and self.telephone.caller else None) + elif "telephone_set_busy" in call: connection.send(self.telephone.set_busy(call["telephone_set_busy"]) if self.telephone else False) + elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"]) if self.telephone else False) + elif "telephone_hangup" in call: connection.send(self.telephone.hangup() if self.telephone else False) + elif "telephone_answer" in call: connection.send(self.telephone.answer() if self.telephone else False) + elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"]) if self.telephone else False) + elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"]) if self.telephone else False) + elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"]) if self.telephone else False) + elif "telephone_set_low_latency_output" in call: connection.send(self.telephone.set_low_latency_output(call["telephone_set_low_latency_output"]) if self.telephone else False) + elif "telephone_announce" in call: connection.send(self.telephone.announce() if self.telephone else False) + elif "telephone_get_call_log" in call: connection.send(self.telephone.get_call_log() if self.telephone else []) else: connection.send(None) @@ -5518,9 +5519,10 @@ class SidebandCore(): RNS.log("Starting voice service", RNS.LOG_DEBUG) self.voice_running = True self.setstate("voice.running", self.voice_running) - from .voice import ReticulumTelephone - self.telephone = ReticulumTelephone(self.identity, owner=self, speaker=self.config["voice_output"], microphone=self.config["voice_input"], ringer=self.config["voice_ringer"]) ringtone_path = os.path.join(self.asset_dir, "audio", "notifications", "soft1.opus") + call_log_path = os.path.join(self.app_dir, "app_storage", "lxst_call_log") + from .voice import ReticulumTelephone + self.telephone = ReticulumTelephone(self.identity, owner=self, speaker=self.config["voice_output"], microphone=self.config["voice_input"], ringer=self.config["voice_ringer"], logpath=call_log_path) self.telephone.set_ringtone(ringtone_path) self.telephone.set_low_latency_output(self.config["voice_low_latency"]) return True @@ -5584,6 +5586,13 @@ class SidebandCore(): if self.gui_foreground(): RNS.log("Squelching call notification since GUI is in foreground", RNS.LOG_DEBUG) else: self.notify(title="Incoming voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") + def missed_call(self, remote_identity): + display_name = self.voice_display_name(remote_identity.hash) + self.setstate("voice.incoming_call", display_name) + # if self.gui_foreground(): RNS.log("Squelching call notification since GUI is in foreground", RNS.LOG_DEBUG) + # else: self.notify(title="Missed voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") + self.notify(title="Missed voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") + rns_config = """# This template is used to generate a # running configuration for Sideband's # internal RNS instance. Incorrect changes diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 72ad879..f40f135 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -6,6 +6,7 @@ import time from LXST._version import __version__ from LXST.Primitives.Telephony import Telephone from RNS.vendor.configobj import ConfigObj +import RNS.vendor.umsgpack as msgpack class ReticulumTelephone(): STATE_AVAILABLE = 0x00 @@ -22,7 +23,9 @@ class ReticulumTelephone(): WAIT_TIME = 60 PATH_TIME = 10 - def __init__(self, identity, owner = None, service = False, speaker=None, microphone=None, ringer=None): + CALL_LOG_KEEP = 30*24*60*60 + + def __init__(self, identity, owner = None, service = False, speaker=None, microphone=None, ringer=None, logpath=None): self.identity = identity self.service = service self.owner = owner @@ -40,6 +43,8 @@ class ReticulumTelephone(): self.speaker_device = speaker self.microphone_device = microphone self.ringer_device = ringer + self.logpath = logpath + self.call_log = None self.phonebook = {} self.aliases = {} self.names = {} @@ -113,6 +118,54 @@ class ReticulumTelephone(): def set_busy(self, busy): self.telephone.set_busy(busy) def set_low_latency_output(self, enabled): self.telephone.set_low_latency_output(enabled) + def get_call_log(self): + if self.call_log: return self.call_log + else: + call_log = [] + try: + if os.path.isfile(self.logpath): + with open(self.logpath, "rb") as logfile: + read_call_log = msgpack.unpackb(logfile.read()) + + for entry in read_call_log: + age = time.time()-entry["time"] + if age < self.CALL_LOG_KEEP: call_log.append(entry) + + except Exception as e: RNS.log(f"Could not read call log file: {e}", RNS.LOG_ERROR) + self.call_log = call_log + return self.call_log + + def log_call(self, event, identity): + RNS.log(f"Logging call event {event} for {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) + if self.logpath: + try: + if not os.path.isfile(self.logpath): + try: + with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb([])) + except Exception as e: raise OSError("Could not create call log file") + + call_log = [] + read_call_log = [] + try: + with open(self.logpath, "rb") as logfile: read_call_log = msgpack.unpackb(logfile.read()) + except Exception as e: + RNS.log(f"Error while reading call log file: {e}", RNS.LOG_ERROR) + RNS.log(f"Call log file will be re-created", RNS.LOG_ERROR) + + for entry in read_call_log: + age = time.time()-entry["time"] + if age < self.CALL_LOG_KEEP: call_log.append(entry) + + entry = {"time": time.time(), "event": event, "identity": identity.hash} + call_log.append(entry) + + with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb(call_log)) + self.call_log = call_log + + except Exception as e: + RNS.log(f"An error occurred while updating call log: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + def dial(self, identity_hash): self.last_dialled_identity_hash = identity_hash destination_hash = RNS.Destination.hash_from_name_and_identity("lxst.telephony", identity_hash) @@ -145,6 +198,10 @@ class ReticulumTelephone(): self.owner.incoming_call(remote_identity) def call_ended(self, remote_identity): + call_was_connecting = self.call_is_connecting + was_ringing = self.is_ringing + was_in_call = self.is_in_call + if self.is_in_call or self.is_ringing or self.call_is_connecting: if self.is_in_call: RNS.log(f"Call with {RNS.prettyhexrep(self.caller.hash)} ended\n", RNS.LOG_DEBUG) if self.is_ringing: RNS.log(f"Call {self.direction} {RNS.prettyhexrep(self.caller.hash)} was not answered\n", RNS.LOG_DEBUG) @@ -152,11 +209,23 @@ class ReticulumTelephone(): self.direction = None self.state = self.STATE_AVAILABLE + if call_was_connecting: self.log_call("outgoing-failure", remote_identity) + elif was_in_call: self.log_call("ongoing-ended", remote_identity) + elif was_ringing: + self.log_call("incoming-missed", remote_identity) + self.owner.missed_call(remote_identity) + def call_established(self, remote_identity): + call_was_connecting = self.call_is_connecting + was_ringing = self.is_ringing + if self.call_is_connecting or self.is_ringing: self.state = self.STATE_IN_CALL RNS.log(f"Call established with {RNS.prettyhexrep(self.caller.hash)}", RNS.LOG_DEBUG) + if call_was_connecting: self.log_call("outgoing-success", remote_identity) + elif was_ringing: self.log_call("incoming-success", remote_identity) + def __is_allowed(self, identity_hash): if self.owner.config["voice_trusted_only"]: return self.owner.voice_is_trusted(identity_hash) @@ -202,4 +271,5 @@ class ReticulumTelephoneProxy(): def set_microphone(self, microphone): return self.owner.service_rpc_request({"telephone_set_microphone": microphone }) def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) def set_low_latency_output(self, enabled): return self.owner.service_rpc_request({"telephone_set_low_latency_output": enabled}) - def announce(self): return self.owner.service_rpc_request({"telephone_announce": True}) \ No newline at end of file + def announce(self): return self.owner.service_rpc_request({"telephone_announce": True}) + def get_call_log(self): return self.owner.service_rpc_request({"telephone_get_call_log": True}) \ No newline at end of file diff --git a/sbapp/ui/helpers.py b/sbapp/ui/helpers.py index 5b43278..d8c0aaa 100644 --- a/sbapp/ui/helpers.py +++ b/sbapp/ui/helpers.py @@ -6,6 +6,7 @@ from kivymd.uix.list import OneLineIconListItem, MDList, IconLeftWidget, IconRig from kivy.properties import StringProperty import re +ts_format_date = "%Y-%m-%d" ts_format = "%Y-%m-%d %H:%M:%S" file_ts_format = "%Y_%m_%d_%H_%M_%S" diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index b0f8e9a..ff604bc 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -12,6 +12,8 @@ from kivymd.uix.pickers import MDColorPicker from kivymd.uix.button import MDRectangleFlatButton from kivymd.uix.button import MDRectangleFlatIconButton from kivymd.uix.dialog import MDDialog +from kivy.properties import StringProperty, BooleanProperty, OptionProperty, ColorProperty, Property +from kivymd.uix.list import MDList, IconLeftWidget, IconRightWidget, OneLineAvatarIconListItem from kivymd.icon_definitions import md_icons from kivymd.toast import toast from kivy.properties import StringProperty, BooleanProperty @@ -22,10 +24,16 @@ import threading from datetime import datetime if RNS.vendor.platformutils.get_platform() == "android": - from ui.helpers import ts_format + from ui.helpers import ts_format_date from android.permissions import request_permissions, check_permission else: - from .helpers import ts_format + from .helpers import ts_format_date + +from kivy.utils import escape_markup +if RNS.vendor.platformutils.get_platform() == "android": + from ui.helpers import multilingual_markup +else: + from .helpers import multilingual_markup class Voice(): def __init__(self, app): @@ -37,6 +45,9 @@ class Voice(): self.path_requesting = None self.output_devices = [] self.input_devices = [] + self.log_list = None + self.last_log_update = 0 + self.log_name_cache = {} self.listed_output_devices = [] self.listed_input_devices = [] self.listed_ringer_devices = [] @@ -46,9 +57,8 @@ class Voice(): self.screen.app = self.app self.screen.delegate = self self.app.root.ids.screen_manager.add_widget(self.screen) + self.update_call_log() - self.screen.ids.voice_scrollview.effect_cls = ScrollEffect - def update_call_status(self, dt=None): if self.app.root.ids.screen_manager.current == "voice_screen": if self.ui_updater == None: self.ui_updater = Clock.schedule_interval(self.update_call_status, 0.5) @@ -89,6 +99,8 @@ class Voice(): db.disabled = True; db.text = "Voice calls disabled" ih.disabled = True + if time.time() > self.last_log_update+3: self.update_call_log() + def target_valid(self): if self.app.sideband.voice_running: db = self.screen.ids.dial_button @@ -170,7 +182,7 @@ class Voice(): self.update_call_status() - ### settings screen + ### Settings screen ###################################### def settings_action(self, sender=None): @@ -297,6 +309,116 @@ class Voice(): self.app.sideband.telephone.set_ringer(self.app.sideband.config["voice_ringer"]) + ### Call log + ###################################### + + def update_call_log(self): + if self.log_list == None: + self.log_list = CallList() + self.screen.ids.log_list_container.add_widget(self.log_list) + + self.update_log_list() + self.last_log_update = time.time() + + def update_log_list(self): + call_log = self.app.sideband.telephone.get_call_log() + call_log.sort(key=lambda e: e["time"], reverse=True) + data = [] + for entry in call_log: + try: + at = entry["time"] + td = int(time.time())-int(at) + evt = entry["event"] + idnt = entry["identity"] + + if not idnt in self.log_name_cache: self.log_name_cache[idnt] = self.app.sideband.voice_display_name(idnt) + name = multilingual_markup(escape_markup(str(self.log_name_cache[idnt])).encode("utf-8")).decode("utf-8") + + icon = None + if evt == "incoming-missed": icon = "phone-missed" + elif evt == "outgoing-failure": icon = "phone-cancel" + elif evt == "incoming-success": icon = "phone-incoming" + elif evt == "outgoing-success": icon = "phone-outgoing" + + time_str = None + if td < 60: time_str = "Just now" + elif td < 60*60: td = int((td//60)*60) + elif td < 60*60*24: td = int((td//60)*60) + elif td < 60*60*24*7: td = int((td//(60*60*24))*(60*60*24)) + else: time_str = time.strftime(ts_format_date, time.localtime(at)) + + if time_str == None: time_str = f"{RNS.prettytime(td)} ago" + + if icon: + info = f"{name} • [i]{time_str}[/i]" + entry = {"icon": icon, "text": f"{info}"} + data.append(entry) + + except Exception as e: + RNS.log(f"An error occurred while updating the call log list: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + self.log_list.data = data + +class LogEntry(OneLineAvatarIconListItem): + app = None + owner_screen = None + conversation_dropdown = None + voice_dropdown = None + clear_dialog = None + clear_telemetry_dialog = None + delete_dialog = None + + icon = StringProperty() + # ti_color = OptionProperty(None, options=theme_text_color_options) + # icon_fg = Property(None, allownone=True) + # icon_bg = Property(None, allownone=True) + + def __init__(self): + super().__init__() + # self.bind(on_release=self.app.conversation_action) + # self.ids.left_icon.bind(on_release=self.left_icon_action) + # self.ids.right_icon.bind(on_release=self.right_icon_action) + + def left_icon_action(self, sender): + pass + + def right_icon_action(self, sender): + pass + +class CallList(MDRecycleView): + def __init__(self): + super().__init__() + self.data = [] + +Builder.load_string(""" + + IconLeftWidget: + id: left_icon + # theme_icon_color: root.ti_color + # icon_color: root.icon_fg + # md_bg_color: root.icon_bg + icon: root.icon + _default_icon_pad: dp(14) + icon_size: dp(24) + + # IconRightWidget: + # id: right_icon + # icon: "dots-vertical" + +: + id: calls_scrollview + viewclass: "LogEntry" + effect_cls: "ScrollEffect" + + RecycleBoxLayout: + default_size: None, dp(57) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height + orientation: "vertical" +""") + layout_voice_screen = """ MDScreen: name: "voice_screen" @@ -316,48 +438,53 @@ MDScreen: ['close', lambda x: root.app.close_any_action(self)], ] - ScrollView: - id: voice_scrollview + MDBoxLayout: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(32), dp(28), dp(16)] MDBoxLayout: orientation: "vertical" + # spacing: "24dp" size_hint_y: None height: self.minimum_height - padding: [dp(28), dp(32), dp(28), dp(16)] + padding: [dp(0), dp(12), dp(0), dp(0)] - MDBoxLayout: - orientation: "vertical" - # spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(12), dp(0), dp(0)] + MDTextField: + id: identity_hash + hint_text: "Identity hash" + mode: "rectangle" + # size_hint: [1.0, None] + pos_hint: {"center_x": .5} + max_text_length: 32 + on_text: root.delegate.target_input_action(self) - MDTextField: - id: identity_hash - hint_text: "Identity hash" - mode: "rectangle" - # size_hint: [1.0, None] - pos_hint: {"center_x": .5} - max_text_length: 32 - on_text: root.delegate.target_input_action(self) + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(35)] - MDBoxLayout: - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(35), dp(0), dp(35)] + MDRectangleFlatIconButton: + id: dial_button + icon: "phone-outgoing" + text: "Call" + 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.dial_action(self) + disabled: True - MDRectangleFlatIconButton: - id: dial_button - icon: "phone-outgoing" - text: "Call" - 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.dial_action(self) - disabled: True + MDSeparator: + orientation: "horizontal" + height: dp(1) + + MDBoxLayout: + orientation: "vertical" + id: log_list_container """ layout_voice_settings_screen = """ From 4b2e2bacd5304deb8bce3f25a2b34203c32eb819 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Nov 2025 14:12:56 +0100 Subject: [PATCH 157/271] Added ability to dial from call log --- sbapp/ui/voice.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index ff604bc..30b011f 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -158,6 +158,12 @@ class Voice(): def _path_request_failed(self, dt): toast("Path request timed out") + def log_dial_action(self, sender=None): + if sender: + self.screen.ids.identity_hash.text = RNS.hexrep(sender.identity, delimit=False) + self.dial_target = sender.identity + self.dial_action() + def dial_action(self, sender=None): if self.app.sideband.voice_running: if self.app.sideband.telephone.is_available: @@ -321,6 +327,7 @@ class Voice(): self.last_log_update = time.time() def update_log_list(self): + LogEntry.owner = self call_log = self.app.sideband.telephone.get_call_log() call_log.sort(key=lambda e: e["time"], reverse=True) data = [] @@ -336,7 +343,7 @@ class Voice(): icon = None if evt == "incoming-missed": icon = "phone-missed" - elif evt == "outgoing-failure": icon = "phone-cancel" + elif evt == "outgoing-failure": icon = "phone-remove" elif evt == "incoming-success": icon = "phone-incoming" elif evt == "outgoing-success": icon = "phone-outgoing" @@ -351,7 +358,7 @@ class Voice(): if icon: info = f"{name} • [i]{time_str}[/i]" - entry = {"icon": icon, "text": f"{info}"} + entry = {"icon": icon, "text": f"{info}", "identity": idnt} data.append(entry) except Exception as e: @@ -361,13 +368,7 @@ class Voice(): self.log_list.data = data class LogEntry(OneLineAvatarIconListItem): - app = None - owner_screen = None - conversation_dropdown = None - voice_dropdown = None - clear_dialog = None - clear_telemetry_dialog = None - delete_dialog = None + owner = None icon = StringProperty() # ti_color = OptionProperty(None, options=theme_text_color_options) @@ -376,10 +377,13 @@ class LogEntry(OneLineAvatarIconListItem): def __init__(self): super().__init__() - # self.bind(on_release=self.app.conversation_action) + self.bind(on_release=self.dial_action) # self.ids.left_icon.bind(on_release=self.left_icon_action) # self.ids.right_icon.bind(on_release=self.right_icon_action) + def dial_action(self, sender=None): + self.owner.log_dial_action(self) + def left_icon_action(self, sender): pass From 596bef2db4d947abba43aa40d7634aa24520c589 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Nov 2025 14:18:38 +0100 Subject: [PATCH 158/271] Added reject button to voice screen --- sbapp/ui/voice.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 30b011f..6535296 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -68,28 +68,34 @@ class Voice(): self.ui_updater = None db = self.screen.ids.dial_button + rb = self.screen.ids.reject_button ih = self.screen.ids.identity_hash if self.app.sideband.voice_running: telephone = self.app.sideband.telephone if self.path_requesting: db.disabled = True + rb.disabled = True ih.disabled = True else: if telephone.is_available: ih.disabled = False + rb.disabled = True self.target_input_action(ih) else: ih.disabled = True + rb.disabled = True if telephone.is_in_call or telephone.call_is_connecting: ih.disabled = True + rb.disabled = True db.disabled = False db.text = "Hang up" db.icon = "phone-hangup" elif telephone.is_ringing: ih.disabled = True + rb.disabled = False db.disabled = False db.text = "Answer" db.icon = "phone-ring" @@ -164,6 +170,11 @@ class Voice(): self.dial_target = sender.identity self.dial_action() + def reject_action(self, sender=None): + if self.app.sideband.voice_running: + if self.app.sideband.telephone.is_ringing: + self.app.sideband.telephone.hangup() + def dial_action(self, sender=None): if self.app.sideband.voice_running: if self.app.sideband.telephone.is_available: @@ -469,7 +480,7 @@ MDScreen: spacing: "24dp" size_hint_y: None height: self.minimum_height - padding: [dp(0), dp(35), dp(0), dp(35)] + padding: [dp(0), dp(35), dp(0), dp(14)] MDRectangleFlatIconButton: id: dial_button @@ -482,6 +493,17 @@ MDScreen: on_release: root.delegate.dial_action(self) disabled: True + MDRectangleFlatIconButton: + id: reject_button + icon: "phone-cancel" + text: "Reject" + 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.reject_action(self) + disabled: True + MDSeparator: orientation: "horizontal" height: dp(1) From 2bc80d293611ac11da8fa0f6ce03481acab204fb Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 9 Nov 2025 14:22:31 +0100 Subject: [PATCH 159/271] Only keep call log for 14 days --- sbapp/sideband/voice.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index f40f135..d271552 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -23,7 +23,7 @@ class ReticulumTelephone(): WAIT_TIME = 60 PATH_TIME = 10 - CALL_LOG_KEEP = 30*24*60*60 + CALL_LOG_KEEP = 14*24*60*60 def __init__(self, identity, owner = None, service = False, speaker=None, microphone=None, ringer=None, logpath=None): self.identity = identity From 04a09623a9bdb21445b61e2ea7ab1f9b9e0030f1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 10 Nov 2025 00:01:34 +0100 Subject: [PATCH 160/271] Fixed voice screen failing to load if voice calls were disabled --- sbapp/main.py | 2 ++ sbapp/ui/voice.py | 66 ++++++++++++++++++++++++----------------------- 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index b58ef11..088ccab 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -5841,6 +5841,8 @@ class SidebandApp(MDApp): self.voice_screen.screen.ids.identity_hash.text = RNS.hexrep(dial_on_complete, delimit=False) Clock.schedule_once(self.voice_screen.dial_action, 0.25) + if self.sideband.config["voice_enabled"] == True: self.request_microphone_permission() + def voice_action(self, sender=None, direction="left", dial_on_complete=None): if self.voice_ready: self.voice_open(direction=direction, dial_on_complete=dial_on_complete) diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 6535296..a71d948 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -338,45 +338,47 @@ class Voice(): self.last_log_update = time.time() def update_log_list(self): - LogEntry.owner = self - call_log = self.app.sideband.telephone.get_call_log() - call_log.sort(key=lambda e: e["time"], reverse=True) - data = [] - for entry in call_log: - try: - at = entry["time"] - td = int(time.time())-int(at) - evt = entry["event"] - idnt = entry["identity"] + if not self.app.sideband.telephone: self.log_list.data = [] + else: + LogEntry.owner = self + call_log = self.app.sideband.telephone.get_call_log() + call_log.sort(key=lambda e: e["time"], reverse=True) + data = [] + for entry in call_log: + try: + at = entry["time"] + td = int(time.time())-int(at) + evt = entry["event"] + idnt = entry["identity"] - if not idnt in self.log_name_cache: self.log_name_cache[idnt] = self.app.sideband.voice_display_name(idnt) - name = multilingual_markup(escape_markup(str(self.log_name_cache[idnt])).encode("utf-8")).decode("utf-8") + if not idnt in self.log_name_cache: self.log_name_cache[idnt] = self.app.sideband.voice_display_name(idnt) + name = multilingual_markup(escape_markup(str(self.log_name_cache[idnt])).encode("utf-8")).decode("utf-8") - icon = None - if evt == "incoming-missed": icon = "phone-missed" - elif evt == "outgoing-failure": icon = "phone-remove" - elif evt == "incoming-success": icon = "phone-incoming" - elif evt == "outgoing-success": icon = "phone-outgoing" + icon = None + if evt == "incoming-missed": icon = "phone-missed" + elif evt == "outgoing-failure": icon = "phone-remove" + elif evt == "incoming-success": icon = "phone-incoming" + elif evt == "outgoing-success": icon = "phone-outgoing" - time_str = None - if td < 60: time_str = "Just now" - elif td < 60*60: td = int((td//60)*60) - elif td < 60*60*24: td = int((td//60)*60) - elif td < 60*60*24*7: td = int((td//(60*60*24))*(60*60*24)) - else: time_str = time.strftime(ts_format_date, time.localtime(at)) + time_str = None + if td < 60: time_str = "Just now" + elif td < 60*60: td = int((td//60)*60) + elif td < 60*60*24: td = int((td//60)*60) + elif td < 60*60*24*7: td = int((td//(60*60*24))*(60*60*24)) + else: time_str = time.strftime(ts_format_date, time.localtime(at)) - if time_str == None: time_str = f"{RNS.prettytime(td)} ago" + if time_str == None: time_str = f"{RNS.prettytime(td)} ago" - if icon: - info = f"{name} • [i]{time_str}[/i]" - entry = {"icon": icon, "text": f"{info}", "identity": idnt} - data.append(entry) + if icon: + info = f"{name} • [i]{time_str}[/i]" + entry = {"icon": icon, "text": f"{info}", "identity": idnt} + data.append(entry) - except Exception as e: - RNS.log(f"An error occurred while updating the call log list: {e}", RNS.LOG_ERROR) - RNS.trace_exception(e) + except Exception as e: + RNS.log(f"An error occurred while updating the call log list: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) - self.log_list.data = data + self.log_list.data = data class LogEntry(OneLineAvatarIconListItem): owner = None From 7a89c3ed799457ae1749ce177962d308ec688e03 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 10 Nov 2025 02:12:03 +0100 Subject: [PATCH 161/271] Improved call notification visibility --- sbapp/services/sidebandservice.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index 75796a8..e5a4b43 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -89,7 +89,10 @@ class SidebandService(): if context_id in silent_contexts: silent = True else: silent = False - self.notification_channel = NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_DEFAULT) + if context_id == "incoming_call": channel_importance = NotificationManager.IMPORTANCE_HIGH + else: channel_importance = NotificationManager.IMPORTANCE_DEFAULT + + self.notification_channel = NotificationChannel(channel_id, channel_name, channel_importance) self.notification_channel.enableVibration(True) if not silent: self.notification_channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), None) else: self.notification_channel.setSound(None, None) From 5b1c910f1f10d2e3d4044dc39e6fcf2904927932 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 10 Nov 2025 02:13:14 +0100 Subject: [PATCH 162/271] Fixed call log saving when identity could not be resolved --- sbapp/sideband/core.py | 8 +++--- sbapp/sideband/voice.py | 55 +++++++++++++++++++++-------------------- sbapp/ui/voice.py | 10 +++++--- 3 files changed, 38 insertions(+), 35 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 38d7feb..589476c 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5583,15 +5583,15 @@ class SidebandCore(): def incoming_call(self, remote_identity): display_name = self.voice_display_name(remote_identity.hash) self.setstate("voice.incoming_call", display_name) - if self.gui_foreground(): RNS.log("Squelching call notification since GUI is in foreground", RNS.LOG_DEBUG) - else: self.notify(title="Incoming voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") + if self.gui_foreground() and self.getstate("app.displaying") == "voice_screen": RNS.log("Squelching call notification since voice screen is active", RNS.LOG_DEBUG) + else: self.notify(title="Incoming call", content=f"From {display_name}", group="lxst.telephony.call", context_id="incoming_call") def missed_call(self, remote_identity): display_name = self.voice_display_name(remote_identity.hash) - self.setstate("voice.incoming_call", display_name) + self.setstate("voice.missed_call", display_name) # if self.gui_foreground(): RNS.log("Squelching call notification since GUI is in foreground", RNS.LOG_DEBUG) # else: self.notify(title="Missed voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") - self.notify(title="Missed voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") + self.notify(title="Missed call", content=f"From {display_name}", group="lxst.telephony.call", context_id="incoming_call") rns_config = """# This template is used to generate a # running configuration for Sideband's diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index d271552..07e4004 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -136,35 +136,36 @@ class ReticulumTelephone(): return self.call_log def log_call(self, event, identity): - RNS.log(f"Logging call event {event} for {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) - if self.logpath: - try: - if not os.path.isfile(self.logpath): - try: - with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb([])) - except Exception as e: raise OSError("Could not create call log file") - - call_log = [] - read_call_log = [] + if identity: + RNS.log(f"Logging call event {event} for {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) + if self.logpath: try: - with open(self.logpath, "rb") as logfile: read_call_log = msgpack.unpackb(logfile.read()) + if not os.path.isfile(self.logpath): + try: + with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb([])) + except Exception as e: raise OSError("Could not create call log file") + + call_log = [] + read_call_log = [] + try: + with open(self.logpath, "rb") as logfile: read_call_log = msgpack.unpackb(logfile.read()) + except Exception as e: + RNS.log(f"Error while reading call log file: {e}", RNS.LOG_ERROR) + RNS.log(f"Call log file will be re-created", RNS.LOG_ERROR) + + for entry in read_call_log: + age = time.time()-entry["time"] + if age < self.CALL_LOG_KEEP: call_log.append(entry) + + entry = {"time": time.time(), "event": event, "identity": identity.hash} + call_log.append(entry) + + with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb(call_log)) + self.call_log = call_log + except Exception as e: - RNS.log(f"Error while reading call log file: {e}", RNS.LOG_ERROR) - RNS.log(f"Call log file will be re-created", RNS.LOG_ERROR) - - for entry in read_call_log: - age = time.time()-entry["time"] - if age < self.CALL_LOG_KEEP: call_log.append(entry) - - entry = {"time": time.time(), "event": event, "identity": identity.hash} - call_log.append(entry) - - with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb(call_log)) - self.call_log = call_log - - except Exception as e: - RNS.log(f"An error occurred while updating call log: {e}", RNS.LOG_ERROR) - RNS.trace_exception(e) + RNS.log(f"An error occurred while updating call log: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) def dial(self, identity_hash): self.last_dialled_identity_hash = identity_hash diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index a71d948..0f0e32e 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -165,10 +165,12 @@ class Voice(): toast("Path request timed out") def log_dial_action(self, sender=None): - if sender: - self.screen.ids.identity_hash.text = RNS.hexrep(sender.identity, delimit=False) - self.dial_target = sender.identity - self.dial_action() + if sender and self.app.sideband.voice_running and self.app.sideband.telephone != None: + telephone = self.app.sideband.telephone + if not telephone.is_ringing and not telephone.is_in_call and not telephone.call_is_connecting: + self.screen.ids.identity_hash.text = RNS.hexrep(sender.identity, delimit=False) + self.dial_target = sender.identity + self.dial_action() def reject_action(self, sender=None): if self.app.sideband.voice_running: From ecdbacd5d2822f8b3808f976da746d0e38dd65e9 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Nov 2025 11:13:27 +0100 Subject: [PATCH 163/271] Cleanup --- sbapp/sideband/core.py | 414 ++++++++++++++--------------------------- 1 file changed, 138 insertions(+), 276 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 589476c..f95ea7d 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -620,298 +620,160 @@ class SidebandCore(): config_file.close() # Migration actions from earlier config formats - if not "debug" in self.config: - self.config["debug"] = False - if not "dark_ui" in self.config: - self.config["dark_ui"] = True - if not "advanced_stats" in self.config: - self.config["advanced_stats"] = True - if not "lxmf_periodic_sync" in self.config: - self.config["lxmf_periodic_sync"] = False - if not "lxmf_ignore_unknown" in self.config: - self.config["lxmf_ignore_unknown"] = False - if not "lxmf_sync_interval" in self.config: - self.config["lxmf_sync_interval"] = 43200 - if not "lxmf_try_propagation_on_fail" in self.config: - self.config["lxmf_try_propagation_on_fail"] = True - if not "lxmf_require_stamps" in self.config: - self.config["lxmf_require_stamps"] = False - if not "lxmf_ignore_invalid_stamps" in self.config: - self.config["lxmf_ignore_invalid_stamps"] = True - if not "lxmf_inbound_stamp_cost" in self.config: - self.config["lxmf_inbound_stamp_cost"] = None - if not "notifications_on" in self.config: - self.config["notifications_on"] = True - if not "print_command" in self.config: - self.config["print_command"] = "lp" - if not "eink_mode" in self.config: - self.config["eink_mode"] = True - if not "classic_message_colors" in self.config: - self.config["classic_message_colors"] = False - if not "display_style_in_contact_list" in self.config: - self.config["display_style_in_contact_list"] = True - if not "lxm_limit_1mb" in self.config: - self.config["lxm_limit_1mb"] = True - if not "hq_ptt" in self.config: - 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 "confirm_calls" in self.config: - self.config["confirm_calls"] = True + if not "debug" in self.config: self.config["debug"] = False + if not "dark_ui" in self.config: self.config["dark_ui"] = True + if not "advanced_stats" in self.config: self.config["advanced_stats"] = True + if not "lxmf_periodic_sync" in self.config: self.config["lxmf_periodic_sync"] = False + if not "lxmf_ignore_unknown" in self.config: self.config["lxmf_ignore_unknown"] = False + if not "lxmf_sync_interval" in self.config: self.config["lxmf_sync_interval"] = 43200 + if not "lxmf_try_propagation_on_fail" in self.config: self.config["lxmf_try_propagation_on_fail"] = True + if not "lxmf_require_stamps" in self.config: self.config["lxmf_require_stamps"] = False + if not "lxmf_ignore_invalid_stamps" in self.config: self.config["lxmf_ignore_invalid_stamps"] = True + if not "lxmf_inbound_stamp_cost" in self.config: self.config["lxmf_inbound_stamp_cost"] = None + if not "notifications_on" in self.config: self.config["notifications_on"] = True + if not "print_command" in self.config: self.config["print_command"] = "lp" + if not "eink_mode" in self.config: self.config["eink_mode"] = True + if not "classic_message_colors" in self.config: self.config["classic_message_colors"] = False + if not "display_style_in_contact_list" in self.config: self.config["display_style_in_contact_list"] = True + if not "lxm_limit_1mb" in self.config: self.config["lxm_limit_1mb"] = True + if not "hq_ptt" in self.config: 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 "confirm_calls" in self.config: self.config["confirm_calls"] = True - if not "input_language" in self.config: - self.config["input_language"] = None - if not "allow_predictive_text" in self.config: - self.config["allow_predictive_text"] = False - if not "block_predictive_text" in self.config: - self.config["block_predictive_text"] = False + if not "input_language" in self.config: self.config["input_language"] = None + if not "allow_predictive_text" in self.config: self.config["allow_predictive_text"] = False + if not "block_predictive_text" in self.config: self.config["block_predictive_text"] = False - if not "config_template" in self.config: - self.config["config_template"] = None - if not "connect_transport" in self.config: - self.config["connect_transport"] = False - if not "connect_share_instance" in self.config: - self.config["connect_share_instance"] = False - if not "connect_rnode" in self.config: - self.config["connect_rnode"] = False - if not "connect_rnode_ifac_netname" in self.config: - self.config["connect_rnode_ifac_netname"] = "" - if not "connect_rnode_ifac_passphrase" in self.config: - self.config["connect_rnode_ifac_passphrase"] = "" - if not "connect_serial" in self.config: - self.config["connect_serial"] = False - if not "connect_serial_ifac_netname" in self.config: - self.config["connect_serial_ifac_netname"] = "" - if not "connect_serial_ifac_passphrase" in self.config: - self.config["connect_serial_ifac_passphrase"] = "" - if not "connect_modem" in self.config: - self.config["connect_modem"] = False - if not "connect_modem_ifac_netname" in self.config: - self.config["connect_modem_ifac_netname"] = "" - if not "connect_modem_ifac_passphrase" in self.config: - self.config["connect_modem_ifac_passphrase"] = "" - if not "connect_weave" in self.config: - self.config["connect_weave"] = False - if not "connect_weave_ifac_netname" in self.config: - self.config["connect_weave_ifac_netname"] = "" - if not "connect_weave_ifac_passphrase" in self.config: - self.config["connect_weave_ifac_passphrase"] = "" + if not "config_template" in self.config: self.config["config_template"] = None + if not "connect_transport" in self.config: self.config["connect_transport"] = False + if not "connect_share_instance" in self.config: self.config["connect_share_instance"] = False + if not "connect_rnode" in self.config: self.config["connect_rnode"] = False + if not "connect_rnode_ifac_netname" in self.config: self.config["connect_rnode_ifac_netname"] = "" + if not "connect_rnode_ifac_passphrase" in self.config: self.config["connect_rnode_ifac_passphrase"] = "" + if not "connect_serial" in self.config: self.config["connect_serial"] = False + if not "connect_serial_ifac_netname" in self.config: self.config["connect_serial_ifac_netname"] = "" + if not "connect_serial_ifac_passphrase" in self.config: self.config["connect_serial_ifac_passphrase"] = "" + if not "connect_modem" in self.config: self.config["connect_modem"] = False + if not "connect_modem_ifac_netname" in self.config: self.config["connect_modem_ifac_netname"] = "" + if not "connect_modem_ifac_passphrase" in self.config: self.config["connect_modem_ifac_passphrase"] = "" + if not "connect_weave" in self.config: self.config["connect_weave"] = False + if not "connect_weave_ifac_netname" in self.config: self.config["connect_weave_ifac_netname"] = "" + if not "connect_weave_ifac_passphrase" in self.config: self.config["connect_weave_ifac_passphrase"] = "" - if not "connect_ifmode_local" in self.config: - self.config["connect_ifmode_local"] = "full" - if not "connect_ifmode_tcp" in self.config: - self.config["connect_ifmode_tcp"] = "full" - if not "connect_ifmode_i2p" in self.config: - self.config["connect_ifmode_i2p"] = "full" - if not "connect_ifmode_rnode" in self.config: - self.config["connect_ifmode_rnode"] = "full" - if not "connect_ifmode_modem" in self.config: - self.config["connect_ifmode_modem"] = "full" - if not "connect_ifmode_serial" in self.config: - self.config["connect_ifmode_serial"] = "full" - if not "connect_ifmode_bluetooth" in self.config: - self.config["connect_ifmode_bluetooth"] = "full" - if not "connect_ifmode_weave" in self.config: - self.config["connect_ifmode_weave"] = "full" + if not "connect_ifmode_local" in self.config: self.config["connect_ifmode_local"] = "full" + if not "connect_ifmode_tcp" in self.config: self.config["connect_ifmode_tcp"] = "full" + if not "connect_ifmode_i2p" in self.config: self.config["connect_ifmode_i2p"] = "full" + if not "connect_ifmode_rnode" in self.config: self.config["connect_ifmode_rnode"] = "full" + if not "connect_ifmode_modem" in self.config: self.config["connect_ifmode_modem"] = "full" + if not "connect_ifmode_serial" in self.config: self.config["connect_ifmode_serial"] = "full" + if not "connect_ifmode_bluetooth" in self.config: self.config["connect_ifmode_bluetooth"] = "full" + if not "connect_ifmode_weave" in self.config: self.config["connect_ifmode_weave"] = "full" - if not "hw_rnode_frequency" in self.config: - self.config["hw_rnode_frequency"] = None - if not "hw_rnode_modulation" in self.config: - self.config["hw_rnode_modulation"] = "LoRa" - if not "hw_rnode_bandwidth" in self.config: - self.config["hw_rnode_bandwidth"] = 62500 - if not "hw_rnode_spreading_factor" in self.config: - self.config["hw_rnode_spreading_factor"] = 8 - if not "hw_rnode_coding_rate" in self.config: - self.config["hw_rnode_coding_rate"] = 6 - if not "hw_rnode_tx_power" in self.config: - self.config["hw_rnode_tx_power"] = 0 - if not "hw_rnode_beaconinterval" in self.config: - self.config["hw_rnode_beaconinterval"] = None - if not "hw_rnode_beacondata" in self.config: - self.config["hw_rnode_beacondata"] = None - if not "hw_rnode_bluetooth" in self.config: - self.config["hw_rnode_bluetooth"] = False - if not "hw_rnode_ble" in self.config: - self.config["hw_rnode_ble"] = False - if not "hw_rnode_enable_framebuffer" in self.config: - self.config["hw_rnode_enable_framebuffer"] = False - if not "hw_rnode_bt_device" in self.config: - self.config["hw_rnode_bt_device"] = None - if not "hw_rnode_atl_short" in self.config: - self.config["hw_rnode_atl_short"] = None - if not "hw_rnode_atl_long" in self.config: - self.config["hw_rnode_atl_long"] = None + if not "hw_rnode_frequency" in self.config: self.config["hw_rnode_frequency"] = None + if not "hw_rnode_modulation" in self.config: self.config["hw_rnode_modulation"] = "LoRa" + if not "hw_rnode_bandwidth" in self.config: self.config["hw_rnode_bandwidth"] = 62500 + if not "hw_rnode_spreading_factor" in self.config: self.config["hw_rnode_spreading_factor"] = 8 + if not "hw_rnode_coding_rate" in self.config: self.config["hw_rnode_coding_rate"] = 6 + if not "hw_rnode_tx_power" in self.config: self.config["hw_rnode_tx_power"] = 0 + if not "hw_rnode_beaconinterval" in self.config: self.config["hw_rnode_beaconinterval"] = None + if not "hw_rnode_beacondata" in self.config: self.config["hw_rnode_beacondata"] = None + if not "hw_rnode_bluetooth" in self.config: self.config["hw_rnode_bluetooth"] = False + if not "hw_rnode_ble" in self.config: self.config["hw_rnode_ble"] = False + if not "hw_rnode_enable_framebuffer" in self.config: self.config["hw_rnode_enable_framebuffer"] = False + if not "hw_rnode_bt_device" in self.config: self.config["hw_rnode_bt_device"] = None + if not "hw_rnode_atl_short" in self.config: self.config["hw_rnode_atl_short"] = None + if not "hw_rnode_atl_long" in self.config: self.config["hw_rnode_atl_long"] = None - if not "hw_modem_baudrate" in self.config: - self.config["hw_modem_baudrate"] = 115200 - if not "hw_modem_databits" in self.config: - self.config["hw_modem_databits"] = 8 - if not "hw_modem_stopbits" in self.config: - self.config["hw_modem_stopbits"] = 1 - if not "hw_modem_parity" in self.config: - self.config["hw_modem_parity"] = "none" - if not "hw_modem_preamble" in self.config: - self.config["hw_modem_preamble"] = 150 - if not "hw_modem_tail" in self.config: - self.config["hw_modem_tail"] = 20 - if not "hw_modem_persistence" in self.config: - self.config["hw_modem_persistence"] = 220 - if not "hw_modem_slottime" in self.config: - self.config["hw_modem_slottime"] = 20 - if not "hw_modem_beaconinterval" in self.config: - self.config["hw_modem_beaconinterval"] = None - if not "hw_modem_beacondata" in self.config: - self.config["hw_modem_beacondata"] = None + if not "hw_modem_baudrate" in self.config: self.config["hw_modem_baudrate"] = 115200 + if not "hw_modem_databits" in self.config: self.config["hw_modem_databits"] = 8 + if not "hw_modem_stopbits" in self.config: self.config["hw_modem_stopbits"] = 1 + if not "hw_modem_parity" in self.config: self.config["hw_modem_parity"] = "none" + if not "hw_modem_preamble" in self.config: self.config["hw_modem_preamble"] = 150 + if not "hw_modem_tail" in self.config: self.config["hw_modem_tail"] = 20 + if not "hw_modem_persistence" in self.config: self.config["hw_modem_persistence"] = 220 + if not "hw_modem_slottime" in self.config: self.config["hw_modem_slottime"] = 20 + if not "hw_modem_beaconinterval" in self.config: self.config["hw_modem_beaconinterval"] = None + if not "hw_modem_beacondata" in self.config: self.config["hw_modem_beacondata"] = None - if not "hw_serial_baudrate" in self.config: - self.config["hw_serial_baudrate"] = 57600 - if not "hw_serial_databits" in self.config: - self.config["hw_serial_databits"] = 8 - if not "hw_serial_stopbits" in self.config: - self.config["hw_serial_stopbits"] = 1 - if not "hw_serial_parity" in self.config: - self.config["hw_serial_parity"] = "none" + if not "hw_serial_baudrate" in self.config: self.config["hw_serial_baudrate"] = 57600 + if not "hw_serial_databits" in self.config: self.config["hw_serial_databits"] = 8 + if not "hw_serial_stopbits" in self.config: self.config["hw_serial_stopbits"] = 1 + if not "hw_serial_parity" in self.config: self.config["hw_serial_parity"] = "none" - if not "telemetry_enabled" in self.config: - self.config["telemetry_enabled"] = False - if not "telemetry_collector" in self.config: - self.config["telemetry_collector"] = None - if not "telemetry_send_to_trusted" in self.config: - self.config["telemetry_send_to_trusted"] = False - if not "telemetry_send_to_collector" in self.config: - self.config["telemetry_send_to_collector"] = False - if not "telemetry_request_from_collector" in self.config: - self.config["telemetry_request_from_collector"] = False - if not "telemetry_send_interval" in self.config: - self.config["telemetry_send_interval"] = 43200 - if not "telemetry_request_interval" in self.config: - 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_enabled" in self.config: self.config["telemetry_enabled"] = False + if not "telemetry_collector" in self.config: self.config["telemetry_collector"] = None + if not "telemetry_send_to_trusted" in self.config: self.config["telemetry_send_to_trusted"] = False + if not "telemetry_send_to_collector" in self.config: self.config["telemetry_send_to_collector"] = False + if not "telemetry_request_from_collector" in self.config: self.config["telemetry_request_from_collector"] = False + if not "telemetry_send_interval" in self.config: self.config["telemetry_send_interval"] = 43200 + if not "telemetry_request_interval" in self.config: 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] - if not "telemetry_fg" in self.config: - self.config["telemetry_fg"] = SidebandCore.DEFAULT_APPEARANCE[1] - if not "telemetry_bg" in self.config: - self.config["telemetry_bg"] = SidebandCore.DEFAULT_APPEARANCE[2] - if not "telemetry_send_appearance" in self.config: - self.config["telemetry_send_appearance"] = True - if not "telemetry_display_trusted_only" in self.config: - self.config["telemetry_display_trusted_only"] = False - if not "display_style_from_all" in self.config: - self.config["display_style_from_all"] = True - if not "telemetry_receive_trusted_only" in self.config: - self.config["telemetry_receive_trusted_only"] = False + if not "telemetry_icon" in self.config: self.config["telemetry_icon"] = SidebandCore.DEFAULT_APPEARANCE[0] + if not "telemetry_fg" in self.config: self.config["telemetry_fg"] = SidebandCore.DEFAULT_APPEARANCE[1] + if not "telemetry_bg" in self.config: self.config["telemetry_bg"] = SidebandCore.DEFAULT_APPEARANCE[2] + if not "telemetry_send_appearance" in self.config: self.config["telemetry_send_appearance"] = True + if not "telemetry_display_trusted_only" in self.config: self.config["telemetry_display_trusted_only"] = False + if not "display_style_from_all" in self.config: self.config["display_style_from_all"] = True + if not "telemetry_receive_trusted_only" in self.config: self.config["telemetry_receive_trusted_only"] = False - if not "telemetry_send_all_to_collector" in self.config: - self.config["telemetry_send_all_to_collector"] = False - if not "telemetry_use_propagation_only" in self.config: - self.config["telemetry_use_propagation_only"] = False - if not "telemetry_try_propagation_on_fail" in self.config: - self.config["telemetry_try_propagation_on_fail"] = True - if not "telemetry_requests_only_send_latest" in self.config: - self.config["telemetry_requests_only_send_latest"] = True - if not "telemetry_allow_requests_from_trusted" in self.config: - self.config["telemetry_allow_requests_from_trusted"] = False - if not "telemetry_allow_requests_from_anyone" in self.config: - self.config["telemetry_allow_requests_from_anyone"] = False + if not "telemetry_send_all_to_collector" in self.config: self.config["telemetry_send_all_to_collector"] = False + if not "telemetry_use_propagation_only" in self.config: self.config["telemetry_use_propagation_only"] = False + if not "telemetry_try_propagation_on_fail" in self.config: self.config["telemetry_try_propagation_on_fail"] = True + if not "telemetry_requests_only_send_latest" in self.config: self.config["telemetry_requests_only_send_latest"] = True + if not "telemetry_allow_requests_from_trusted" in self.config: self.config["telemetry_allow_requests_from_trusted"] = False + if not "telemetry_allow_requests_from_anyone" in self.config: self.config["telemetry_allow_requests_from_anyone"] = False - if not "telemetry_s_location" in self.config: - self.config["telemetry_s_location"] = False - if not "telemetry_s_battery" in self.config: - self.config["telemetry_s_battery"] = False - if not "telemetry_s_pressure" in self.config: - self.config["telemetry_s_pressure"] = False - if not "telemetry_s_temperature" in self.config: - self.config["telemetry_s_temperature"] = False - if not "telemetry_s_humidity" in self.config: - self.config["telemetry_s_humidity"] = False - if not "telemetry_s_magnetic_field" in self.config: - self.config["telemetry_s_magnetic_field"] = False - if not "telemetry_s_ambient_light" in self.config: - self.config["telemetry_s_ambient_light"] = False - if not "telemetry_s_gravity" in self.config: - self.config["telemetry_s_gravity"] = False - if not "telemetry_s_angular_velocity" in self.config: - self.config["telemetry_s_angular_velocity"] = False - if not "telemetry_s_acceleration" in self.config: - 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: - self.config["telemetry_s_fixed_latlon"] = [0.0, 0.0] - if not "telemetry_s_fixed_altitude" in self.config: - self.config["telemetry_s_fixed_altitude"] = 0.0 - if not "telemetry_s_information" in self.config: - self.config["telemetry_s_information"] = False - if not "telemetry_s_information_text" in self.config: - self.config["telemetry_s_information_text"] = "" + if not "telemetry_s_location" in self.config: self.config["telemetry_s_location"] = False + if not "telemetry_s_battery" in self.config: self.config["telemetry_s_battery"] = False + if not "telemetry_s_pressure" in self.config: self.config["telemetry_s_pressure"] = False + if not "telemetry_s_temperature" in self.config: self.config["telemetry_s_temperature"] = False + if not "telemetry_s_humidity" in self.config: self.config["telemetry_s_humidity"] = False + if not "telemetry_s_magnetic_field" in self.config: self.config["telemetry_s_magnetic_field"] = False + if not "telemetry_s_ambient_light" in self.config: self.config["telemetry_s_ambient_light"] = False + if not "telemetry_s_gravity" in self.config: self.config["telemetry_s_gravity"] = False + if not "telemetry_s_angular_velocity" in self.config: self.config["telemetry_s_angular_velocity"] = False + if not "telemetry_s_acceleration" in self.config: 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: self.config["telemetry_s_fixed_latlon"] = [0.0, 0.0] + if not "telemetry_s_fixed_altitude" in self.config: self.config["telemetry_s_fixed_altitude"] = 0.0 + if not "telemetry_s_information" in self.config: self.config["telemetry_s_information"] = False + if not "telemetry_s_information_text" in self.config: self.config["telemetry_s_information_text"] = "" - if not "service_plugins_enabled" in self.config: - self.config["service_plugins_enabled"] = False - if not "command_plugins_enabled" in self.config: - self.config["command_plugins_enabled"] = False - if not "command_plugins_path" in self.config: - self.config["command_plugins_path"] = None + if not "service_plugins_enabled" in self.config: self.config["service_plugins_enabled"] = False + if not "command_plugins_enabled" in self.config: self.config["command_plugins_enabled"] = False + if not "command_plugins_path" in self.config: self.config["command_plugins_path"] = None - if not "map_history_limit" in self.config: - self.config["map_history_limit"] = 7*24*60*60 - if not "map_lat" in self.config: - self.config["map_lat"] = 0.0 - if not "map_lon" in self.config: - self.config["map_lon"] = 0.0 - if not "map_zoom" in self.config: - self.config["map_zoom"] = 3 - if not "map_storage_external" in self.config: - self.config["map_storage_external"] = False - if not "map_use_offline" in self.config: - self.config["map_use_offline"] = False - if not "map_use_online" in self.config: - self.config["map_use_online"] = True - if not "map_layer" in self.config: - self.config["map_layer"] = None + if not "map_history_limit" in self.config: self.config["map_history_limit"] = 7*24*60*60 + if not "map_lat" in self.config: self.config["map_lat"] = 0.0 + if not "map_lon" in self.config: self.config["map_lon"] = 0.0 + if not "map_zoom" in self.config: self.config["map_zoom"] = 3 + if not "map_storage_external" in self.config: self.config["map_storage_external"] = False + if not "map_use_offline" in self.config: self.config["map_use_offline"] = False + if not "map_use_online" in self.config: self.config["map_use_online"] = True + if not "map_layer" in self.config: self.config["map_layer"] = None - if not "map_storage_path" in self.config: - self.config["map_storage_path"] = None - if not "map_storage_file" in self.config: - self.config["map_storage_file"] = None + if not "map_storage_path" in self.config: self.config["map_storage_path"] = None + if not "map_storage_file" in self.config: self.config["map_storage_file"] = None - if not "voice_enabled" in self.config: - self.config["voice_enabled"] = False - if not "voice_output" in self.config: - self.config["voice_output"] = None - if not "voice_input" in self.config: - self.config["voice_input"] = None - if not "voice_ringer" in self.config: - self.config["voice_ringer"] = None - if not "voice_trusted_only" in self.config: - self.config["voice_trusted_only"] = False - if not "voice_low_latency" in self.config: - self.config["voice_low_latency"] = False + if not "voice_enabled" in self.config: self.config["voice_enabled"] = False + if not "voice_output" in self.config: self.config["voice_output"] = None + if not "voice_input" in self.config: self.config["voice_input"] = None + if not "voice_ringer" in self.config: self.config["voice_ringer"] = None + if not "voice_trusted_only" in self.config: self.config["voice_trusted_only"] = False + if not "voice_low_latency" in self.config: self.config["voice_low_latency"] = False # Make sure we have a database - if not os.path.isfile(self.db_path): - self.__db_init() + if not os.path.isfile(self.db_path): self.__db_init() else: self._db_initstate() self._db_initpersistent() From 5d5f949a156fb2656f3be8ce601ba8298d4b87c3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Nov 2025 11:59:01 +0100 Subject: [PATCH 164/271] Added wifi connection option to RNode settings --- sbapp/main.py | 78 ++++++++++++++++------------------- sbapp/sideband/core.py | 2 + sbapp/ui/layouts.py | 93 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 122 insertions(+), 51 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 088ccab..e18a46b 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4533,58 +4533,40 @@ class SidebandApp(MDApp): self.root.ids.screen_manager.transition = self.slide_transition def hardware_rnode_save(self): - try: - self.sideband.config["hw_rnode_frequency"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_frequency.text)*1000000) - except: - pass + try: self.sideband.config["hw_rnode_frequency"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_frequency.text)*1000000) + except: pass - try: - self.sideband.config["hw_rnode_bandwidth"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text)*1000) - except: - pass + try: self.sideband.config["hw_rnode_bandwidth"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text)*1000) + except: pass - try: - self.sideband.config["hw_rnode_tx_power"] = int(self.hardware_rnode_screen.ids.hardware_rnode_txpower.text) - except: - pass + try: self.sideband.config["hw_rnode_tx_power"] = int(self.hardware_rnode_screen.ids.hardware_rnode_txpower.text) + except: pass - try: - self.sideband.config["hw_rnode_spreading_factor"] = int(self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text) - except: - pass + try: self.sideband.config["hw_rnode_spreading_factor"] = int(self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text) + except: pass - try: - self.sideband.config["hw_rnode_coding_rate"] = int(self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text) - except: - pass + try: self.sideband.config["hw_rnode_coding_rate"] = int(self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text) + except: pass - try: - self.sideband.config["hw_rnode_atl_short"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text) - except: - self.sideband.config["hw_rnode_atl_short"] = None + try: self.sideband.config["hw_rnode_atl_short"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text) + except: self.sideband.config["hw_rnode_atl_short"] = None - try: - self.sideband.config["hw_rnode_atl_long"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text) - except: - self.sideband.config["hw_rnode_atl_long"] = None + try: self.sideband.config["hw_rnode_atl_long"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text) + except: self.sideband.config["hw_rnode_atl_long"] = None - if self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text == "": - self.sideband.config["hw_rnode_beaconinterval"] = None + if self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text == "": self.sideband.config["hw_rnode_beaconinterval"] = None else: - try: - self.sideband.config["hw_rnode_beaconinterval"] = int(self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text) - except: - pass + try: self.sideband.config["hw_rnode_beaconinterval"] = int(self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text) + except: pass - if self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text == "": - self.sideband.config["hw_rnode_beacondata"] = None - else: - self.sideband.config["hw_rnode_beacondata"] = self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text + if self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text == "": self.sideband.config["hw_rnode_beacondata"] = None + else: self.sideband.config["hw_rnode_beacondata"] = self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text - if self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text == "": - self.sideband.config["hw_rnode_bt_device"] = None - else: - self.sideband.config["hw_rnode_bt_device"] = self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text + if self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text == "": self.sideband.config["hw_rnode_bt_device"] = None + else: self.sideband.config["hw_rnode_bt_device"] = self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text + + if self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text == "": self.sideband.config["hw_rnode_tcp_host"] = None + else: self.sideband.config["hw_rnode_tcp_host"] = self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text self.sideband.save_configuration() @@ -4724,6 +4706,12 @@ class SidebandApp(MDApp): self.sideband.save_configuration() + def hardware_rnode_tcp_toggle_action(self, sender=None, event=None): + if sender.active: self.sideband.config["hw_rnode_tcp"] = True + else: self.sideband.config["hw_rnode_tcp"] = False + + self.sideband.save_configuration() + def hardware_rnode_init(self, sender=None): if not self.hardware_rnode_ready: if not self.root.ids.screen_manager.has_screen("hardware_rnode_screen"): @@ -4773,6 +4761,8 @@ class SidebandApp(MDApp): t_btd = str(self.sideband.config["hw_rnode_bt_device"]) else: t_btd = "" + if self.sideband.config["hw_rnode_tcp_host"] != None: t_th = str(self.sideband.config["hw_rnode_tcp_host"]) + else: t_th = "" if self.sideband.config["hw_rnode_atl_short"] != None: t_ats = str(self.sideband.config["hw_rnode_atl_short"]) else: @@ -4784,6 +4774,7 @@ class SidebandApp(MDApp): self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.active = self.sideband.config["hw_rnode_bluetooth"] self.hardware_rnode_screen.ids.hardware_rnode_ble.active = self.sideband.config["hw_rnode_ble"] + self.hardware_rnode_screen.ids.hardware_rnode_tcp.active = self.sideband.config["hw_rnode_tcp"] self.hardware_rnode_screen.ids.hardware_rnode_framebuffer.active = self.sideband.config["hw_rnode_enable_framebuffer"] self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = t_freq self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = t_bw @@ -4793,6 +4784,7 @@ class SidebandApp(MDApp): self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = t_bi self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text = t_bd self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text = t_btd + self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text = t_th self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text = t_ats self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text = t_atl self.hardware_rnode_screen.ids.hardware_rnode_frequency.bind(focus=focus_save) @@ -4803,6 +4795,7 @@ class SidebandApp(MDApp): self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.bind(focus=focus_save) self.hardware_rnode_screen.ids.hardware_rnode_beacondata.bind(focus=focus_save) self.hardware_rnode_screen.ids.hardware_rnode_bt_device.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.bind(focus=focus_save) self.hardware_rnode_screen.ids.hardware_rnode_frequency.bind(on_text_validate=save_connectivity) self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.bind(on_text_validate=save_connectivity) self.hardware_rnode_screen.ids.hardware_rnode_txpower.bind(on_text_validate=save_connectivity) @@ -4815,6 +4808,7 @@ class SidebandApp(MDApp): self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.bind(active=self.hardware_rnode_bt_toggle_action) self.hardware_rnode_screen.ids.hardware_rnode_ble.bind(active=self.hardware_rnode_ble_toggle_action) self.hardware_rnode_screen.ids.hardware_rnode_framebuffer.bind(active=self.hardware_rnode_framebuffer_toggle_action) + self.hardware_rnode_screen.ids.hardware_rnode_tcp.bind(active=self.hardware_rnode_tcp_toggle_action) self.hardware_rnode_ready = True diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index f95ea7d..8adf170 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -680,8 +680,10 @@ class SidebandCore(): if not "hw_rnode_beacondata" in self.config: self.config["hw_rnode_beacondata"] = None if not "hw_rnode_bluetooth" in self.config: self.config["hw_rnode_bluetooth"] = False if not "hw_rnode_ble" in self.config: self.config["hw_rnode_ble"] = False + if not "hw_rnode_tcp" in self.config: self.config["hw_rnode_tcp"] = False if not "hw_rnode_enable_framebuffer" in self.config: self.config["hw_rnode_enable_framebuffer"] = False if not "hw_rnode_bt_device" in self.config: self.config["hw_rnode_bt_device"] = None + if not "hw_rnode_tcp_host" in self.config: self.config["hw_rnode_tcp_host"] = None if not "hw_rnode_atl_short" in self.config: self.config["hw_rnode_atl_short"] = None if not "hw_rnode_atl_long" in self.config: self.config["hw_rnode_atl_long"] = None diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index e457b64..bcd2329 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -2589,8 +2589,8 @@ MDScreen: MDBoxLayout: orientation: "horizontal" size_hint_y: None - padding: [0,dp(14),dp(24),dp(48)] - height: dp(86) + padding: [0,dp(14),dp(24),dp(0)] + height: dp(48) MDLabel: text: "Control RNode Display" @@ -2602,13 +2602,71 @@ MDScreen: active: False MDLabel: - text: "Bluetooth Settings\\n" + text: "•" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2+14), 0, dp(22+24)] + + MDLabel: + text: "WiFi & Ethernet Connection\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info_wifi + markup: True + text: "If your device is hosting or connected to a WiFi network, you can connect it by entering its IP address or hostname below." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,dp(12),dp(24),dp(0)] + height: dp(36) + + MDLabel: + text: "Connect using WiFi" + font_style: "H6" + + MDSwitch: + id: hardware_rnode_tcp + pos_hint: {"center_y": 0.3} + active: False + + MDBoxLayout: + orientation: "vertical" + # spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_tcp_host + hint_text: "RNode IP address or hostname" + text: "" + font_size: dp(24) + + MDLabel: + text: "•" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2+14), 0, dp(22+24)] + + MDLabel: + text: "Bluetooth Connection\\n" font_style: "H6" MDLabel: id: hardware_rnode_info markup: True - text: "If you enable connection via Bluetooth, Sideband will attempt to connect to any available and paired RNodes over Bluetooth. If your RNode uses BLE (ESP32-S3 and nRF devices) instead of classic Bluetooth, enable the [i]Device requires BLE[/i] option as well." + text: "If you enable connection via Bluetooth, Sideband will attempt to connect to any available and paired RNodes over Bluetooth.\\n\\nIf your RNode uses BLE (ESP32-S3 and nRF devices) instead of classic Bluetooth, enable the [i]Device requires BLE[/i] option as well." size_hint_y: None text_size: self.width, None height: self.texture_size[1] @@ -2631,8 +2689,8 @@ MDScreen: MDBoxLayout: orientation: "horizontal" size_hint_y: None - padding: [0,0,dp(24),dp(0)] - height: dp(48) + padding: [0,0,dp(24),dp(48)] + height: dp(86) MDLabel: text: "Device requires BLE" @@ -2643,10 +2701,14 @@ MDScreen: pos_hint: {"center_y": 0.3} active: False + MDLabel: + text: "Bluetooth Pairing\\n" + font_style: "H6" + MDLabel: id: hardware_rnode_info markup: True - text: "You must first pair the RNode with your device for this to work. To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode.You can then pair the device using the Bluetooth settings of your device, or by pressing the pairing button below. On older Android versions, the in-app scanning and pairing may not work. In this case, use the Bluetooth settings of your device to scan and pair.\\n" + text: "To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode. If the in-app pairing does not find any devices, use the Bluetooth settings of your device to scan and pair.\\n" size_hint_y: None text_size: self.width, None height: self.texture_size[1] @@ -2674,12 +2736,16 @@ MDScreen: spacing: "24dp" size_hint_y: None height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(12)] + padding: [dp(0), dp(0), dp(0), dp(12+24)] + + MDLabel: + text: "Preffered Bluetooth Device\\n" + font_style: "H6" MDLabel: id: hardware_rnode_info markup: True - text: "By default, Sideband will connect to the first available RNode that is paired. If you want to always use a specific RNode, you can enter its name in the Preferred RNode Device Name field below, for example \\"RNode A8EB\\"." + text: "Sideband will connect to the first available RNode that is paired. If you want to always use a specific RNode, you can enter its name here, for example \\"RNode A8EB\\"." size_hint_y: None text_size: self.width, None height: self.texture_size[1] @@ -2697,6 +2763,15 @@ MDScreen: text: "" font_size: dp(24) + MDLabel: + text: "•" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2+14), 0, dp(22)] + MDLabel: text: "\\n\\nDevice Bluetooth Control\\n" font_style: "H6" From 576bc3fd8552d2efb4d0ea17b7d16e17dcf5824e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Nov 2025 12:02:36 +0100 Subject: [PATCH 165/271] Cleanup --- sbapp/main.py | 74 ++++++++++++++++++++++----------------------------- 1 file changed, 32 insertions(+), 42 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e18a46b..dda83bc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4729,48 +4729,38 @@ class SidebandApp(MDApp): if not sender.focus: save_connectivity(sender=sender) - if self.sideband.config["hw_rnode_frequency"] != None: - t_freq = str(self.sideband.config["hw_rnode_frequency"]/1000000.0) - else: - t_freq = "" - if self.sideband.config["hw_rnode_bandwidth"] != None: - t_bw = str(self.sideband.config["hw_rnode_bandwidth"]/1000.0) - else: - t_bw = str(62.5) - if self.sideband.config["hw_rnode_tx_power"] != None: - t_p = str(self.sideband.config["hw_rnode_tx_power"]) - else: - t_p = str(0) - if self.sideband.config["hw_rnode_spreading_factor"] != None: - t_sf = str(self.sideband.config["hw_rnode_spreading_factor"]) - else: - t_sf = str(8) - if self.sideband.config["hw_rnode_coding_rate"] != None: - t_cr = str(self.sideband.config["hw_rnode_coding_rate"]) - else: - t_cr = str(6) - if self.sideband.config["hw_rnode_beaconinterval"] != None: - t_bi = str(self.sideband.config["hw_rnode_beaconinterval"]) - else: - t_bi = "" - if self.sideband.config["hw_rnode_beacondata"] != None: - t_bd = str(self.sideband.config["hw_rnode_beacondata"]) - else: - t_bd = "" - if self.sideband.config["hw_rnode_bt_device"] != None: - t_btd = str(self.sideband.config["hw_rnode_bt_device"]) - else: - t_btd = "" - if self.sideband.config["hw_rnode_tcp_host"] != None: t_th = str(self.sideband.config["hw_rnode_tcp_host"]) - else: t_th = "" - if self.sideband.config["hw_rnode_atl_short"] != None: - t_ats = str(self.sideband.config["hw_rnode_atl_short"]) - else: - t_ats = "" - if self.sideband.config["hw_rnode_atl_long"] != None: - t_atl = str(self.sideband.config["hw_rnode_atl_long"]) - else: - t_atl = "" + if self.sideband.config["hw_rnode_frequency"] != None: t_freq = str(self.sideband.config["hw_rnode_frequency"]/1000000.0) + else: t_freq = "" + + if self.sideband.config["hw_rnode_bandwidth"] != None: t_bw = str(self.sideband.config["hw_rnode_bandwidth"]/1000.0) + else: t_bw = str(62.5) + + if self.sideband.config["hw_rnode_tx_power"] != None: t_p = str(self.sideband.config["hw_rnode_tx_power"]) + else: t_p = str(0) + + if self.sideband.config["hw_rnode_spreading_factor"] != None: t_sf = str(self.sideband.config["hw_rnode_spreading_factor"]) + else: t_sf = str(8) + + if self.sideband.config["hw_rnode_coding_rate"] != None: t_cr = str(self.sideband.config["hw_rnode_coding_rate"]) + else: t_cr = str(6) + + if self.sideband.config["hw_rnode_beaconinterval"] != None: t_bi = str(self.sideband.config["hw_rnode_beaconinterval"]) + else: t_bi = "" + + if self.sideband.config["hw_rnode_beacondata"] != None: t_bd = str(self.sideband.config["hw_rnode_beacondata"]) + else: t_bd = "" + + if self.sideband.config["hw_rnode_bt_device"] != None: t_btd = str(self.sideband.config["hw_rnode_bt_device"]) + else: t_btd = "" + + if self.sideband.config["hw_rnode_tcp_host"] != None: t_th = str(self.sideband.config["hw_rnode_tcp_host"]) + else: t_th = "" + + if self.sideband.config["hw_rnode_atl_short"] != None: t_ats = str(self.sideband.config["hw_rnode_atl_short"]) + else: t_ats = "" + + if self.sideband.config["hw_rnode_atl_long"] != None: t_atl = str(self.sideband.config["hw_rnode_atl_long"]) + else: t_atl = "" self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.active = self.sideband.config["hw_rnode_bluetooth"] self.hardware_rnode_screen.ids.hardware_rnode_ble.active = self.sideband.config["hw_rnode_ble"] From 4ed2be070767c9d57fc7cc4d50285f718d23d552 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 18 Nov 2025 12:29:59 +0100 Subject: [PATCH 166/271] Added ability to connect RNodes over WiFi/Ethernet on Android --- sbapp/sideband/core.py | 69 +++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 28 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 8adf170..9f4b005 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -3901,6 +3901,7 @@ class SidebandCore(): bt_device_name = None rnode_allow_bluetooth = False rnode_allow_ble = False + rnode_allow_tcp = False if self.getpersistent("permissions.bluetooth"): if self.config["hw_rnode_bluetooth"]: RNS.log("Allowing RNode bluetooth", RNS.LOG_DEBUG) @@ -3923,25 +3924,19 @@ class SidebandCore(): RNS.log("Disallowing RNode bluetooth due to missing permission", RNS.LOG_DEBUG) rnode_allow_bluetooth = False - if self.config["connect_rnode_ifac_netname"] == "": - ifac_netname = None - else: - ifac_netname = self.config["connect_rnode_ifac_netname"] + if self.config["hw_rnode_tcp"] and self.config["hw_rnode_tcp_host"]: + rnode_allow_bluetooth = False + rnode_allow_ble = False + rnode_allow_tcp = True - if self.config["connect_rnode_ifac_passphrase"] == "": - ifac_netkey = None - else: - ifac_netkey = self.config["connect_rnode_ifac_passphrase"] - - if self.config["hw_rnode_atl_short"] == "": - atl_short = None - else: - atl_short = self.config["hw_rnode_atl_short"] - - if self.config["hw_rnode_atl_long"] == "": - atl_long = None - else: - atl_long = self.config["hw_rnode_atl_long"] + if self.config["connect_rnode_ifac_netname"] == "": ifac_netname = None + else: ifac_netname = self.config["connect_rnode_ifac_netname"] + if self.config["connect_rnode_ifac_passphrase"] == "": ifac_netkey = None + else: ifac_netkey = self.config["connect_rnode_ifac_passphrase"] + if self.config["hw_rnode_atl_short"] == "": atl_short = None + else: atl_short = self.config["hw_rnode_atl_short"] + if self.config["hw_rnode_atl_long"] == "": atl_long = None + else: atl_long = self.config["hw_rnode_atl_long"] interface_config = None if rnode_allow_ble: @@ -3965,6 +3960,28 @@ class SidebandCore(): "ble_addr": None, } + elif rnode_allow_tcp: + interface_config = { + "name": "RNodeInterface", + "port": None, + "frequency": self.config["hw_rnode_frequency"], + "bandwidth": self.config["hw_rnode_bandwidth"], + "txpower": self.config["hw_rnode_tx_power"], + "spreadingfactor": self.config["hw_rnode_spreading_factor"], + "codingrate": self.config["hw_rnode_coding_rate"], + "flow_control": False, + "id_interval": self.config["hw_rnode_beaconinterval"], + "id_callsign": self.config["hw_rnode_beacondata"], + "st_alock": atl_short, + "lt_alock": atl_long, + "allow_bluetooth": False, + "target_device_name": None, + "force_ble": False, + "ble_name": None, + "ble_addr": None, + "tcp_host": self.config["hw_rnode_tcp_host"], + } + else: interface_config = { "name": "RNodeInterface", @@ -3991,16 +4008,12 @@ class SidebandCore(): if RNS.Reticulum.transport_enabled(): if_mode = Interface.Interface.MODE_FULL - if self.config["connect_ifmode_rnode"] == "gateway": - if_mode = Interface.Interface.MODE_GATEWAY - elif self.config["connect_ifmode_rnode"] == "access point": - if_mode = Interface.Interface.MODE_ACCESS_POINT - elif self.config["connect_ifmode_rnode"] == "roaming": - if_mode = Interface.Interface.MODE_ROAMING - elif self.config["connect_ifmode_rnode"] == "boundary": - if_mode = Interface.Interface.MODE_BOUNDARY - else: - if_mode = None + if self.config["connect_ifmode_rnode"] == "gateway": if_mode = Interface.Interface.MODE_GATEWAY + elif self.config["connect_ifmode_rnode"] == "access point": if_mode = Interface.Interface.MODE_ACCESS_POINT + elif self.config["connect_ifmode_rnode"] == "roaming": if_mode = Interface.Interface.MODE_ROAMING + elif self.config["connect_ifmode_rnode"] == "boundary": if_mode = Interface.Interface.MODE_BOUNDARY + + else: if_mode = None self.reticulum._add_interface(rnodeinterface, mode = if_mode, ifac_netname = ifac_netname, ifac_netkey = ifac_netkey) self.interface_rnode = rnodeinterface From 553401884ac650ad73490d94636f1fa1c95c5a3b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 19 Nov 2025 14:38:22 +0100 Subject: [PATCH 167/271] Fixed peer appearance updates from bulk telemetry transfer --- sbapp/sideband/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 9f4b005..39fbc28 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2407,7 +2407,7 @@ class SidebandCore(): if not "appearance" in data_dict: data_dict["appearance"] = None - if from_bulk_telemetry and data_dict["appearance"] != SidebandCore.DEFAULT_APPEARANCE: + if from_bulk_telemetry and data_dict["appearance"] != SidebandCore.DEFAULT_APPEARANCE and data_dict["appearance"] != None: RNS.log("Aborting appearance update from bulk transfer, since conversation already has appearance set: "+str(appearance)+" / "+str(data_dict["appearance"]), RNS.LOG_DEBUG) return From 6d8960563d93a4f83a5b9ac025eec97a62b4cd77 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 19 Nov 2025 16:38:25 +0100 Subject: [PATCH 168/271] Updated repository versions and flasher URL --- sbapp/Makefile | 6 +++--- sbapp/main.py | 2 +- sbapp/share/flasher.html | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index 5508d19..8eacb30 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -64,9 +64,9 @@ endif fetchshare: -(rm ./share/pkg/*) -(rm ./share/mirrors/* -r) - cp ../../dist_archive/rns-1.0.1-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/rnspure-1.0.1-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/lxmf-0.9.1-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rns-1.0.3-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rnspure-1.0.3-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/lxmf-0.9.3-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/nomadnet-0.9.1-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/rnsh-0.1.7-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/RNode_Firmware_*_Source.zip ./share/pkg/ diff --git a/sbapp/main.py b/sbapp/main.py index dda83bc..f40e5ca 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4284,7 +4284,7 @@ class SidebandApp(MDApp): 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" + self.rnode_flasher_url = ipurl+"mirrors/rnode-flasher/RNode_Flasher.html" ms = "" if len(ips) == 1 else "es" info += "The repository server is running at the following address" + ms +":\n\n"+ipstr diff --git a/sbapp/share/flasher.html b/sbapp/share/flasher.html index 9033cc9..a45de5f 100644 --- a/sbapp/share/flasher.html +++ b/sbapp/share/flasher.html @@ -26,7 +26,7 @@ To use the flasher, you will need firmware packages for the boards you want use.

  • You can compile them yourself from the RNode Firmware source code package included in this repository.

  • -
    +


    From 2e32f22076c6985fc1db5b1dbf93a561657bf447 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 19 Nov 2025 16:48:45 +0100 Subject: [PATCH 169/271] Updated dependency versions --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 4766856..a8dbee4 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.0.1", - "lxmf>=0.9.1", + "rns>=1.0.3", + "lxmf>=0.9.3", "kivy>=2.3.0", "pillow>=10.2.0", "qrcode", From ca2ef3ca377aec910fa6c31be505e33024a405ca Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 20 Nov 2025 11:37:14 +0100 Subject: [PATCH 170/271] Startup checks for CLI console --- sbapp/main.py | 9 +++++++-- sbapp/sideband/core.py | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index f40e5ca..b16f5c0 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -6958,8 +6958,13 @@ def run(): if args.interactive: while not sideband.getstate("core.started") == True: time.sleep(0.1) - from .sideband import console - console.attach(sideband) + import importlib + if importlib.util.find_spec('prompt_toolkit') != None: + from .sideband import console + console.attach(sideband) + else: + print("Could not start Sideband console, since the \"prompt-toolkit\" module is not available") + print("You can install it with \"pip install prompt-toolkit\"") else: while True: time.sleep(5) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 39fbc28..2aaf717 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -898,7 +898,7 @@ class SidebandCore(): def save_configuration(self): self.__save_config() - if self.is_standalone: self.owner_app.save_window_config() + if self.is_standalone and not self.is_daemon: self.owner_app.save_window_config() def set_active_propagation_node(self, dest): if dest == None: From 0de6b2d1d0f7a6035c1df02adb2b934e2baeb3a2 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 20 Nov 2025 23:30:57 +0100 Subject: [PATCH 171/271] Added ability to start Sideband at device boot on Android --- sbapp/buildozer.spec | 2 +- sbapp/main.py | 14 ++++++++++---- sbapp/patches/AndroidManifest.tmpl.xml | 6 ++++++ sbapp/patches/PythonService.java | 24 ++++++++++++++++++++++++ sbapp/sideband/core.py | 11 +++++++++-- sbapp/ui/layouts.py | 15 +++++++++++++++ 6 files changed, 65 insertions(+), 7 deletions(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 5d5af68..ca77da4 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -29,7 +29,7 @@ android.presplash_color = #00000000 orientation = portrait fullscreen = 0 -android.permissions = INTERNET,POST_NOTIFICATIONS,WAKE_LOCK,FOREGROUND_SERVICE,CHANGE_WIFI_MULTICAST_STATE,BLUETOOTH_SCAN,BLUETOOTH_ADVERTISE,BLUETOOTH_CONNECT,ACCESS_NETWORK_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,MANAGE_EXTERNAL_STORAGE,ACCESS_BACKGROUND_LOCATION,RECORD_AUDIO,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,FOREGROUND_SERVICE_CONNECTED_DEVICE,MODIFY_AUDIO_SETTINGS +android.permissions = INTERNET,POST_NOTIFICATIONS,WAKE_LOCK,FOREGROUND_SERVICE,CHANGE_WIFI_MULTICAST_STATE,BLUETOOTH_SCAN,BLUETOOTH_ADVERTISE,BLUETOOTH_CONNECT,ACCESS_NETWORK_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,MANAGE_EXTERNAL_STORAGE,ACCESS_BACKGROUND_LOCATION,RECORD_AUDIO,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,FOREGROUND_SERVICE_CONNECTED_DEVICE,MODIFY_AUDIO_SETTINGS,RECEIVE_BOOT_COMPLETED android.api = 33 android.minapi = 24 diff --git a/sbapp/main.py b/sbapp/main.py index b16f5c0..7787f9a 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3592,6 +3592,10 @@ class SidebandApp(MDApp): self.sideband.start_voice() else: self.sideband.stop_voice() + def save_start_at_boot(sender=None, event=None): + self.sideband.config["start_at_boot"] = self.settings_screen.ids.settings_start_at_boot.active + self.sideband.save_configuration() + def save_print_command(sender=None, event=None): if not sender.focus: in_cmd = self.settings_screen.ids.settings_print_command.text @@ -3671,11 +3675,10 @@ class SidebandApp(MDApp): else: self.settings_screen.ids.settings_print_command.text = self.sideband.config["print_command"] self.settings_screen.ids.settings_print_command.bind(focus=save_print_command) + self.settings_screen.ids.settings_start_at_boot.disabled = True - if self.sideband.config["lxmf_propagation_node"] == None: - prop_node_addr = "" - else: - prop_node_addr = RNS.hexrep(self.sideband.config["lxmf_propagation_node"], delimit=False) + if self.sideband.config["lxmf_propagation_node"] == None: prop_node_addr = "" + else: prop_node_addr = RNS.hexrep(self.sideband.config["lxmf_propagation_node"], delimit=False) self.settings_screen.ids.settings_propagation_node_address.text = prop_node_addr self.settings_screen.ids.settings_propagation_node_address.bind(focus=save_prop_addr) @@ -3705,6 +3708,9 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_advanced_statistics.active = self.sideband.config["advanced_stats"] self.settings_screen.ids.settings_advanced_statistics.bind(active=save_advanced_stats) + self.settings_screen.ids.settings_start_at_boot.active = self.sideband.config["start_at_boot"] + self.settings_screen.ids.settings_start_at_boot.bind(active=save_start_at_boot) + self.settings_screen.ids.settings_start_announce.active = self.sideband.config["start_announce"] self.settings_screen.ids.settings_start_announce.bind(active=save_start_announce) diff --git a/sbapp/patches/AndroidManifest.tmpl.xml b/sbapp/patches/AndroidManifest.tmpl.xml index c6cdd64..9ff83ec 100644 --- a/sbapp/patches/AndroidManifest.tmpl.xml +++ b/sbapp/patches/AndroidManifest.tmpl.xml @@ -121,6 +121,12 @@ {% endfor %} + + + + + + {% if args.billing_pubkey %} diff --git a/sbapp/patches/PythonService.java b/sbapp/patches/PythonService.java index ad7142c..72e853c 100644 --- a/sbapp/patches/PythonService.java +++ b/sbapp/patches/PythonService.java @@ -25,8 +25,32 @@ import android.graphics.drawable.Icon; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.MulticastLock; +import java.util.Objects; +import android.content.BroadcastReceiver; + +import io.unsigned.sideband.ServiceSidebandservice; + public class PythonService extends Service implements Runnable { + public static class ServiceBootReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + try { + if (Objects.equals(intent.getAction(), "android.intent.action.BOOT_COMPLETED")) { + boolean should_start = false; + String app_dir = context.getFilesDir().getParentFile().getParent(); + String toggle_path = context.getFilesDir()+"/app_storage/"; + File file = new File(toggle_path, "boot_toggle"); + if (file.exists()) { should_start = true; } + if (should_start) { + ServiceSidebandservice svc = new ServiceSidebandservice(); + svc.start(context, app_dir); + } + } + } catch (Exception e) { Log.e("sidebandservice", "Could not start Sideband service at boot: "+e); } + } + } + // Thread for Python code private Thread pythonThread = null; diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 2aaf717..ba30abe 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -623,6 +623,7 @@ class SidebandCore(): if not "debug" in self.config: self.config["debug"] = False if not "dark_ui" in self.config: self.config["dark_ui"] = True if not "advanced_stats" in self.config: self.config["advanced_stats"] = True + if not "start_at_boot" in self.config: self.config["start_at_boot"] = False if not "lxmf_periodic_sync" in self.config: self.config["lxmf_periodic_sync"] = False if not "lxmf_ignore_unknown" in self.config: self.config["lxmf_ignore_unknown"] = False if not "lxmf_sync_interval" in self.config: self.config["lxmf_sync_interval"] = 43200 @@ -807,9 +808,15 @@ class SidebandCore(): time.sleep(0.15) try: self.saving_configuration = True - with open(self.config_path, "wb") as config_file: - config_file.write(msgpack.packb(self.config)) + with open(self.config_path, "wb") as config_file: config_file.write(msgpack.packb(self.config)) self.saving_configuration = False + if RNS.vendor.platformutils.is_android(): + boot_toggle_path = self.app_dir+"/app_storage/boot_toggle" + boot_toggle_exists = os.path.isfile(boot_toggle_path) + if self.config["start_at_boot"] == True and not boot_toggle_exists: + with open(boot_toggle_path, "w") as f: f.write("true") + elif self.config["start_at_boot"] == False and boot_toggle_exists: + os.unlink(boot_toggle_path) except Exception as e: self.saving_configuration = False RNS.log("Error while saving Sideband configuration: "+str(e), RNS.LOG_ERROR) diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index bcd2329..4909255 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -1666,6 +1666,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: "Start at boot" + font_style: "H6" + + MDSwitch: + id: settings_start_at_boot + pos_hint: {"center_y": 0.3} + active: False + MDLabel: text: "•" font_style: "H6" From 24bf675ca3fbac5c8cefd3c188ac9283a7ad9741 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 20 Nov 2025 23:55:45 +0100 Subject: [PATCH 172/271] Added call confirm dialog to calls made from call log --- sbapp/main.py | 28 +++++++++++++++------------- sbapp/ui/voice.py | 19 +++++++++++++------ 2 files changed, 28 insertions(+), 19 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 7787f9a..2021874 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2011,6 +2011,19 @@ class SidebandApp(MDApp): item = c[(len(c)-1)-i] self.conversation_action(item) + def init_confirm_call_dialog(self, call_dialog_text): + yes_button = MDRectangleFlatButton(text="Call",font_size=dp(18), theme_text_color="Custom", line_color=self.color_accept, text_color=self.color_accept) + no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) + self.confirm_call_dialog = MDDialog(text=call_dialog_text, buttons=[ no_button, yes_button ]) + def dl_no(s): self.confirm_call_dialog.dismiss() + def dl_yes(s): + self.confirm_call_dialog.dismiss() + def cb(dt): self.dial_action(self.confirm_call_dialog.dest_identity_hash) + Clock.schedule_once(cb, 0.15) + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + def conversation_action(self, sender): if sender.conv_type == self.sideband.CONV_P2P: context_dest = sender.sb_uid @@ -2025,20 +2038,9 @@ class SidebandApp(MDApp): def cb(dt): self.dial_action(identity_hash) Clock.schedule_once(cb, 0.15) else: - call_dialog_text = f"[b]Initiate Voice Call?[/b]\n\nDestination Identity:\n{RNS.prettyhexrep(identity_hash)}?" + call_dialog_text = f"[b]Initiate Voice Call?[/b]\n\nDestination Identity:\n{RNS.prettyhexrep(identity_hash)}" if hasattr(self, "confirm_call_dialog"): self.confirm_call_dialog.text = call_dialog_text - else: - yes_button = MDRectangleFlatButton(text="Call",font_size=dp(18), theme_text_color="Custom", line_color=self.color_accept, text_color=self.color_accept) - no_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) - self.confirm_call_dialog = MDDialog(text=call_dialog_text, buttons=[ no_button, yes_button ]) - def dl_no(s): self.confirm_call_dialog.dismiss() - def dl_yes(s): - self.confirm_call_dialog.dismiss() - def cb(dt): self.dial_action(self.confirm_call_dialog.dest_identity_hash) - Clock.schedule_once(cb, 0.15) - - yes_button.bind(on_release=dl_yes) - no_button.bind(on_release=dl_no) + else: self.init_confirm_call_dialog(call_dialog_text) self.confirm_call_dialog.dest_identity_hash = identity_hash self.confirm_call_dialog.open() diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 0f0e32e..a9acfa3 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -165,12 +165,19 @@ class Voice(): toast("Path request timed out") def log_dial_action(self, sender=None): - if sender and self.app.sideband.voice_running and self.app.sideband.telephone != None: - telephone = self.app.sideband.telephone - if not telephone.is_ringing and not telephone.is_in_call and not telephone.call_is_connecting: - self.screen.ids.identity_hash.text = RNS.hexrep(sender.identity, delimit=False) - self.dial_target = sender.identity - self.dial_action() + def job(dt=None): + if not self.app.root.ids.screen_manager.current == "voice_screen": return + if sender and self.app.sideband.voice_running and self.app.sideband.telephone != None: + telephone = self.app.sideband.telephone + if not telephone.is_ringing and not telephone.is_in_call and not telephone.call_is_connecting: + call_dialog_text = f"[b]Initiate Voice Call?[/b]\n\nDestination Identity:\n{RNS.prettyhexrep(sender.identity)}" + if hasattr(self.app, "confirm_call_dialog"): self.app.confirm_call_dialog.text = call_dialog_text + else: self.app.init_confirm_call_dialog(call_dialog_text) + self.app.confirm_call_dialog.dest_identity_hash = sender.identity + self.app.confirm_call_dialog.open() + + Clock.schedule_once(job, 0.1) + def reject_action(self, sender=None): if self.app.sideband.voice_running: From e4d649ca794fc46f4d774c84758bc3aa27740948 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 21 Nov 2025 00:10:38 +0100 Subject: [PATCH 173/271] Added ability to clear call log --- sbapp/sideband/core.py | 55 +++++++++++++++++++++-------------------- sbapp/sideband/voice.py | 25 ++++++++++++------- sbapp/ui/voice.py | 25 ++++++++++++++++++- 3 files changed, 68 insertions(+), 37 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index ba30abe..840e313 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1997,33 +1997,34 @@ class SidebandCore(): connection.send(send_result) elif "get_plugins_info" in call: connection.send(self._get_plugins_info()) elif "get_destination_establishment_rate" in call: connection.send(self._get_destination_establishment_rate(call["get_destination_establishment_rate"])) - elif "get_destination_mtu" in call: connection.send(self._get_destination_mtu(call["get_destination_mtu"])) - elif "get_destination_edr" in call: connection.send(self._get_destination_edr(call["get_destination_edr"])) - elif "get_destination_lmd" in call: connection.send(self._get_destination_lmd(call["get_destination_lmd"])) - elif "get_lxm_progress" in call: connection.send(self.get_lxm_progress(call["get_lxm_progress"]["lxm_hash"])) - elif "get_lxm_stamp_cost" in call: connection.send(self.get_lxm_stamp_cost(call["get_lxm_stamp_cost"]["lxm_hash"])) - elif "get_lxm_propagation_cost" in call: connection.send(self.get_lxm_propagation_cost(call["get_lxm_propagation_cost"]["lxm_hash"])) - elif "is_tracking" in call: connection.send(self.is_tracking(call["is_tracking"])) - elif "start_tracking" in call: connection.send(self.start_tracking(object_addr=call["start_tracking"]["object_addr"], interval=call["start_tracking"]["interval"], duration=call["start_tracking"]["duration"])) - elif "stop_tracking" in call: connection.send(self.stop_tracking(object_addr=call["stop_tracking"]["object_addr"])) - elif "get_service_log" in call: connection.send(self.get_service_log()) - elif "start_voice" in call: connection.send(self.start_voice()) - elif "stop_voice" in call: connection.send(self.stop_voice()) - elif "telephone_is_available" in call: connection.send(self.telephone.is_available if self.telephone else False) - elif "telephone_is_in_call" in call: connection.send(self.telephone.is_in_call if self.telephone else False) - elif "telephone_call_is_connecting" in call: connection.send(self.telephone.call_is_connecting if self.telephone else False) - elif "telephone_is_ringing" in call: connection.send(self.telephone.is_ringing if self.telephone else False) - elif "telephone_caller_info" in call: connection.send(self.telephone.caller.hash if self.telephone and self.telephone.caller else None) - elif "telephone_set_busy" in call: connection.send(self.telephone.set_busy(call["telephone_set_busy"]) if self.telephone else False) - elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"]) if self.telephone else False) - elif "telephone_hangup" in call: connection.send(self.telephone.hangup() if self.telephone else False) - elif "telephone_answer" in call: connection.send(self.telephone.answer() if self.telephone else False) - elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"]) if self.telephone else False) - elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"]) if self.telephone else False) - elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"]) if self.telephone else False) - elif "telephone_set_low_latency_output" in call: connection.send(self.telephone.set_low_latency_output(call["telephone_set_low_latency_output"]) if self.telephone else False) - elif "telephone_announce" in call: connection.send(self.telephone.announce() if self.telephone else False) - elif "telephone_get_call_log" in call: connection.send(self.telephone.get_call_log() if self.telephone else []) + elif "get_destination_mtu" in call: connection.send(self._get_destination_mtu(call["get_destination_mtu"])) + elif "get_destination_edr" in call: connection.send(self._get_destination_edr(call["get_destination_edr"])) + elif "get_destination_lmd" in call: connection.send(self._get_destination_lmd(call["get_destination_lmd"])) + elif "get_lxm_progress" in call: connection.send(self.get_lxm_progress(call["get_lxm_progress"]["lxm_hash"])) + elif "get_lxm_stamp_cost" in call: connection.send(self.get_lxm_stamp_cost(call["get_lxm_stamp_cost"]["lxm_hash"])) + elif "get_lxm_propagation_cost" in call: connection.send(self.get_lxm_propagation_cost(call["get_lxm_propagation_cost"]["lxm_hash"])) + elif "is_tracking" in call: connection.send(self.is_tracking(call["is_tracking"])) + elif "start_tracking" in call: connection.send(self.start_tracking(object_addr=call["start_tracking"]["object_addr"], interval=call["start_tracking"]["interval"], duration=call["start_tracking"]["duration"])) + elif "stop_tracking" in call: connection.send(self.stop_tracking(object_addr=call["stop_tracking"]["object_addr"])) + elif "get_service_log" in call: connection.send(self.get_service_log()) + elif "start_voice" in call: connection.send(self.start_voice()) + elif "stop_voice" in call: connection.send(self.stop_voice()) + elif "telephone_is_available" in call: connection.send(self.telephone.is_available if self.telephone else False) + elif "telephone_is_in_call" in call: connection.send(self.telephone.is_in_call if self.telephone else False) + elif "telephone_call_is_connecting" in call: connection.send(self.telephone.call_is_connecting if self.telephone else False) + elif "telephone_is_ringing" in call: connection.send(self.telephone.is_ringing if self.telephone else False) + elif "telephone_caller_info" in call: connection.send(self.telephone.caller.hash if self.telephone and self.telephone.caller else None) + elif "telephone_set_busy" in call: connection.send(self.telephone.set_busy(call["telephone_set_busy"]) if self.telephone else False) + elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"]) if self.telephone else False) + elif "telephone_hangup" in call: connection.send(self.telephone.hangup() if self.telephone else False) + elif "telephone_answer" in call: connection.send(self.telephone.answer() if self.telephone else False) + elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"]) if self.telephone else False) + elif "telephone_set_microphone" in call: connection.send(self.telephone.set_microphone(call["telephone_set_microphone"]) if self.telephone else False) + elif "telephone_set_ringer" in call: connection.send(self.telephone.set_ringer(call["telephone_set_ringer"]) if self.telephone else False) + elif "telephone_set_low_latency_output" in call: connection.send(self.telephone.set_low_latency_output(call["telephone_set_low_latency_output"]) if self.telephone else False) + elif "telephone_announce" in call: connection.send(self.telephone.announce() if self.telephone else False) + elif "telephone_get_call_log" in call: connection.send(self.telephone.get_call_log() if self.telephone else []) + elif "telephone_clear_call_log" in call: connection.send(self.telephone.clear_call_log() if self.telephone else False) else: connection.send(None) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 07e4004..f506da6 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -118,6 +118,12 @@ class ReticulumTelephone(): def set_busy(self, busy): self.telephone.set_busy(busy) def set_low_latency_output(self, enabled): self.telephone.set_low_latency_output(enabled) + def clear_call_log(self): + self.call_log = [] + try: + with open(self.logpath, "wb") as logfile: logfile.write(msgpack.packb([])) + except Exception as e: raise OSError("Could not clear call log file") + def get_call_log(self): if self.call_log: return self.call_log else: @@ -264,13 +270,14 @@ class ReticulumTelephoneProxy(): @property def caller(self): return CallerProxy(hash=self.owner.service_rpc_request({"telephone_caller_info": True })) - def set_busy(self, busy): return self.owner.service_rpc_request({"telephone_set_busy": busy }) - def dial(self, dial_target): return self.owner.service_rpc_request({"telephone_dial": dial_target }) - def hangup(self): return self.owner.service_rpc_request({"telephone_hangup": True }) - def answer(self): return self.owner.service_rpc_request({"telephone_answer": True }) - def set_speaker(self, speaker): return self.owner.service_rpc_request({"telephone_set_speaker": speaker }) - def set_microphone(self, microphone): return self.owner.service_rpc_request({"telephone_set_microphone": microphone }) - def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) + def set_busy(self, busy): return self.owner.service_rpc_request({"telephone_set_busy": busy }) + def dial(self, dial_target): return self.owner.service_rpc_request({"telephone_dial": dial_target }) + def hangup(self): return self.owner.service_rpc_request({"telephone_hangup": True }) + def answer(self): return self.owner.service_rpc_request({"telephone_answer": True }) + def set_speaker(self, speaker): return self.owner.service_rpc_request({"telephone_set_speaker": speaker }) + def set_microphone(self, microphone): return self.owner.service_rpc_request({"telephone_set_microphone": microphone }) + def set_ringer(self, ringer): return self.owner.service_rpc_request({"telephone_set_ringer": ringer }) def set_low_latency_output(self, enabled): return self.owner.service_rpc_request({"telephone_set_low_latency_output": enabled}) - def announce(self): return self.owner.service_rpc_request({"telephone_announce": True}) - def get_call_log(self): return self.owner.service_rpc_request({"telephone_get_call_log": True}) \ No newline at end of file + def announce(self): return self.owner.service_rpc_request({"telephone_announce": True}) + def get_call_log(self): return self.owner.service_rpc_request({"telephone_get_call_log": True}) + def clear_call_log(self): return self.owner.service_rpc_request({"telephone_clear_call_log": True}) \ No newline at end of file diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index a9acfa3..f739285 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -164,6 +164,10 @@ class Voice(): def _path_request_failed(self, dt): toast("Path request timed out") + def clear_log_action(self, sender=None): + self.app.sideband.telephone.clear_call_log() + self.update_call_log() + def log_dial_action(self, sender=None): def job(dt=None): if not self.app.root.ids.screen_manager.current == "voice_screen": return @@ -178,7 +182,6 @@ class Voice(): Clock.schedule_once(job, 0.1) - def reject_action(self, sender=None): if self.app.sideband.voice_running: if self.app.sideband.telephone.is_ringing: @@ -522,6 +525,26 @@ MDScreen: MDBoxLayout: orientation: "vertical" id: log_list_container + + MDSeparator: + orientation: "horizontal" + height: dp(1) + + MDBoxLayout: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(24), dp(28), dp(24)] + + MDRectangleFlatIconButton: + id: clear_log_button + icon: "playlist-remove" + text: "Clear Log" + 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.clear_log_action(self) """ layout_voice_settings_screen = """ From d38f91898c6e1de51fb791960fafa89aae4fada0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 21 Nov 2025 16:55:57 +0100 Subject: [PATCH 174/271] Added call profile configuration to voice screen. Added automatic incoming call profile configuration. --- sbapp/sideband/core.py | 3 +- sbapp/sideband/voice.py | 34 ++++++++++----------- sbapp/ui/voice.py | 66 +++++++++++++++++++++++++++++++++-------- 3 files changed, 72 insertions(+), 31 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 840e313..e84514c 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2014,8 +2014,9 @@ class SidebandCore(): elif "telephone_call_is_connecting" in call: connection.send(self.telephone.call_is_connecting if self.telephone else False) elif "telephone_is_ringing" in call: connection.send(self.telephone.is_ringing if self.telephone else False) elif "telephone_caller_info" in call: connection.send(self.telephone.caller.hash if self.telephone and self.telephone.caller else None) + elif "telephone_active_profile" in call: connection.send(self.telephone.active_profile if self.telephone else None) elif "telephone_set_busy" in call: connection.send(self.telephone.set_busy(call["telephone_set_busy"]) if self.telephone else False) - elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"]) if self.telephone else False) + elif "telephone_dial" in call: connection.send(self.telephone.dial(call["telephone_dial"], profile=call["profile"]) if self.telephone else False) elif "telephone_hangup" in call: connection.send(self.telephone.hangup() if self.telephone else False) elif "telephone_answer" in call: connection.send(self.telephone.answer() if self.telephone else False) elif "telephone_set_speaker" in call: connection.send(self.telephone.set_speaker(call["telephone_set_speaker"]) if self.telephone else False) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index f506da6..1721a43 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -80,28 +80,25 @@ class ReticulumTelephone(): self.telephone.announce(attached_interface=attached_interface) @property - def is_available(self): - return self.state == self.STATE_AVAILABLE + def is_available(self): return self.state == self.STATE_AVAILABLE @property - def is_in_call(self): - return self.state == self.STATE_IN_CALL + def is_in_call(self): return self.state == self.STATE_IN_CALL @property - def is_ringing(self): - return self.state == self.STATE_RINGING + def is_ringing(self): return self.state == self.STATE_RINGING @property - def call_is_connecting(self): - return self.state == self.STATE_CONNECTING + def call_is_connecting(self): return self.state == self.STATE_CONNECTING @property - def hw_is_idle(self): - return self.hw_state == self.HW_STATE_IDLE + def hw_is_idle(self): return self.hw_state == self.HW_STATE_IDLE @property - def hw_is_dialing(self): - return self.hw_state == self.HW_STATE_DIAL + def hw_is_dialing(self): return self.hw_state == self.HW_STATE_DIAL + + @property + def active_profile(self): return self.telephone.active_profile def start(self): if not self.should_run: @@ -173,7 +170,7 @@ class ReticulumTelephone(): RNS.log(f"An error occurred while updating call log: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) - def dial(self, identity_hash): + def dial(self, identity_hash, profile=None): self.last_dialled_identity_hash = identity_hash destination_hash = RNS.Destination.hash_from_name_and_identity("lxst.telephony", identity_hash) if RNS.Transport.has_path(destination_hash): @@ -181,19 +178,19 @@ class ReticulumTelephone(): cs = "" if call_hops == 1 else "s" RNS.log(f"Connecting call over {call_hops} hop{cs}...", RNS.LOG_DEBUG) identity = RNS.Identity.recall(destination_hash) - self.call(identity) + self.call(identity, profile=profile) else: return "no_path" def redial(self, args=None): if self.last_dialled_identity_hash: self.dial(self.last_dialled_identity_hash) - def call(self, remote_identity): + def call(self, remote_identity, profile=None): RNS.log(f"Calling {RNS.prettyhexrep(remote_identity.hash)}...", RNS.LOG_DEBUG) self.state = self.STATE_CONNECTING self.caller = remote_identity self.direction = "to" - self.telephone.call(self.caller) + self.telephone.call(self.caller, profile=profile) def ringing(self, remote_identity): if self.hw_state == self.HW_STATE_SLEEP: self.hw_state = self.HW_STATE_IDLE @@ -270,8 +267,11 @@ class ReticulumTelephoneProxy(): @property def caller(self): return CallerProxy(hash=self.owner.service_rpc_request({"telephone_caller_info": True })) + @property + def active_profile(self): return self.owner.service_rpc_request({"telephone_active_profile": True }) + def set_busy(self, busy): return self.owner.service_rpc_request({"telephone_set_busy": busy }) - def dial(self, dial_target): return self.owner.service_rpc_request({"telephone_dial": dial_target }) + def dial(self, dial_target, profile=None): return self.owner.service_rpc_request({"telephone_dial": dial_target, "profile": profile }) def hangup(self): return self.owner.service_rpc_request({"telephone_hangup": True }) def answer(self): return self.owner.service_rpc_request({"telephone_answer": True }) def set_speaker(self, speaker): return self.owner.service_rpc_request({"telephone_set_speaker": speaker }) diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index f739285..80e05aa 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -35,6 +35,8 @@ if RNS.vendor.platformutils.get_platform() == "android": else: from .helpers import multilingual_markup +from LXST.Primitives.Telephony import Telephone, Profiles + class Voice(): def __init__(self, app): self.app = app @@ -51,6 +53,7 @@ class Voice(): self.listed_output_devices = [] self.listed_input_devices = [] self.listed_ringer_devices = [] + self.call_profile = Profiles.DEFAULT_PROFILE if not self.app.root.ids.screen_manager.has_screen("voice_screen"): self.screen = Builder.load_string(layout_voice_screen) @@ -70,6 +73,7 @@ class Voice(): db = self.screen.ids.dial_button rb = self.screen.ids.reject_button ih = self.screen.ids.identity_hash + pb = self.screen.ids.call_profile_button if self.app.sideband.voice_running: telephone = self.app.sideband.telephone if self.path_requesting: @@ -81,29 +85,39 @@ class Voice(): if telephone.is_available: ih.disabled = False rb.disabled = True + pb.disabled = False self.target_input_action(ih) else: ih.disabled = True rb.disabled = True + pb.disabled = True if telephone.is_in_call or telephone.call_is_connecting: ih.disabled = True rb.disabled = True db.disabled = False + pb.disabled = True db.text = "Hang up" db.icon = "phone-hangup" + if telephone.active_profile: self.call_profile = telephone.active_profile elif telephone.is_ringing: ih.disabled = True rb.disabled = False db.disabled = False + pb.disabled = True db.text = "Answer" db.icon = "phone-ring" if telephone.caller: ih.text = RNS.hexrep(telephone.caller.hash, delimit=False) + if telephone.active_profile: self.call_profile = telephone.active_profile else: db.disabled = True; db.text = "Voice calls disabled" ih.disabled = True + rb.disabled = True + pb.disabled = True + + pb.text = Profiles.profile_abbrevation(self.call_profile) if time.time() > self.last_log_update+3: self.update_call_log() @@ -151,7 +165,7 @@ class Voice(): self.app.sideband.telephone.set_busy(False) if RNS.Transport.has_path(self.path_requesting): RNS.log(f"Calling {RNS.prettyhexrep(self.dial_target)}...", RNS.LOG_DEBUG) - self.app.sideband.telephone.dial(self.dial_target) + self.app.sideband.telephone.dial(self.dial_target, profile=self.call_profile) Clock.schedule_once(self.update_call_status, 0.1) else: @@ -164,6 +178,12 @@ class Voice(): def _path_request_failed(self, dt): toast("Path request timed out") + def call_profile_action(self, sender=None): + pb = self.screen.ids.call_profile_button + self.call_profile = Profiles.next_profile(self.call_profile) + pb.text = Profiles.profile_abbrevation(self.call_profile) + toast(f"Call Profile: {Profiles.profile_name(self.call_profile)}") + def clear_log_action(self, sender=None): self.app.sideband.telephone.clear_call_log() self.update_call_log() @@ -197,7 +217,7 @@ class Voice(): else: RNS.log(f"Calling {RNS.prettyhexrep(self.dial_target)}...", RNS.LOG_DEBUG) - self.app.sideband.telephone.dial(self.dial_target) + self.app.sideband.telephone.dial(self.dial_target, profile=self.call_profile) self.update_call_status() elif self.app.sideband.telephone.is_in_call or self.app.sideband.telephone.call_is_connecting: @@ -246,6 +266,8 @@ class Voice(): self.voice_settings_screen.ids.voice_low_latency.active = self.app.sideband.config["voice_low_latency"] self.voice_settings_screen.ids.voice_low_latency.bind(active=self.settings_save_action) + if not RNS.vendor.platformutils.is_android(): self.voice_settings_screen.ids.voice_low_latency.disabled = True + bp = 6; ml = 38; fs = 16; ics = 14 self.update_devices() @@ -471,7 +493,7 @@ MDScreen: orientation: "vertical" size_hint_y: None height: self.minimum_height - padding: [dp(28), dp(32), dp(28), dp(16)] + padding: [dp(28), dp(12), dp(28), dp(16)] MDBoxLayout: orientation: "vertical" @@ -496,16 +518,34 @@ MDScreen: height: self.minimum_height padding: [dp(0), dp(35), dp(0), dp(14)] - MDRectangleFlatIconButton: - id: dial_button - icon: "phone-outgoing" - text: "Call" - 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.dial_action(self) - disabled: True + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(0)] + + MDRectangleFlatIconButton: + id: call_profile_button + icon: "account-voice" + text: "HQ" + 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.call_profile_action(self) + disabled: False + + MDRectangleFlatIconButton: + id: dial_button + icon: "phone-outgoing" + text: "Call" + padding: [dp(0), dp(14), dp(0), dp(14)] + icon_size: dp(24) + font_size: dp(16) + size_hint: [2.0, None] + on_release: root.delegate.dial_action(self) + disabled: True MDRectangleFlatIconButton: id: reject_button From 75e6fd05e887426976d1ee194e701d84cfe66cce Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 21 Nov 2025 17:17:21 +0100 Subject: [PATCH 175/271] Updated info view --- sbapp/main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 2021874..9d53cd2 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -27,6 +27,8 @@ import base64 import threading import RNS.vendor.umsgpack as msgpack +from LXST._version import __version__ as lxst_version + WINDOW_DEFAULT_WIDTH = 494 WINDOW_DEFAULT_HEIGHT = 800 WINDOW_HEIGHT_MARGIN = 0 @@ -3251,7 +3253,7 @@ class SidebandApp(MDApp): str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]Able[/b] (MIT License)\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 + info = "This is "+self.root.ids.app_version_info.text+"\nRunning on RNS v"+RNS.__version__+", LXMF v"+LXMF.__version__+" and LXST v"+lxst_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 6edc6e377193aaf69750849ff18343fca8728441 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 22 Nov 2025 10:28:42 +0100 Subject: [PATCH 176/271] Render toast component in-application on all platforms --- sbapp/kivymd/toast/__init__.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/sbapp/kivymd/toast/__init__.py b/sbapp/kivymd/toast/__init__.py index d5270c6..4e73ac1 100755 --- a/sbapp/kivymd/toast/__init__.py +++ b/sbapp/kivymd/toast/__init__.py @@ -2,10 +2,14 @@ __all__ = ("toast",) from kivy.utils import platform +use_native_toast = False + if platform == "android": - try: - from .androidtoast import toast - except ModuleNotFoundError: + if use_native_toast: + try: from .androidtoast import toast + except ModuleNotFoundError: from .kivytoast import toast + else: from .kivytoast import toast + else: from .kivytoast import toast From d854a2d93d342f708d3a2d605a47422364051338 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 22 Nov 2025 10:56:45 +0100 Subject: [PATCH 177/271] Fixed text-field rendering bug no Android --- sbapp/kivymd/uix/textfield/textfield.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sbapp/kivymd/uix/textfield/textfield.py b/sbapp/kivymd/uix/textfield/textfield.py index a351580..666ec33 100755 --- a/sbapp/kivymd/uix/textfield/textfield.py +++ b/sbapp/kivymd/uix/textfield/textfield.py @@ -306,6 +306,7 @@ from kivymd.font_definitions import theme_font_styles from kivymd.theming import ThemableBehavior from kivymd.uix.behaviors import DeclarativeBehavior from kivymd.uix.label import MDIcon +from kivy.utils import platform with open( os.path.join(uix_path, "textfield", "textfield.kv"), encoding="utf-8" @@ -1483,7 +1484,8 @@ class MDTextField( Animation(_hint_y=y, duration=0.2, t="out_quad").start(self) if self.mode == "rectangle": if not self.icon_left: - _hint_x = x + if platform == "android": _hint_x = x+dp(7) + else: _hint_x = x else: if y == dp(10): _hint_x = dp(-4) From 2fb4c0132fef816ab062c398f861f15a5a720b02 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 22 Nov 2025 15:17:30 +0100 Subject: [PATCH 178/271] Updated Android build code --- sbapp/buildozer.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index ca77da4..c5bbffe 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 = 20251103 +android.numeric_version = 20251122 requirements = kivy==2.3.0,libbz2,sqlite3,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 From d99393dfd6bbff020cd2f5c0cceb52c80fc5b6f9 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 22 Nov 2025 15:20:03 +0100 Subject: [PATCH 179/271] Updated dependency versions --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index a8dbee4..7617665 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.0.3", + "rns>=1.0.4", "lxmf>=0.9.3", "kivy>=2.3.0", "pillow>=10.2.0", @@ -123,7 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy>=2.0.0", - "lxst>=0.4.0", + "lxst>=0.4.1", "mistune>=3.0.2", "beautifulsoup4", "pycodec2>=4.1.0;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From 4c99029f9fe5500b0818a266ba440fbb7ddbe7f7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 22 Nov 2025 20:23:34 +0100 Subject: [PATCH 180/271] Fixed toast --- sbapp/main.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 9d53cd2..6e06dd5 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4627,7 +4627,8 @@ class SidebandApp(MDApp): if pair_addr in self.bt_bonded_devices: pairing_confirmed = True RNS.log(f"Pairing with {device_name} ({pair_addr}) successful", RNS.LOG_NOTICE) - toast(f"Paired with {device_name}") + def job(dt=None): toast(f"Paired with {device_name}") + Clock.schedule_once(job, 0.2) def hardware_rnode_pair_device_action(self, pair_addr): RNS.log(f"Pair action for {pair_addr}", RNS.LOG_DEBUG) From a911996070d1990a2487ca948239a8fcad393fd4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 01:46:51 +0100 Subject: [PATCH 181/271] Build native LXST filterlib.so and inject into APK --- recipes/lxst/__init__.py | 33 +++++++++++++++++++++++++++++++++ sbapp/Makefile | 10 ++++++++-- sbapp/buildozer.spec | 4 ++-- 3 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 recipes/lxst/__init__.py diff --git a/recipes/lxst/__init__.py b/recipes/lxst/__init__.py new file mode 100644 index 0000000..ec6639c --- /dev/null +++ b/recipes/lxst/__init__.py @@ -0,0 +1,33 @@ +""" +Android Bluetooth Low Energy +""" +from pythonforandroid.recipe import PythonRecipe +from pythonforandroid.toolchain import current_directory, info, shprint +import sh +from os.path import join + + +class LXSTRecipe(PythonRecipe): + name = 'lxst_recipe' + depends = ['python3', 'setuptools', 'android', "cffi"] + call_hostpython_via_targetpython = False + install_in_hostpython = True + + def prepare_build_dir(self, arch): + build_dir = self.get_build_dir(arch) + assert build_dir.endswith(self.name) + shprint(sh.rm, '-rf', build_dir) + shprint(sh.mkdir, build_dir) + + srcs = ('/home/markqvist/Information/Source/LXST/LXST', '/home/markqvist/Information/Source/LXST/setup.py', '/home/markqvist/Information/Source/LXST/README.md') + + for filename in srcs: + print(f"Copy {join(self.get_recipe_dir(), filename)} to {build_dir}") + shprint(sh.cp, '-a', join(self.get_recipe_dir(), filename), + build_dir) + + def postbuild_arch(self, arch): + super(LXSTRecipe, self).postbuild_arch(arch) + info("LXST native build completed") + +recipe = LXSTRecipe() diff --git a/sbapp/Makefile b/sbapp/Makefile index 8eacb30..cb54e64 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -47,6 +47,11 @@ injectxml: cp patches/AndroidManifest.tmpl.xml .buildozer/android/platform/build-arm64-v8a/dists/sideband/templates/ cp patches/p4a_build.py .buildozer/android/platform/build-arm64-v8a/dists/sideband/build.py +injectlibs: + @(echo Injecting native libs...) + cp .buildozer/android/platform/build-arm64-v8a/dists/sideband/_python_bundle__arm64-v8a/_python_bundle/site-packages/LXST/filterlib.so LXST/ + @(sleep 1) + debug: buildozer android debug @@ -83,10 +88,11 @@ release: postbuild: $(MAKE) cleanrns + -(rm ../LXST/filterlib.so) -apk: prepare prebake pacthfiles fetchshare release postbuild +apk: prepare prebake pacthfiles fetchshare injectlibs release postbuild -devapk: prepare prebake pacthfiles fetchshare debug postbuild +devapk: prepare prebake pacthfiles fetchshare injectlibs debug postbuild version: @(echo $$(python ./gv.py)) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index c5bbffe..af3020e 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -4,7 +4,7 @@ package.name = sideband package.domain = io.unsigned source.dir = . -source.include_exts = py,png,jpg,jpeg,webp,ttf,kv,pyi,typed,so,0,1,2,3,atlas,frag,html,css,js,whl,zip,gz,woff2,pdf,epub,pgm,opus +source.include_exts = py,png,jpg,jpeg,webp,ttf,kv,pyi,typed,so,0,1,2,3,atlas,frag,html,css,js,whl,zip,gz,woff2,pdf,epub,pgm,opus,h,c source.include_patterns = assets/*,assets/fonts/*,assets/audio/notifications/*,share/* source.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements,precompiled/*,parked/*,./setup.py,Makef*,./Makefile,Makefile,bin/*,build/*,dist/*,__pycache__/* @@ -12,7 +12,7 @@ version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py android.numeric_version = 20251122 -requirements = kivy==2.3.0,libbz2,sqlite3,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 +requirements = kivy==2.3.0,libbz2,sqlite3,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,lxst android.gradle_dependencies = com.android.support:support-compat:28.0.0 #android.enable_androidx = True From 194efbbf223f10529dc48f2fbc4b5e218883124b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 01:56:16 +0100 Subject: [PATCH 182/271] Updated version --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 6e06dd5..65ade54 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.8.1" +__version__ = "1.8.2" __variant__ = "" import sys From 3f1cdd27246a042bb11efa2291bcb61398087de6 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 01:58:59 +0100 Subject: [PATCH 183/271] Updated dependency versions --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 7617665..86332d0 100644 --- a/setup.py +++ b/setup.py @@ -123,7 +123,7 @@ setuptools.setup( "ffpyplayer", "sh", "numpy>=2.0.0", - "lxst>=0.4.1", + "lxst>=0.4.2", "mistune>=3.0.2", "beautifulsoup4", "pycodec2>=4.1.0;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", From 581e8073c534a06e0a847bba91873b611f8c0a1e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 11:38:19 +0100 Subject: [PATCH 184/271] Improved call status feedback and decreased call connect timeout --- sbapp/main.py | 17 +++++++++++------ sbapp/sideband/core.py | 5 +++-- sbapp/sideband/voice.py | 8 ++++++-- sbapp/ui/voice.py | 11 +++++++---- 4 files changed, 27 insertions(+), 14 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 65ade54..0b4c163 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1504,11 +1504,17 @@ class SidebandApp(MDApp): if service_voice_running: self.sideband.voice_running = True else: self.sideband.voice_running = False - incoming_call = self.sideband.getstate("voice.incoming_call") - if incoming_call: - self.sideband.setstate("voice.incoming_call", None) - if RNS.vendor.platformutils.is_android(): toast(f"Call from {incoming_call}") - else: toast(f"Call from {incoming_call}", duration=7) + if self.sideband.voice_running: + incoming_call = self.sideband.getstate("voice.incoming_call") + ended_call = self.sideband.getstate("voice.ongoing_ended") + if incoming_call: + self.sideband.setstate("voice.incoming_call", None) + dn = multilingual_markup(escape_markup(str(incoming_call)).encode("utf-8")).decode("utf-8") + toast(f"Call from {dn}", duration=4) + + if ended_call: + self.sideband.setstate("voice.ongoing_ended", False) + toast("Call ended", duration=4) if self.root.ids.screen_manager.current == "messages_screen": self.messages_view.update() @@ -5866,7 +5872,6 @@ class SidebandApp(MDApp): if self.sideband.voice_running: if self.sideband.telephone.is_ringing or self.sideband.telephone.is_in_call: self.sideband.telephone.hangup() - toast("Call ended") ### Telemetry Screen ###################################### diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index e84514c..4a33e77 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5475,10 +5475,11 @@ class SidebandCore(): def missed_call(self, remote_identity): display_name = self.voice_display_name(remote_identity.hash) self.setstate("voice.missed_call", display_name) - # if self.gui_foreground(): RNS.log("Squelching call notification since GUI is in foreground", RNS.LOG_DEBUG) - # else: self.notify(title="Missed voice call", content=f"From {display_name}", group="LXST.Telephony", context_id="incoming_call") self.notify(title="Missed call", content=f"From {display_name}", group="lxst.telephony.call", context_id="incoming_call") + def ended_call(self, remote_identity): + self.setstate("voice.ongoing_ended", True) + rns_config = """# This template is used to generate a # running configuration for Sideband's # internal RNS instance. Incorrect changes diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 1721a43..92dcabd 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -213,8 +213,12 @@ class ReticulumTelephone(): self.direction = None self.state = self.STATE_AVAILABLE - if call_was_connecting: self.log_call("outgoing-failure", remote_identity) - elif was_in_call: self.log_call("ongoing-ended", remote_identity) + if call_was_connecting: + self.log_call("outgoing-failure", remote_identity) + self.owner.setstate("voice.connection_failure", True) + elif was_in_call: + self.log_call("ongoing-ended", remote_identity) + self.owner.ended_call(remote_identity) elif was_ringing: self.log_call("incoming-missed", remote_identity) self.owner.missed_call(remote_identity) diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 80e05aa..4060a6c 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -111,6 +111,10 @@ class Voice(): if telephone.caller: ih.text = RNS.hexrep(telephone.caller.hash, delimit=False) if telephone.active_profile: self.call_profile = telephone.active_profile + if self.app.sideband.getstate("voice.connection_failure"): + self.app.sideband.setstate("voice.connection_failure", False) + toast("Could not connect call", duration=5) + else: db.disabled = True; db.text = "Voice calls disabled" ih.disabled = True @@ -212,12 +216,11 @@ class Voice(): if self.app.sideband.telephone.is_available: destination_hash = RNS.Destination.hash_from_name_and_identity("lxst.telephony", self.dial_target) - if not RNS.Transport.has_path(destination_hash): - self.request_path(destination_hash) - + if not RNS.Transport.has_path(destination_hash): self.request_path(destination_hash) else: RNS.log(f"Calling {RNS.prettyhexrep(self.dial_target)}...", RNS.LOG_DEBUG) - self.app.sideband.telephone.dial(self.dial_target, profile=self.call_profile) + if self.app.sideband.telephone.dial(self.dial_target, profile=self.call_profile) == "no_path": + self.request_path(destination_hash) self.update_call_status() elif self.app.sideband.telephone.is_in_call or self.app.sideband.telephone.call_is_connecting: From 1ae7cea2b60b29efd6fb110e5ddce3069236c06c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 13:38:20 +0100 Subject: [PATCH 185/271] Added in-call profile switching for voice calls. Improved voice call UI feedback on establishment failure. --- sbapp/sideband/core.py | 1 + sbapp/sideband/voice.py | 16 +++++++++++++--- sbapp/ui/voice.py | 28 +++++++++++++++++++++++----- setup.py | 2 +- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 4a33e77..f77a251 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2026,6 +2026,7 @@ class SidebandCore(): elif "telephone_announce" in call: connection.send(self.telephone.announce() if self.telephone else False) elif "telephone_get_call_log" in call: connection.send(self.telephone.get_call_log() if self.telephone else []) elif "telephone_clear_call_log" in call: connection.send(self.telephone.clear_call_log() if self.telephone else False) + elif "telephone_switch_profile" in call: connection.send(self.telephone.switch_profile(call["telephone_switch_profile"]) if self.telephone else False) else: connection.send(None) diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py index 92dcabd..9e39ced 100644 --- a/sbapp/sideband/voice.py +++ b/sbapp/sideband/voice.py @@ -39,6 +39,7 @@ class ReticulumTelephone(): self.direction = None self.last_input = None self.first_run = False + self.user_hung_up = False self.ringtone_path = None self.speaker_device = speaker self.microphone_device = microphone @@ -110,7 +111,10 @@ class ReticulumTelephone(): self.telephone.teardown() self.telephone = None - def hangup(self): self.telephone.hangup() + def hangup(self): + self.user_hung_up = True + self.telephone.hangup() + def answer(self): self.telephone.answer(self.caller) def set_busy(self, busy): self.telephone.set_busy(busy) def set_low_latency_output(self, enabled): self.telephone.set_low_latency_output(enabled) @@ -192,6 +196,9 @@ class ReticulumTelephone(): self.direction = "to" self.telephone.call(self.caller, profile=profile) + def switch_profile(self, profile): + self.telephone.switch_profile(profile) + def ringing(self, remote_identity): if self.hw_state == self.HW_STATE_SLEEP: self.hw_state = self.HW_STATE_IDLE self.state = self.STATE_RINGING @@ -205,6 +212,8 @@ class ReticulumTelephone(): call_was_connecting = self.call_is_connecting was_ringing = self.is_ringing was_in_call = self.is_in_call + user_hung_up = self.user_hung_up + self.user_hung_up = False if self.is_in_call or self.is_ringing or self.call_is_connecting: if self.is_in_call: RNS.log(f"Call with {RNS.prettyhexrep(self.caller.hash)} ended\n", RNS.LOG_DEBUG) @@ -215,7 +224,7 @@ class ReticulumTelephone(): if call_was_connecting: self.log_call("outgoing-failure", remote_identity) - self.owner.setstate("voice.connection_failure", True) + if not user_hung_up: self.owner.setstate("voice.connection_failure", True) elif was_in_call: self.log_call("ongoing-ended", remote_identity) self.owner.ended_call(remote_identity) @@ -284,4 +293,5 @@ class ReticulumTelephoneProxy(): def set_low_latency_output(self, enabled): return self.owner.service_rpc_request({"telephone_set_low_latency_output": enabled}) def announce(self): return self.owner.service_rpc_request({"telephone_announce": True}) def get_call_log(self): return self.owner.service_rpc_request({"telephone_get_call_log": True}) - def clear_call_log(self): return self.owner.service_rpc_request({"telephone_clear_call_log": True}) \ No newline at end of file + def clear_call_log(self): return self.owner.service_rpc_request({"telephone_clear_call_log": True}) + def switch_profile(self, profile): return self.owner.service_rpc_request({"telephone_switch_profile": profile}) \ No newline at end of file diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py index 4060a6c..b54fb10 100644 --- a/sbapp/ui/voice.py +++ b/sbapp/ui/voice.py @@ -96,7 +96,8 @@ class Voice(): ih.disabled = True rb.disabled = True db.disabled = False - pb.disabled = True + if telephone.call_is_connecting: pb.disabled = True + if telephone.is_in_call: pb.disabled = False db.text = "Hang up" db.icon = "phone-hangup" if telephone.active_profile: self.call_profile = telephone.active_profile @@ -183,10 +184,24 @@ class Voice(): toast("Path request timed out") def call_profile_action(self, sender=None): - pb = self.screen.ids.call_profile_button - self.call_profile = Profiles.next_profile(self.call_profile) - pb.text = Profiles.profile_abbrevation(self.call_profile) - toast(f"Call Profile: {Profiles.profile_name(self.call_profile)}") + if self.app.sideband.telephone.is_in_call: self.switch_profile_action() + else: + pb = self.screen.ids.call_profile_button + self.call_profile = Profiles.next_profile(self.call_profile) + pb.text = Profiles.profile_abbrevation(self.call_profile) + toast(f"Call Profile: {Profiles.profile_name(self.call_profile)}") + + def switch_profile_action(self, sender=None): + if self.initial_call_profile == None: self.initial_call_profile = self.call_profile + if self.initial_call_profile < Profiles.QUALITY_MEDIUM: alt_profile = Profiles.QUALITY_MEDIUM + else: alt_profile = Profiles.BANDWIDTH_LOW + switch_profiles = [alt_profile, self.initial_call_profile] + if self.call_profile == switch_profiles[0]: + RNS.log(f"Switching to {Profiles.profile_name(switch_profiles[1])}", RNS.LOG_DEBUG) + self.app.sideband.telephone.switch_profile(switch_profiles[1]) + else: + RNS.log(f"Switching to {Profiles.profile_name(switch_profiles[0])}", RNS.LOG_DEBUG) + self.app.sideband.telephone.switch_profile(switch_profiles[0]) def clear_log_action(self, sender=None): self.app.sideband.telephone.clear_call_log() @@ -210,6 +225,7 @@ class Voice(): if self.app.sideband.voice_running: if self.app.sideband.telephone.is_ringing: self.app.sideband.telephone.hangup() + self.initial_call_profile = None def dial_action(self, sender=None): if self.app.sideband.voice_running: @@ -233,6 +249,8 @@ class Voice(): self.app.sideband.telephone.answer() self.update_call_status() + self.initial_call_profile = None + ### Settings screen ###################################### diff --git a/setup.py b/setup.py index 86332d0..28c14fc 100644 --- a/setup.py +++ b/setup.py @@ -126,7 +126,7 @@ setuptools.setup( "lxst>=0.4.2", "mistune>=3.0.2", "beautifulsoup4", - "pycodec2>=4.1.0;sys.platform!='Windows' and sys.platform!='win32' and sys.platform!='darwin'", + "pycodec2>=4.1.0", "pyaudio;sys.platform=='linux'", "pyobjus;sys.platform=='darwin'", "pyogg;sys.platform=='Windows' and sys.platform!='win32'", From 314febee3a49ef8bbd2bfaeafdd80a6abd00fa83 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 18:43:32 +0100 Subject: [PATCH 186/271] Added message size rendering limit to conversation view. Fixes #93. --- sbapp/ui/messages.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index acf8230..f32df78 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -49,6 +49,8 @@ if RNS.vendor.platformutils.is_darwin(): from kivy.lang.builder import Builder from kivymd.uix.list import OneLineIconListItem, IconLeftWidget +MSG_RENDER_LIMIT = 11000 + class DialogItem(OneLineIconListItem): divider = None icon = StringProperty() @@ -735,8 +737,11 @@ class Messages(): alstr = RNS.prettysize(len(audio_field[1])) heading_str += f"\n[b]Audio Message[/b] ({alstr})" + final_content = pre_content+message_markup.decode("utf-8")+extra_content + if len(final_content) > MSG_RENDER_LIMIT: + final_content = pre_content+"[i]The content of this message is too large to display in the message stream. You can copy the message content into another program by using the context menu of this message, and selecting [b]Copy[/b].[/i]"+extra_content item = ListLXMessageCard( - text=pre_content+message_markup.decode("utf-8")+extra_content, + text=final_content, heading=heading_str, md_bg_color=msg_color, ) From 0bf7fce688757a71e7581456273720477c9203eb Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 19:47:07 +0100 Subject: [PATCH 187/271] Fixed display resolution getter on rotated displays --- sbapp/main.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 0b4c163..1e0b5cc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -49,11 +49,26 @@ def get_display_res(): else: try: import subprocess - cmd_xrandr = subprocess.Popen(['xrandr'], stdout=subprocess.PIPE) - cmd_grep = subprocess.Popen(['grep', '*'], stdin=cmd_xrandr.stdout, stdout=subprocess.PIPE) + # Try to get connected and primary display + cmd_xrandr = subprocess.Popen(["xrandr"], stdout=subprocess.PIPE) + cmd_grep = subprocess.Popen(["grep", " connected primary"], stdin=cmd_xrandr.stdout, stdout=subprocess.PIPE) cmd_xrandr.stdout.close(); res_bytes, _ = cmd_grep.communicate() - resolution = res_bytes.split()[0] - width, height = resolution.split(b'x') + if not (len(res_bytes) > 25 and b"x" in res_bytes): + # Try to get connected display + cmd_xrandr = subprocess.Popen(["xrandr"], stdout=subprocess.PIPE) + cmd_grep = subprocess.Popen(["grep", " connected"], stdin=cmd_xrandr.stdout, stdout=subprocess.PIPE) + cmd_xrandr.stdout.close(); res_bytes, _ = cmd_grep.communicate() + + resolution_es = res_bytes.split() + for e in resolution_es: + if b"x" in e: + if b"+" in e: e = e.split(b"+")[0] + cs = e.split(b"x") + if len(cs) == 2: + resolution = e + break + + width, height = resolution.split(b"x") app_ui_dsp_width = int(width) app_ui_dsp_height = int(height) return app_ui_dsp_width, app_ui_dsp_height From 5fc5eec700cba7991c7b3333ad44711ad422332b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 21:06:09 +0100 Subject: [PATCH 188/271] Workaround for Kivy/SDL window positioning bug --- sbapp/main.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 1e0b5cc..dab02cc 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -145,7 +145,7 @@ def apply_ui_scale(): with open(ui_wcfg_path, "r") as sf: window_config = sf.readline().split() if window_config != None: - if type(window_config) == list and len(window_config) == 5: + if type(window_config) == list and len(window_config) >= 5: app_ui_window_config = window_config @@ -182,6 +182,9 @@ def patch_sdl_window_events(patch_target): # # End of Kivy/SDL2 patch ########################## +window_x_offset = 0 +window_y_offset = 0 + if args.export_settings: from .sideband.core import SidebandCore sideband = SidebandCore( @@ -354,12 +357,15 @@ else: window_height_target = int(WINDOW_DEFAULT_HEIGHT) # But use saved window configuration if possible - if type(app_ui_window_config) == list and len(app_ui_window_config) == 5: + if type(app_ui_window_config) == list and len(app_ui_window_config) >= 5: window_width_target = int(app_ui_window_config[0]) window_height_target = int(app_ui_window_config[1]) window_target_x = int(app_ui_window_config[2]) window_target_y = int(app_ui_window_config[3]) window_state = app_ui_window_config[4] + + if len(app_ui_window_config) > 5: window_x_offset = int(app_ui_window_config[5]) + if len(app_ui_window_config) > 6: window_y_offset = int(app_ui_window_config[6]) if not window_state in ["maximized", "minimized", "normal"]: window_state = "normal" if window_target_x < 0: window_target_x = 0 @@ -379,8 +385,10 @@ else: if window_target_x and window_target_y: Config.set('graphics', 'position', 'custom') - Config.set("graphics", "left", str(window_target_x)) - Config.set("graphics", "top", str(window_target_y)) + Config.set("graphics", "left", str(window_target_x+window_x_offset)) + Config.set("graphics", "top", str(window_target_y+window_y_offset)) + _window_init_x = window_target_x + _window_init_y = window_target_y if window_state == "maximized": Config.set("graphics", "window_state", "maximized") @@ -893,7 +901,7 @@ class SidebandApp(MDApp): def save_window_config(self): try: if not RNS.vendor.platformutils.is_android(): - wcfg = f"{Window.width} {Window.height} {Window.left} {Window.top} {self.window_state}" + wcfg = f"{Window.width} {Window.height} {Window.left} {Window.top} {self.window_state} {window_x_offset} {window_y_offset}" if app_ui_wcfg_path == None: RNS.log("No path to UI window config file could be found, cannot save window config", RNS.LOG_ERROR) else: try: From 467b63671c61d1108427b99eecddf985e19ed299 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 24 Nov 2025 23:50:24 +0100 Subject: [PATCH 189/271] Updated readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4298051..1f864e6 100644 --- a/README.md +++ b/README.md @@ -59,10 +59,10 @@ sudo apt install python3-pip python3-pyaudio libopusfile0 codec2 xclip xsel sudo apt install python3-pip python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel # For Manjaro and derivatives -pamac install python-pyaudio codec2 xclip xsel +pamac install python-pyaudio opusfile codec2 xclip xsel # For Arch and derivatives -sudo pacman -Sy python-pyaudio codec2 xclip xsel +sudo pacman -Sy python-pyaudio opusfile codec2 xclip xsel ``` From b97bba07dbab530bb274feb78ee144693cfffad3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 10:53:51 +0100 Subject: [PATCH 190/271] Updated readme --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 1f864e6..bdce201 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,20 @@ For your Android devices, you can download an [APK on the latest release page](h After the application is installed on your Android device, it is also possible to pull updates directly through the **Repository** section of the application. +The Sideband APK file is always signed with a consistent signing certificate directly at build time. After downloading the APK, you can verify that it has not been modified, by checking that the APK file's signing certificate matches these hashes: + +```text +SHA-256 digest: 1c65f01f586a2b73ac4eb8bf48730b3899d046447185fd9d005685a4af20cdea +SHA-1 digest: 4ab9269c320c72f4e4057ec7ea5acade320c2a48 +MD5 digest: 09afff8c505089a544ad2bf371c29422 +``` + +Sideband will never be released on app store platforms that does not support complete control of the APK signing directly from the developer. If you download Sideband from any other source than this repository, and the certificate hashes do not match, **do not install it**. + +The Android version of Sideband has been carefully set up to **not** use any Android APIs or functionality that is dependent on Google (or other vendor-specific) components or libraries. It uses only raw Android OS APIs, and accesses them directly, instead of through "compatibility", "support" or "helper" libraries, which can often hijack application data flow into privacy-compromising pipelines controlled by Google or other vendors. + +This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs. + ## On Linux On all Linux-based operating systems, Sideband is available as a `pip`/`pipx` package. This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. From 1311b99ba025d7e1b04eb5dc2c1829de90f9f195 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 10:55:03 +0100 Subject: [PATCH 191/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bdce201..bd37ebf 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ For your Android devices, you can download an [APK on the latest release page](h After the application is installed on your Android device, it is also possible to pull updates directly through the **Repository** section of the application. -The Sideband APK file is always signed with a consistent signing certificate directly at build time. After downloading the APK, you can verify that it has not been modified, by checking that the APK file's signing certificate matches these hashes: +The Sideband APK file is always signed with a consistent signing certificate directly at build time. Before installing it for the first time, you can verify that the APK has not been modified, by checking that the APK file's signing certificate matches these hashes: ```text SHA-256 digest: 1c65f01f586a2b73ac4eb8bf48730b3899d046447185fd9d005685a4af20cdea From 13be8031d935f22f502d1b4589cf766c891eaeea Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 10:55:35 +0100 Subject: [PATCH 192/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bd37ebf..02d8d61 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ MD5 digest: 09afff8c505089a544ad2bf371c29422 Sideband will never be released on app store platforms that does not support complete control of the APK signing directly from the developer. If you download Sideband from any other source than this repository, and the certificate hashes do not match, **do not install it**. -The Android version of Sideband has been carefully set up to **not** use any Android APIs or functionality that is dependent on Google (or other vendor-specific) components or libraries. It uses only raw Android OS APIs, and accesses them directly, instead of through "compatibility", "support" or "helper" libraries, which can often hijack application data flow into privacy-compromising pipelines controlled by Google or other vendors. +The Android version of Sideband has been carefully set up to **not** use any Android APIs or functionality that are dependent on Google (or other vendor-specific) components or libraries. It uses only raw Android OS APIs, and accesses them directly, instead of through "compatibility", "support" or "helper" libraries, which can often hijack application data flow into privacy-compromising pipelines controlled by Google or other vendors. This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs. From 0a781464a64b67fee0e985ff52156570ef17edd8 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 10:56:12 +0100 Subject: [PATCH 193/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 02d8d61..d36f391 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Sideband will never be released on app store platforms that does not support com The Android version of Sideband has been carefully set up to **not** use any Android APIs or functionality that are dependent on Google (or other vendor-specific) components or libraries. It uses only raw Android OS APIs, and accesses them directly, instead of through "compatibility", "support" or "helper" libraries, which can often hijack application data flow into privacy-compromising pipelines controlled by Google or other vendors. -This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs. +This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs, such as GrapheneOS. ## On Linux From 0e8b1d41cf70b6d9551ce2119cbfa4788ad79fc0 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 10:57:01 +0100 Subject: [PATCH 194/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d36f391..0abfdb2 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Sideband will never be released on app store platforms that does not support com The Android version of Sideband has been carefully set up to **not** use any Android APIs or functionality that are dependent on Google (or other vendor-specific) components or libraries. It uses only raw Android OS APIs, and accesses them directly, instead of through "compatibility", "support" or "helper" libraries, which can often hijack application data flow into privacy-compromising pipelines controlled by Google or other vendors. -This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs, such as GrapheneOS. +This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs, such as GrapheneOS, de-googled devices and privacy-improved Android versions. ## On Linux From beb5788e86e367b59a42ccb05dd27375d3a8a3c4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 10:57:47 +0100 Subject: [PATCH 195/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0abfdb2..7af43ff 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Sideband will never be released on app store platforms that does not support com The Android version of Sideband has been carefully set up to **not** use any Android APIs or functionality that are dependent on Google (or other vendor-specific) components or libraries. It uses only raw Android OS APIs, and accesses them directly, instead of through "compatibility", "support" or "helper" libraries, which can often hijack application data flow into privacy-compromising pipelines controlled by Google or other vendors. -This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs, such as GrapheneOS, de-googled devices and privacy-improved Android versions. +This also means that Sideband is designed to be fully compatible with custom (and more privacy-friendly) Android versions and ROMs, such as GrapheneOS, de-googled devices and other custom ROMs. ## On Linux From ab42d8d502ff785fd5095b13aeea87c7dc7ff6fc Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 25 Nov 2025 11:03:53 +0100 Subject: [PATCH 196/271] Updated readme --- README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7af43ff..2272c88 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,9 @@ This also means that Sideband is designed to be fully compatible with custom (an ## On Linux -On all Linux-based operating systems, Sideband is available as a `pip`/`pipx` package. This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. +On all Linux-based operating systems, Sideband is available as a `pip`/`pipx` package. You can either pull and install Sideband directly from the `pip` repository, or download and install locally using `whl` package from the [latest release page](https://github.com/markqvist/Sideband/releases/latest). + +This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. #### Basic Installation You will first need to install a few dependencies for voice calls, audio messaging and Codec2 support to work: @@ -126,8 +128,8 @@ You can also install Sideband in various alternative ways: pipx install sbapp # Or, if you intend to run Sideband in headless -# daemon mode, you can also install it without -# any of the normal UI dependencies: +# daemon or console mode, you can also install +# it without any of the normal UI dependencies: pip install sbapp --no-dependencies # In the case of using --no-dependencies, you @@ -135,6 +137,9 @@ pip install sbapp --no-dependencies # and LXMF dependencies: pip install rns lxmf +# Dependencies can vary slightly on older OS +# versions, due to different package names. + # Install Sideband on Debian 11 and derivatives: sudo apt install python3-pip python3-pyaudio python3-dev build-essential libopusfile0 portaudio19-dev codec2 xclip xsel pip install sbapp @@ -214,8 +219,6 @@ If you do not already have Reticulum connectivity set up on your computer or loc For more advanced setups, including the ability to run Sideband in headless daemon mode, enable debug logging output, configuration import and export and more, you may want to install it from the source package via `pip` instead. -**Please note!** The very latest Python release, Python 3.13 is currently **not** compatible with the Kivy framework, that Sideband uses to render its user interface. If your version of macOS uses Python 3.13 as its default Python installation, you will need to install an earlier version as well. Using [the latest release of Python 3.12](https://www.python.org/downloads/release/python-3127/) is recommended. - To install Sideband via `pip`, follow these instructions: ```bash From 8541fce0289dd9f520e882e7ce8cbe5f185f436b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 26 Nov 2025 13:18:38 +0100 Subject: [PATCH 197/271] Use LXST to play audio message contents. Adds support for audio message playback on Windows and macOS. --- sbapp/main.py | 153 ++++++++++++++--------------------------- sbapp/sideband/core.py | 115 ++++++++++++++----------------- 2 files changed, 100 insertions(+), 168 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index dab02cc..19203dd 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2422,116 +2422,66 @@ class SidebandApp(MDApp): self.compat_error_dialog.open() def play_audio_field(self, audio_field): - if RNS.vendor.platformutils.is_darwin(): - if self.compat_error_dialog == None: - def cb(sender): - self.compat_error_dialog.dismiss() - self.compat_error_dialog = MDDialog( - title="Unsupported Feature on macOS", - text="Audio message functionality is currently only implemented on Linux and Android. Please support the development if you need this feature on macOS.", - buttons=[ - MDRectangleFlatButton( - text="OK", - font_size=dp(18), - on_release=cb - ) - ], - ) - self.compat_error_dialog.open() - return - elif RNS.vendor.platformutils.is_windows(): - if self.compat_error_dialog == None: - def cb(sender): - self.compat_error_dialog.dismiss() - self.compat_error_dialog = MDDialog( - title="Unsupported Feature on Windows", - text="Audio message functionality is currently only implemented on Linux and Android. Please support the development if you need this feature on Windows.", - buttons=[ - MDRectangleFlatButton( - text="OK", - font_size=dp(18), - on_release=cb - ) - ], - ) - self.compat_error_dialog.open() - return - else: - try: - temp_path = None - if self.last_msg_audio != audio_field[1]: - RNS.log("Reloading audio source", RNS.LOG_DEBUG) - if len(audio_field[1]) > 10: - self.last_msg_audio = audio_field[1] + try: + if self.msg_sound != None and self.msg_sound.playing: + RNS.log("Stopping playback", RNS.LOG_DEBUG) + self.msg_sound.stop() + return + + temp_path = None + if self.last_msg_audio != audio_field[1]: + RNS.log("Reloading audio source", RNS.LOG_DEBUG) + if len(audio_field[1]) > 10: self.last_msg_audio = audio_field[1] + else: + self.last_msg_audio = None + return + + if audio_field[0] == LXMF.AM_OPUS_OGG: + temp_path = self.sideband.rec_cache+"/msg.ogg" + with open(temp_path, "wb") as af: af.write(self.last_msg_audio) + + elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200: + temp_path = self.sideband.rec_cache+"/msg.ogg" + from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 + + target_rate = 8000 + if RNS.vendor.platformutils.is_linux(): target_rate = 48000 + + if detect_codec2(): + if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate): RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG) + else: RNS.log("OGG write failed", RNS.LOG_DEBUG) else: self.last_msg_audio = None + self.display_codec2_error() return + + else: raise NotImplementedError(audio_field[0]) - if audio_field[0] == LXMF.AM_OPUS_OGG: - temp_path = self.sideband.rec_cache+"/msg.ogg" - with open(temp_path, "wb") as af: - af.write(self.last_msg_audio) + if self.msg_sound == None: + from LXST.Primitives.Players import FilePlayer + self.msg_sound = FilePlayer() - elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200: - temp_path = self.sideband.rec_cache+"/msg.ogg" - from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 - - target_rate = 8000 - if RNS.vendor.platformutils.is_linux(): - target_rate = 48000 + self.msg_sound.set_source(temp_path) - if detect_codec2(): - if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate): - RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG) - else: - RNS.log("OGG write failed", RNS.LOG_DEBUG) - else: - self.last_msg_audio = None - self.display_codec2_error() - return - - else: - raise NotImplementedError(audio_field[0]) + if self.msg_sound != None: + RNS.log("Starting playback", RNS.LOG_DEBUG) + self.msg_sound.play() + else: + RNS.log("Playback was requested, but no audio data was loaded for playback", RNS.LOG_ERROR) - if self.msg_sound == None: - if RNS.vendor.platformutils.is_android(): - from plyer import audio - self.request_microphone_permission() - else: - from sbapp.plyer import audio - - self.msg_sound = audio - - self.msg_sound._file_path = temp_path - self.msg_sound.reload() - - if self.msg_sound != None and self.msg_sound.playing(): - RNS.log("Stopping playback", RNS.LOG_DEBUG) - self.msg_sound.stop() - else: - if self.msg_sound != None: - RNS.log("Starting playback", RNS.LOG_DEBUG) - self.msg_sound.play() - else: - RNS.log("Playback was requested, but no audio data was loaded for playback", RNS.LOG_ERROR) - - except Exception as e: - RNS.log("Error while playing message audio:"+str(e)) - RNS.trace_exception(e) + except Exception as e: + RNS.log("Error while playing message audio:"+str(e)) + RNS.trace_exception(e) def message_ptt_down_action(self, sender=None): - if self.sideband.ui_recording: - return + if self.sideband.ui_recording: return self.sideband.ui_started_recording() - if self.sideband.config["hq_ptt"]: - self.audio_msg_mode = LXMF.AM_OPUS_OGG - else: - self.audio_msg_mode = LXMF.AM_CODEC2_2400 + if self.sideband.config["hq_ptt"]: self.audio_msg_mode = LXMF.AM_OPUS_OGG + else: self.audio_msg_mode = LXMF.AM_CODEC2_2400 self.message_attach_action(attach_type="audio", nodialog=True) - if self.rec_dialog == None: - self.message_init_rec_dialog() + if self.rec_dialog == None: self.message_init_rec_dialog() self.rec_dialog.recording = True el_button = self.messages_view.ids.message_ptt_button el_icon = self.messages_view.ids.message_ptt_button.children[0].children[1] @@ -2540,14 +2490,12 @@ class SidebandApp(MDApp): el_button.line_color=mdc("Orange","400") el_icon.theme_text_color="Custom" el_icon.text_color=mdc("Orange","400") - def cb(dt): - self.msg_audio.start() + def cb(dt): self.msg_audio.start() Clock.schedule_once(cb, 0.15) def message_ptt_up_action(self, sender=None): - if not self.sideband.ui_recording: - return + if not self.sideband.ui_recording: return self.rec_dialog.recording = False el_button = self.messages_view.ids.message_ptt_button @@ -2558,8 +2506,7 @@ class SidebandApp(MDApp): el_icon.theme_text_color="Custom" el_icon.text_color=mdc("BlueGray","500") def cb_s(dt): - try: - self.msg_audio.stop() + try: self.msg_audio.stop() except Exception as e: RNS.log("An error occurred while stopping recording: "+str(e), RNS.LOG_ERROR) RNS.trace_exception(e) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index f77a251..dc03ef0 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -152,9 +152,9 @@ class SidebandCore(): self.is_service = is_service self.is_client = is_client self.is_daemon = is_daemon - self.msg_audio = None + self.ptt_player = None + self.ptt_player_lock = threading.Lock() self.last_msg_audio = None - self.ptt_playback_lock = threading.Lock() self.ui_recording = False self.db = None self.db_lock = threading.Lock() @@ -4989,80 +4989,65 @@ class SidebandCore(): def ptt_playback(self, message): ptt_timeout = 60 event_time = time.time() - while hasattr(self, "msg_sound") and self.msg_sound != None and self.msg_sound.playing() and time.time() < event_time+ptt_timeout: - time.sleep(0.1) - time.sleep(0.5) + with self.ptt_player_lock: + time.sleep(0.2) - if self.msg_audio == None: - if RNS.vendor.platformutils.is_android(): - from plyer import audio - else: - from sbapp.plyer import audio - - RNS.log("Audio init done") - self.msg_audio = audio - try: - temp_path = None - audio_field = message.fields[LXMF.FIELD_AUDIO] - if self.last_msg_audio != audio_field[1]: - RNS.log("Reloading audio source", RNS.LOG_DEBUG) - if len(audio_field[1]) > 10: - self.last_msg_audio = audio_field[1] - else: - self.last_msg_audio = None - return - - if audio_field[0] == LXMF.AM_OPUS_OGG: - temp_path = self.rec_cache+"/msg.ogg" - with open(temp_path, "wb") as af: - af.write(self.last_msg_audio) - - elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200: - temp_path = self.rec_cache+"/msg.ogg" - from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 - - target_rate = 8000 - if RNS.vendor.platformutils.is_linux(): - target_rate = 48000 - - if detect_codec2(): - if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate): - RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG) - else: - RNS.log("OGG write failed", RNS.LOG_DEBUG) + try: + temp_path = None + audio_field = message.fields[LXMF.FIELD_AUDIO] + if self.last_msg_audio != audio_field[1]: + RNS.log("Reloading audio source", RNS.LOG_DEBUG) + if len(audio_field[1]) > 10: self.last_msg_audio = audio_field[1] else: self.last_msg_audio = None return - - else: + + if audio_field[0] == LXMF.AM_OPUS_OGG: + temp_path = self.rec_cache+"/ptt_msg.ogg" + with open(temp_path, "wb") as af: af.write(self.last_msg_audio) + + elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200: + temp_path = self.rec_cache+"/ptt_msg.ogg" + from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 + + target_rate = 8000 + if RNS.vendor.platformutils.is_linux(): target_rate = 48000 + + if detect_codec2(): + if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate): RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG) + else: RNS.log("OGG write failed", RNS.LOG_DEBUG) + else: + self.last_msg_audio = None + return + # Unimplemented audio type - pass + else: pass - self.msg_sound = self.msg_audio - self.msg_sound._file_path = temp_path - self.msg_sound.reload() + if self.ptt_player == None: + from LXST.Primitives.Players import FilePlayer + self.ptt_player = FilePlayer() + RNS.log("LXMF PTT audio init done", RNS.LOG_DEBUG) - if self.msg_sound != None: - RNS.log("Starting playback", RNS.LOG_DEBUG) - self.msg_sound.play() - else: - RNS.log("Playback was requested, but no audio data was loaded for playback", RNS.LOG_ERROR) + self.ptt_player.set_source(temp_path) - except Exception as e: - RNS.log("Error while playing message audio:"+str(e)) - RNS.trace_exception(e) + if self.ptt_player != None: + RNS.log("Starting playback", RNS.LOG_DEBUG) + self.ptt_player.play() + while self.ptt_player.playing and time.time() < event_time+ptt_timeout: time.sleep(0.25) + if self.ptt_player.playing: self.ptt_player.stop() + time.sleep(0.2) + else: + RNS.log("Playback was requested, but no audio data was loaded for playback", RNS.LOG_ERROR) + + except Exception as e: + RNS.log("Error while playing message audio:"+str(e)) + RNS.trace_exception(e) def ptt_event(self, message): def ptt_job(): - try: - self.ptt_playback_lock.acquire() - while self.ui_recording: - time.sleep(0.5) - self.ptt_playback(message) - except Exception as e: - RNS.log("Error while starting playback for PTT-enabled conversation: "+str(e), RNS.LOG_ERROR) - finally: - self.ptt_playback_lock.release() + while self.ui_recording: time.sleep(0.5) + try: self.ptt_playback(message) + except Exception as e: RNS.log("Error while starting playback for PTT-enabled conversation: "+str(e), RNS.LOG_ERROR) threading.Thread(target=ptt_job, daemon=True).start() From e3c0da03754290e5dd51263c9748ba0ad5cc0a23 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 26 Nov 2025 18:48:22 +0100 Subject: [PATCH 198/271] Use LXST for LXMF voice message handling --- sbapp/main.py | 128 ++++++++++++++++++-------------------------------- 1 file changed, 45 insertions(+), 83 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 19203dd..e0b84cf 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -28,6 +28,8 @@ import threading import RNS.vendor.umsgpack as msgpack from LXST._version import __version__ as lxst_version +from LXST.Primitives.Recorders import FileRecorder +from LXST.Primitives.Players import FilePlayer WINDOW_DEFAULT_WIDTH = 494 WINDOW_DEFAULT_HEIGHT = 800 @@ -1929,25 +1931,6 @@ class SidebandApp(MDApp): Clock.schedule_once(final_exit, 0.85) - # def test_audio_action(self, sender=None): - # if not hasattr(self, "audiotestrunning") or self.audiotestrunning == False: - # RNS.log("LXST audio backend test starting", RNS.LOG_DEBUG) - # self.audiotestrunning = True - # import LXST - # ringtone_path = os.path.join(self.sideband.asset_dir, "audio", "notifications", "soft1.opus") - # target_frame_ms = 40 - # selected_source = LXST.Sources.OpusFileSource(ringtone_path, loop=True, target_frame_ms=target_frame_ms) - # line_sink = LXST.Sinks.LineSink() - # loopback = LXST.Sources.Loopback() - # raw = LXST.Codecs.Raw() - # self.input_pipeline = LXST.Pipeline(source=selected_source, codec=raw, sink=loopback) - # self.output_pipeline = LXST.Pipeline(source=loopback, codec=raw, sink=line_sink) - # self.input_pipeline.start(); self.output_pipeline.start() - # else: - # RNS.log("LXST audio backend test stopping", RNS.LOG_DEBUG) - # self.input_pipeline.stop() - # self.audiotestrunning = False - def announce_now_action(self, sender=None): self.sideband.lxmf_announce() if self.sideband.telephone: self.sideband.telephone.announce() @@ -2458,7 +2441,6 @@ class SidebandApp(MDApp): else: raise NotImplementedError(audio_field[0]) if self.msg_sound == None: - from LXST.Primitives.Players import FilePlayer self.msg_sound = FilePlayer() self.msg_sound.set_source(temp_path) @@ -2480,9 +2462,11 @@ class SidebandApp(MDApp): if self.sideband.config["hq_ptt"]: self.audio_msg_mode = LXMF.AM_OPUS_OGG else: self.audio_msg_mode = LXMF.AM_CODEC2_2400 + if not hasattr(self, "ptt_recorder") or self.ptt_recorder == None: + self.ptt_recording_path = self.sideband.rec_cache+"/ptt_recording.ogg" + self.ptt_recorder = FileRecorder(self.ptt_recording_path) + self.message_attach_action(attach_type="audio", nodialog=True) - if self.rec_dialog == None: self.message_init_rec_dialog() - self.rec_dialog.recording = True el_button = self.messages_view.ids.message_ptt_button el_icon = self.messages_view.ids.message_ptt_button.children[0].children[1] el_button.theme_text_color="Custom" @@ -2490,14 +2474,12 @@ class SidebandApp(MDApp): el_button.line_color=mdc("Orange","400") el_icon.theme_text_color="Custom" el_icon.text_color=mdc("Orange","400") - def cb(dt): self.msg_audio.start() - Clock.schedule_once(cb, 0.15) + self.ptt_recorder.start() def message_ptt_up_action(self, sender=None): if not self.sideband.ui_recording: return - self.rec_dialog.recording = False el_button = self.messages_view.ids.message_ptt_button el_icon = self.messages_view.ids.message_ptt_button.children[0].children[1] el_button.theme_text_color="Custom" @@ -2505,40 +2487,39 @@ class SidebandApp(MDApp): el_button.line_color=mdc("BlueGray","500") el_icon.theme_text_color="Custom" el_icon.text_color=mdc("BlueGray","500") - def cb_s(dt): - try: self.msg_audio.stop() + def job(): + try: + self.ptt_recorder.stop() + self.ptt_recorder = None except Exception as e: RNS.log("An error occurred while stopping recording: "+str(e), RNS.LOG_ERROR) RNS.trace_exception(e) self.sideband.ui_stopped_recording() - if self.message_process_audio(): - if self.outbound_mode_command: - self.outbound_mode_reset() + if self.message_process_audio(self.ptt_recording_path): + if self.outbound_mode_command: self.outbound_mode_reset() self.message_send_action() - Clock.schedule_once(cb_s, 0.35) + threading.Thread(target=job, daemon=True).start() - def message_process_audio(self): + def message_process_audio(self, input_path): + from sideband.audioproc import voice_processing if self.audio_msg_mode == LXMF.AM_OPUS_OGG: - from sideband.audioproc import voice_processing - proc_path = voice_processing(self.msg_audio._file_path) + proc_path = voice_processing(input_path) if proc_path: self.attach_path = proc_path - os.unlink(self.msg_audio._file_path) + os.unlink(input_path) RNS.log("Using voice-processed OPUS data in OGG container", RNS.LOG_DEBUG) else: - self.attach_path = self.msg_audio._file_path + self.attach_path = input_path RNS.log("Using unmodified OPUS data in OGG container", RNS.LOG_DEBUG) else: ap_start = time.time() - from sideband.audioproc import voice_processing - proc_path = voice_processing(self.msg_audio._file_path) - + proc_path = voice_processing(input_path) if proc_path: opus_file = pyogg.OpusFile(proc_path) RNS.log("Using voice-processed audio for codec2 encoding", RNS.LOG_DEBUG) else: - opus_file = pyogg.OpusFile(self.msg_audio._file_path) + opus_file = pyogg.OpusFile(input_path) RNS.log("Using unprocessed audio data for codec2 encoding", RNS.LOG_DEBUG) RNS.log(f"OPUS LOAD {opus_file.frequency}Hz {opus_file.bytes_per_sample*8}bit {opus_file.channels}ch") @@ -2568,7 +2549,7 @@ class SidebandApp(MDApp): with open(export_path, "wb") as export_file: export_file.write(encoded) self.attach_path = export_path - os.unlink(self.msg_audio._file_path) + os.unlink(input_path) else: self.display_codec2_error() return False @@ -2577,19 +2558,14 @@ class SidebandApp(MDApp): def message_init_rec_dialog(self): ss = int(dp(18)) - if RNS.vendor.platformutils.is_android(): - from plyer import audio - self.request_microphone_permission() - else: - from sbapp.plyer import audio - - self.msg_audio = audio - self.msg_audio._file_path = self.sideband.rec_cache+"/recording.ogg" + if RNS.vendor.platformutils.is_android(): self.request_microphone_permission() + self.recording_player = FilePlayer() def a_rec_action(sender): - if not self.rec_dialog.recording: + if not self.rec_dialog.recording and not self.rec_dialog.recorder: self.sideband.ui_started_recording() - # RNS.log("Starting recording...") # TODO: Remove + self.rec_dialog.recorder = FileRecorder(self.rec_dialog.file_path) + RNS.log("Starting recording...") # TODO: Remove self.rec_dialog.recording = True el = self.rec_dialog.rec_item.children[0].children[0] el.ttc = el.theme_text_color; el.tc = el.text_color @@ -2597,40 +2573,40 @@ class SidebandApp(MDApp): el.text_color=mdc("Red","400") el.icon = "stop-circle" self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Stop Recording[/size]" - def cb(dt): - self.msg_audio.start() - Clock.schedule_once(cb, 0.10) + self.rec_dialog.recorder.start() else: - self.sideband.ui_stopped_recording() - # RNS.log("Stopping recording...") # TODO: Remove - self.rec_dialog.recording = False + RNS.log("Stopping recording...") # TODO: Remove + self.rec_dialog.recorder.stop() + self.rec_dialog.recorder = None + RNS.log("Recording stopped") # TODO: Remove self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Start Recording[/size]" el = self.rec_dialog.rec_item.children[0].children[0] el.icon = "record" el.text_color = self.theme_cls._get_text_color() self.rec_dialog.play_item.disabled = False self.rec_dialog.save_item.disabled = False - self.msg_audio.stop() + self.rec_dialog.recording = False + self.sideband.ui_stopped_recording() self.msg_rec_a_rec = a_rec_action def a_play(sender): - if self.rec_dialog.recording: - a_rec_action(sender) + if self.rec_dialog.recording: a_rec_action(sender) if not self.rec_dialog.playing: RNS.log("Playing recording...", RNS.LOG_DEBUG) self.rec_dialog.playing = True self.rec_dialog.play_item.children[0].children[0].icon = "stop" self.rec_dialog.play_item.text = "[size="+str(ss)+"]Stop[/size]" - self.msg_audio.play() + self.recording_player.set_source(self.rec_dialog.file_path) + self.recording_player.play() else: RNS.log("Stopping playback...", RNS.LOG_DEBUG) self.rec_dialog.playing = False self.rec_dialog.play_item.children[0].children[0].icon = "play" self.rec_dialog.play_item.text = "[size="+str(ss)+"]Play[/size]" - self.msg_audio.stop() + self.recording_player.stop() self.msg_rec_a_play = a_play @@ -2640,30 +2616,16 @@ class SidebandApp(MDApp): self.rec_dialog.play_item.children[0].children[0].icon = "play" self.rec_dialog.play_item.text = "[size="+str(ss)+"]Play[/size]" - self.msg_audio._finished_callback = a_finished + self.recording_player.finished_callback = a_finished def a_save(sender): - if self.rec_dialog.recording: - a_rec_action(sender) + if self.rec_dialog.recording: a_rec_action(sender) self.rec_dialog_is_open = False self.rec_dialog.dismiss() try: - if self.audio_msg_mode == LXMF.AM_OPUS_OGG: - from sideband.audioproc import voice_processing - proc_path = voice_processing(self.msg_audio._file_path) - if proc_path: - self.attach_path = proc_path - os.unlink(self.msg_audio._file_path) - RNS.log("Using voice-processed OPUS data in OGG container", RNS.LOG_DEBUG) - else: - self.attach_path = self.msg_audio._file_path - RNS.log("Using unmodified OPUS data in OGG container", RNS.LOG_DEBUG) - else: - self.message_process_audio() - - if self.outbound_mode_command: - self.outbound_mode_reset() + self.message_process_audio(self.rec_dialog.file_path) + if self.outbound_mode_command: self.outbound_mode_reset() self.update_message_widgets() toast("Added recorded audio to message") @@ -2679,7 +2641,6 @@ class SidebandApp(MDApp): self.rec_dialog = MDDialog( title="Record Audio", type="simple", - # text="Test\n", items=[ rec_item, play_item, @@ -2689,16 +2650,17 @@ class SidebandApp(MDApp): width_offset=dp(32), ) cancel_button.bind(on_release=self.rec_dialog.dismiss) + self.rec_dialog.recorder = None self.rec_dialog.recording = False self.rec_dialog.playing = False self.rec_dialog.rec_item = rec_item self.rec_dialog.play_item = play_item self.rec_dialog.save_item = save_item + self.rec_dialog.file_path = self.sideband.rec_cache+"/recording.ogg" def message_record_audio_action(self): ss = int(dp(18)) - if self.rec_dialog == None: - self.message_init_rec_dialog() + if self.rec_dialog == None: self.message_init_rec_dialog() else: self.rec_dialog.play_item.disabled = True From f8a84cfa58b46e44284ab2474e2c0322bab91fe1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 26 Nov 2025 18:52:03 +0100 Subject: [PATCH 199/271] Enabled full audio messaging support on Windows and macOS --- sbapp/main.py | 8 -------- sbapp/ui/messages.py | 11 +++-------- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e0b84cf..4034c9c 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2721,14 +2721,6 @@ class SidebandApp(MDApp): DialogItem(IconLeftWidget(icon="account-voice", on_release=a_audio_lb), text="[size="+str(ss)+"]Low-bandwidth Voice[/size]", on_release=a_audio_lb), DialogItem(IconLeftWidget(icon="microphone-message", on_release=a_audio_hq), text="[size="+str(ss)+"]High-quality Voice[/size]", on_release=a_audio_hq), DialogItem(IconLeftWidget(icon="file-outline", on_release=a_file), text="[size="+str(ss)+"]File Attachment[/size]", on_release=a_file)] - - if RNS.vendor.platformutils.is_windows(): - ad_items.pop(3) - ad_items.pop(3) - - if RNS.vendor.platformutils.is_darwin(): - ad_items.pop(3) - ad_items.pop(3) if RNS.vendor.platformutils.is_android() and android_api_version < 29: ad_items.pop(3) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index f32df78..af26f2d 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -246,14 +246,9 @@ class Messages(): layout = GridLayout(cols=1, spacing=dp(16), padding=dp(16), size_hint_y=None) layout.bind(minimum_height=layout.setter('height')) self.list = layout - - if RNS.vendor.platformutils.is_darwin() or RNS.vendor.platformutils.is_windows(): - self.hide_widget(self.ids.message_ptt, True) - else: - if self.ptt_enabled: - self.hide_widget(self.ids.message_ptt, False) - else: - self.hide_widget(self.ids.message_ptt, True) + + if self.ptt_enabled: self.hide_widget(self.ids.message_ptt, False) + else: self.hide_widget(self.ids.message_ptt, True) c_ts = time.time() if len(self.new_messages) > 0: From e6a4ab919a317b92e38dc3bd32f5c9b3e3b3576f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 26 Nov 2025 19:04:22 +0100 Subject: [PATCH 200/271] Fix codec2 decode target rate --- sbapp/main.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 4034c9c..ce0e7c9 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2427,9 +2427,7 @@ class SidebandApp(MDApp): temp_path = self.sideband.rec_cache+"/msg.ogg" from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 - target_rate = 8000 - if RNS.vendor.platformutils.is_linux(): target_rate = 48000 - + target_rate = 48000 if detect_codec2(): if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate): RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG) else: RNS.log("OGG write failed", RNS.LOG_DEBUG) From 6808620f0c2ab2e691178ce61d99537b389aecc9 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 26 Nov 2025 22:14:49 +0100 Subject: [PATCH 201/271] Cleanup --- recipes/ffpyplayer/__init__.py | 42 ------- recipes/ffpyplayer/setup.py.patch | 15 --- recipes/mffmpeg/__init__.py | 152 ------------------------ recipes/mffmpeg/patches/configure.patch | 11 -- sbapp/buildozer.spec | 2 +- 5 files changed, 1 insertion(+), 221 deletions(-) delete mode 100644 recipes/ffpyplayer/__init__.py delete mode 100644 recipes/ffpyplayer/setup.py.patch delete mode 100644 recipes/mffmpeg/__init__.py delete mode 100644 recipes/mffmpeg/patches/configure.patch diff --git a/recipes/ffpyplayer/__init__.py b/recipes/ffpyplayer/__init__.py deleted file mode 100644 index 53a9d7f..0000000 --- a/recipes/ffpyplayer/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -from pythonforandroid.recipe import PyProjectRecipe, Recipe -from os.path import join - - -class FFPyPlayerRecipe(PyProjectRecipe): - version = 'v4.5.2' - url = 'https://github.com/matham/ffpyplayer/archive/{version}.zip' - depends = ['python3', 'sdl2', 'ffmpeg'] - patches = ["setup.py.patch"] - opt_depends = ['openssl', 'ffpyplayer_codecs'] - - def get_recipe_env(self, arch, with_flags_in_cc=True): - env = super().get_recipe_env(arch) - - build_dir = Recipe.get_recipe('ffmpeg', self.ctx).get_build_dir(arch.arch) - env["FFMPEG_INCLUDE_DIR"] = join(build_dir, "include") - env["FFMPEG_LIB_DIR"] = join(build_dir, "lib") - - env["SDL_INCLUDE_DIR"] = join(self.ctx.bootstrap.build_dir, 'jni', 'SDL', 'include') - env["SDL_LIB_DIR"] = join(self.ctx.bootstrap.build_dir, 'libs', arch.arch) - - env["USE_SDL2_MIXER"] = '1' - - # ffpyplayer does not allow to pass more than one include dir for sdl2_mixer (and ATM is - # not needed), so we only pass the first one. - sdl2_mixer_recipe = self.get_recipe('sdl2_mixer', self.ctx) - env["SDL2_MIXER_INCLUDE_DIR"] = sdl2_mixer_recipe.get_include_dirs(arch)[0] - - # NDKPLATFORM and LIBLINK are our switches for detecting Android platform, so can't be empty - # FIXME: We may want to introduce a cleaner approach to this? - env['NDKPLATFORM'] = "NOTNONE" - env['LIBLINK'] = 'NOTNONE' - - # ffmpeg recipe enables GPL components only if ffpyplayer_codecs recipe used. - # Therefore we need to disable libpostproc if skipped. - if 'ffpyplayer_codecs' not in self.ctx.recipe_build_order: - env["CONFIG_POSTPROC"] = '0' - - return env - - -recipe = FFPyPlayerRecipe() \ No newline at end of file diff --git a/recipes/ffpyplayer/setup.py.patch b/recipes/ffpyplayer/setup.py.patch deleted file mode 100644 index 35f4b69..0000000 --- a/recipes/ffpyplayer/setup.py.patch +++ /dev/null @@ -1,15 +0,0 @@ ---- ffpyplayer/setup.py 2024-06-02 11:10:49.691183467 +0530 -+++ ffpyplayer.mod/setup.py 2024-06-02 11:20:16.220966873 +0530 -@@ -27,12 +27,6 @@ - # This sets whether or not Cython gets added to setup_requires. - declare_cython = False - --if platform in ('ios', 'android'): -- # NEVER use or declare cython on these platforms -- print('Not using cython on %s' % platform) -- can_use_cython = False --else: -- declare_cython = True - - src_path = build_path = dirname(__file__) - print(f'Source/build path: {src_path}') \ No newline at end of file diff --git a/recipes/mffmpeg/__init__.py b/recipes/mffmpeg/__init__.py deleted file mode 100644 index a51a246..0000000 --- a/recipes/mffmpeg/__init__.py +++ /dev/null @@ -1,152 +0,0 @@ -from pythonforandroid.toolchain import Recipe, current_directory, shprint -from os.path import exists, join, realpath -import sh - - -class FFMpegRecipe(Recipe): - version = 'n4.3.1' - # Moved to github.com instead of ffmpeg.org to improve download speed - url = 'https://github.com/FFmpeg/FFmpeg/archive/{version}.zip' - depends = ['sdl2'] # Need this to build correct recipe order - opts_depends = ['openssl', 'ffpyplayer_codecs'] - patches = ['patches/configure.patch'] - - def should_build(self, arch): - build_dir = self.get_build_dir(arch.arch) - return not exists(join(build_dir, 'lib', 'libavcodec.so')) - - def prebuild_arch(self, arch): - self.apply_patches(arch) - - def get_recipe_env(self, arch): - env = super().get_recipe_env(arch) - env['NDK'] = self.ctx.ndk_dir - return env - - def build_arch(self, arch): - with current_directory(self.get_build_dir(arch.arch)): - env = arch.get_env() - - # flags = ['--disable-everything'] - flags = [] - cflags = [] - ldflags = [] - - if 'openssl' in self.ctx.recipe_build_order: - flags += [ - '--enable-openssl', - '--enable-nonfree', - '--enable-protocol=https,tls_openssl', - ] - build_dir = Recipe.get_recipe( - 'openssl', self.ctx).get_build_dir(arch.arch) - cflags += ['-I' + build_dir + '/include/', - '-DOPENSSL_API_COMPAT=0x10002000L'] - ldflags += ['-L' + build_dir] - - if 'ffpyplayer_codecs' in self.ctx.recipe_build_order: - # Enable GPL - flags += ['--enable-gpl'] - - # libx264 - flags += ['--enable-libx264'] - build_dir = Recipe.get_recipe( - 'libx264', self.ctx).get_build_dir(arch.arch) - cflags += ['-I' + build_dir + '/include/'] - ldflags += ['-lx264', '-L' + build_dir + '/lib/'] - - # libshine - flags += ['--enable-libshine'] - build_dir = Recipe.get_recipe('libshine', self.ctx).get_build_dir(arch.arch) - cflags += ['-I' + build_dir + '/include/'] - ldflags += ['-lshine', '-L' + build_dir + '/lib/'] - ldflags += ['-lm'] - - # libvpx - flags += ['--enable-libvpx'] - build_dir = Recipe.get_recipe( - 'libvpx', self.ctx).get_build_dir(arch.arch) - cflags += ['-I' + build_dir + '/include/'] - ldflags += ['-lvpx', '-L' + build_dir + '/lib/'] - - # Enable all codecs: - flags += [ - '--enable-parsers', - '--enable-decoders', - '--enable-encoders', - '--enable-muxers', - '--enable-demuxers', - ] - else: - # Enable codecs only for .mp4: - flags += [ - '--enable-parser=aac,ac3,h261,h264,mpegaudio,mpeg4video,mpegvideo,vc1', - '--enable-decoder=aac,h264,mpeg4,mpegvideo', - '--enable-muxer=h264,mov,mp4,mpeg2video', - '--enable-demuxer=aac,h264,m4v,mov,mpegvideo,vc1,rtsp', - ] - - # needed to prevent _ffmpeg.so: version node not found for symbol av_init_packet@LIBAVFORMAT_52 - # /usr/bin/ld: failed to set dynamic section sizes: Bad value - flags += [ - '--disable-symver', - ] - - # disable binaries / doc - flags += [ - # '--disable-programs', - '--disable-doc', - ] - - # other flags: - flags += [ - '--enable-filter=aresample,resample,crop,adelay,volume,scale', - '--enable-protocol=file,http,hls,udp,tcp', - '--enable-small', - '--enable-hwaccels', - '--enable-pic', - '--disable-static', - '--disable-debug', - '--enable-shared', - ] - - if 'arm64' in arch.arch: - arch_flag = 'aarch64' - elif 'x86' in arch.arch: - arch_flag = 'x86' - flags += ['--disable-asm'] - else: - arch_flag = 'arm' - - # android: - flags += [ - '--target-os=android', - '--enable-cross-compile', - '--cross-prefix={}-'.format(arch.target), - '--arch={}'.format(arch_flag), - '--strip={}'.format(self.ctx.ndk.llvm_strip), - '--sysroot={}'.format(self.ctx.ndk.sysroot), - '--enable-neon', - '--prefix={}'.format(realpath('.')), - ] - - if arch_flag == 'arm': - cflags += [ - '-mfpu=vfpv3-d16', - '-mfloat-abi=softfp', - '-fPIC', - ] - - env['CFLAGS'] += ' ' + ' '.join(cflags) - env['LDFLAGS'] += ' ' + ' '.join(ldflags) - - configure = sh.Command('./configure') - shprint(configure, *flags, _env=env) - shprint(sh.make, '-j4', _env=env) - shprint(sh.make, 'install', _env=env) - # copy libs: - sh.cp('-a', sh.glob('./lib/lib*.so'), - self.ctx.get_libs_dir(arch.arch)) - - -recipe = FFMpegRecipe() diff --git a/recipes/mffmpeg/patches/configure.patch b/recipes/mffmpeg/patches/configure.patch deleted file mode 100644 index cacf029..0000000 --- a/recipes/mffmpeg/patches/configure.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- ./configure 2020-10-11 19:12:16.759760904 +0200 -+++ ./configure.patch 2020-10-11 19:15:49.059533563 +0200 -@@ -6361,7 +6361,7 @@ - enabled librsvg && require_pkg_config librsvg librsvg-2.0 librsvg-2.0/librsvg/rsvg.h rsvg_handle_render_cairo - enabled librtmp && require_pkg_config librtmp librtmp librtmp/rtmp.h RTMP_Socket - enabled librubberband && require_pkg_config librubberband "rubberband >= 1.8.1" rubberband/rubberband-c.h rubberband_new -lstdc++ && append librubberband_extralibs "-lstdc++" --enabled libshine && require_pkg_config libshine shine shine/layer3.h shine_encode_buffer -+enabled libshine && require "shine" shine/layer3.h shine_encode_buffer -lshine -lm - enabled libsmbclient && { check_pkg_config libsmbclient smbclient libsmbclient.h smbc_init || - require libsmbclient libsmbclient.h smbc_init -lsmbclient; } - enabled libsnappy && require libsnappy snappy-c.h snappy_compress -lsnappy -lstdc++ \ No newline at end of file diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index af3020e..5fbfbfc 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 = 20251122 -requirements = kivy==2.3.0,libbz2,sqlite3,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,lxst +requirements = kivy==2.3.0,libbz2,sqlite3,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,codec2,pycodec2,sh,pynacl,typing-extensions,mistune>=3.0.2,beautifulsoup4,lxst android.gradle_dependencies = com.android.support:support-compat:28.0.0 #android.enable_androidx = True From 7d5266de054586ba23354896a92969c1f6371d73 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 02:12:01 +0100 Subject: [PATCH 202/271] Handle all audio processing with LXST --- sbapp/main.py | 14 +++++++---- sbapp/sideband/audioproc.py | 46 +++++++++++++++++++------------------ sbapp/sideband/core.py | 4 +--- 3 files changed, 34 insertions(+), 30 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index ce0e7c9..6643dd8 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -30,6 +30,8 @@ import RNS.vendor.umsgpack as msgpack from LXST._version import __version__ as lxst_version from LXST.Primitives.Recorders import FileRecorder from LXST.Primitives.Players import FilePlayer +from LXST.Codecs import Opus +from LXST.Filters import BandPass, AGC WINDOW_DEFAULT_WIDTH = 494 WINDOW_DEFAULT_HEIGHT = 800 @@ -2462,7 +2464,8 @@ class SidebandApp(MDApp): if not hasattr(self, "ptt_recorder") or self.ptt_recorder == None: self.ptt_recording_path = self.sideband.rec_cache+"/ptt_recording.ogg" - self.ptt_recorder = FileRecorder(self.ptt_recording_path) + self.ptt_recorder = FileRecorder(self.ptt_recording_path, profile=Opus.PROFILE_VOICE_HIGH, gain=2.0, + skip=0.075, ease_in=0.125, filters=[BandPass(300, 8500), AGC(target_level=-15.0)]) self.message_attach_action(attach_type="audio", nodialog=True) el_button = self.messages_view.ids.message_ptt_button @@ -2562,8 +2565,9 @@ class SidebandApp(MDApp): def a_rec_action(sender): if not self.rec_dialog.recording and not self.rec_dialog.recorder: self.sideband.ui_started_recording() - self.rec_dialog.recorder = FileRecorder(self.rec_dialog.file_path) - RNS.log("Starting recording...") # TODO: Remove + self.rec_dialog.recorder = FileRecorder(self.rec_dialog.file_path, profile=Opus.PROFILE_VOICE_HIGH, gain=2.0, + skip=0.075, ease_in=0.125, filters=[BandPass(300, 8500), AGC(target_level=-15.0)]) + RNS.log("Starting recording...", RNS.LOG_DEBUG) # TODO: Remove self.rec_dialog.recording = True el = self.rec_dialog.rec_item.children[0].children[0] el.ttc = el.theme_text_color; el.tc = el.text_color @@ -2574,10 +2578,10 @@ class SidebandApp(MDApp): self.rec_dialog.recorder.start() else: - RNS.log("Stopping recording...") # TODO: Remove + RNS.log("Stopping recording...", RNS.LOG_DEBUG) # TODO: Remove self.rec_dialog.recorder.stop() self.rec_dialog.recorder = None - RNS.log("Recording stopped") # TODO: Remove + RNS.log("Recording stopped", RNS.LOG_DEBUG) # TODO: Remove self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Start Recording[/size]" el = self.rec_dialog.rec_item.children[0].children[0] el.icon = "record" diff --git a/sbapp/sideband/audioproc.py b/sbapp/sideband/audioproc.py index c973342..4fbf4bd 100644 --- a/sbapp/sideband/audioproc.py +++ b/sbapp/sideband/audioproc.py @@ -102,28 +102,30 @@ def samples_to_wav(samples=None, file_path=None): def voice_processing(input_path): try: - ffmpeg = None - ffmpeg = sh.ffmpeg - if ffmpeg: - filters = "atrim=start=0.075, afade=t=in:st=0:d=0.085, highpass=f=250, lowpass=f=3000, speechnorm=e=12.5:r=0.0001:l=1" - output_bitrate = "12k" - opus_apptype = "audio" - output_path = input_path.replace(".ogg","")+".p.ogg" - args = [ - "-i", input_path, "-filter:a", filters, - "-c:a", "libopus", "-application", opus_apptype, - "-vbr", "on","-b:a", output_bitrate, output_path] - try: - try: - os.unlink(output_path) - except: - pass - ffmpeg(*args) - return output_path - except Exception as e: - RNS.log("Could not process audio with ffmpeg", RNS.LOG_ERROR) - RNS.trace_exception(e) - return None + return None + # Moving to LXST native processing + # ffmpeg = None + # ffmpeg = sh.ffmpeg + # if ffmpeg: + # filters = "atrim=start=0.075, afade=t=in:st=0:d=0.085, highpass=f=250, lowpass=f=3000, speechnorm=e=12.5:r=0.0001:l=1" + # output_bitrate = "12k" + # opus_apptype = "audio" + # output_path = input_path.replace(".ogg","")+".p.ogg" + # args = [ + # "-i", input_path, "-filter:a", filters, + # "-c:a", "libopus", "-application", opus_apptype, + # "-vbr", "on","-b:a", output_bitrate, output_path] + # try: + # try: + # os.unlink(output_path) + # except: + # pass + # ffmpeg(*args) + # return output_path + # except Exception as e: + # RNS.log("Could not process audio with ffmpeg", RNS.LOG_ERROR) + # RNS.trace_exception(e) + # return None except Exception as e: return None diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index dc03ef0..01d71d6 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5010,9 +5010,7 @@ class SidebandCore(): temp_path = self.rec_cache+"/ptt_msg.ogg" from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 - target_rate = 8000 - if RNS.vendor.platformutils.is_linux(): target_rate = 48000 - + target_rate = 48000 if detect_codec2(): if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate): RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG) else: RNS.log("OGG write failed", RNS.LOG_DEBUG) From fbb46a63c7e3d9fe5320c44747acf0bab67e16a4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 02:13:34 +0100 Subject: [PATCH 203/271] Cleanup --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 6643dd8..d11ef49 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3182,7 +3182,7 @@ class SidebandApp(MDApp): str_comps = " - [b]Reticulum[/b] (Reticulum License)\n - [b]LXMF[/b] (Reticulum 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]Able[/b] (MIT License)\n - [b]FFmpeg[/b] (GPL3 License)" + str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)\n - [b]Able[/b] (MIT 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+"\nRunning on RNS v"+RNS.__version__+", LXMF v"+LXMF.__version__+" and LXST v"+lxst_version+".\n\nHumbly build using the following open components:\n\n"+str_comps From 424c2fcd068b2c840f45b4125cc3c14e5c815c8c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 11:11:58 +0100 Subject: [PATCH 204/271] Fixed notifications not displaying on windows. Ignore accidental PTT presses. Cleaned up file path resolution. --- sbapp/main.py | 89 ++++++++++++++++--------------- sbapp/sideband/audioproc.py | 37 ++----------- sbapp/sideband/core.py | 101 ++++++++++++++++++------------------ setup.py | 3 +- 4 files changed, 104 insertions(+), 126 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index d11ef49..0a4cec8 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -102,15 +102,14 @@ def apply_ui_scale(): try: if RNS.vendor.platformutils.is_android(): import plyer - ui_scale_path = plyer.storagepath.get_application_dir()+"/io.unsigned.sideband/files/app_storage/ui_scale" + ui_scale_path = os.path.join(plyer.storagepath.get_application_dir(), "io.unsigned.sideband", "files", "app_storage", "ui_scale") else: if config_path == None: import sbapp.plyer as plyer - ui_scale_path = plyer.storagepath.get_home_dir()+"/.config/sideband/app_storage/ui_scale" - if ui_scale_path.startswith("file://"): - ui_scale_path = ui_scale_path.replace("file://", "") + ui_scale_path = os.path.join(plyer.storagepath.get_home_dir(), ".config", "sideband", "app_storage", "ui_scale") + if ui_scale_path.startswith("file://"): ui_scale_path = ui_scale_path.replace("file://", "") else: - ui_scale_path = config_path+"/app_storage/ui_scale" + ui_scale_path = os.path.join(config_path, "app_storage", "ui_scale") if ui_scale_path: ui_scale_path = f"{ui_scale_path}{res_ident}" @@ -449,8 +448,8 @@ else: from android.permissions import request_permissions, check_permission from android.storage import primary_external_storage_path, secondary_external_storage_path - import pyogg - from pydub import AudioSegment + import LXST.Codecs.libs.pyogg as pyogg + from LXST.Codecs.libs.pydub import AudioSegment from kivymd.utils.set_bars_colors import set_bars_colors android_api_version = autoclass('android.os.Build$VERSION').SDK_INT @@ -473,8 +472,8 @@ else: from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem from .ui.helpers import multilingual_markup, mdc - import sbapp.pyogg as pyogg - from sbapp.pydub import AudioSegment + import LXST.Codecs.libs.pyogg as pyogg + from LXST.Codecs.libs.pydub import AudioSegment from kivymd.toast import toast @@ -572,6 +571,7 @@ class SidebandApp(MDApp): self.attach_dialog = None self.shared_attach_dialog = None self.rec_dialog = None + self.recording_started = None self.last_msg_audio = None self.msg_sound = None self.audio_msg_mode = LXMF.AM_OPUS_OGG @@ -581,8 +581,8 @@ class SidebandApp(MDApp): Window.softinput_mode = "below_target" self.window_state = app_init_window_state - self.icon = self.sideband.asset_dir+"/icon.png" - self.notification_icon = self.sideband.asset_dir+"/notification_icon.png" + self.icon = os.path.join(self.sideband.asset_dir, "icon.png") + self.notification_icon = os.path.join(self.sideband.asset_dir, "notification_icon.png") self.resume_event_scheduler = None self.connectivity_updater = None @@ -830,40 +830,40 @@ class SidebandApp(MDApp): def font_config(self): from kivy.core.text import LabelBase, DEFAULT_FONT - fb_path = self.sideband.asset_dir+"/fonts/" + fb_path = os.path.join(self.sideband.asset_dir, "fonts") LabelBase.register(name="hebrew", - fn_regular=fb_path+"NotoSansHebrew-Regular.ttf", - fn_bold=fb_path+"NotoSansHebrew-Bold.ttf",) + fn_regular=os.path.join(fb_path, "NotoSansHebrew-Regular.ttf"), + fn_bold=os.path.join(fb_path, "NotoSansHebrew-Bold.ttf")) LabelBase.register(name="japanese", - fn_regular=fb_path+"NotoSansJP-Regular.ttf") + fn_regular=os.path.join(fb_path, "NotoSansJP-Regular.ttf")) LabelBase.register(name="chinese", - fn_regular=fb_path+"NotoSansSC-Regular.ttf") + fn_regular=os.path.join(fb_path, "NotoSansSC-Regular.ttf")) LabelBase.register(name="korean", - fn_regular=fb_path+"NotoSansKR-Regular.ttf") + fn_regular=os.path.join(fb_path, "NotoSansKR-Regular.ttf")) LabelBase.register(name="emoji", - fn_regular=fb_path+"NotoEmoji-Regular.ttf") + fn_regular=os.path.join(fb_path, "NotoEmoji-Regular.ttf")) LabelBase.register(name="defaultinput", - fn_regular=fb_path+"DefaultInput.ttf") + fn_regular=os.path.join(fb_path, "DefaultInput.ttf")) LabelBase.register(name="combined", - fn_regular=fb_path+"NotoSans-Regular.ttf", - fn_bold=fb_path+"NotoSans-Bold.ttf", - fn_italic=fb_path+"NotoSans-Italic.ttf", - fn_bolditalic=fb_path+"NotoSans-BoldItalic.ttf") + fn_regular=os.path.join(fb_path, "NotoSans-Regular.ttf"), + fn_bold=os.path.join(fb_path, "NotoSans-Bold.ttf"), + fn_italic=os.path.join(fb_path, "NotoSans-Italic.ttf"), + fn_bolditalic=os.path.join(fb_path, "NotoSans-BoldItalic.ttf")) LabelBase.register(name="mono", - fn_regular=fb_path+"RobotoMonoNerdFont-Regular.ttf") + fn_regular=os.path.join(fb_path, "RobotoMonoNerdFont-Regular.ttf")) LabelBase.register(name="term", - fn_regular=fb_path+"BigBlueTerm437NerdFont-Regular.ttf") + fn_regular=os.path.join(fb_path, "BigBlueTerm437NerdFont-Regular.ttf")) LabelBase.register(name="nf", - fn_regular=fb_path+"RobotoMonoNerdFont-Regular.ttf") + fn_regular=os.path.join(fb_path, "RobotoMonoNerdFont-Regular.ttf")) def update_input_language(self): language = self.sideband.config["input_language"] @@ -1001,7 +1001,7 @@ class SidebandApp(MDApp): def share_image(self, image, filename): if RNS.vendor.platformutils.get_platform() == "android": save_path = self.sideband.exports_dir - file_path = save_path+"/"+filename + file_path = os.path.join(save_path, filename) try: if not os.path.isdir(save_path): @@ -1440,11 +1440,9 @@ class SidebandApp(MDApp): self.sideband.lxm_ingest_uri(lxm_uri) def build(self): - FONT_PATH = self.sideband.asset_dir+"/fonts" - if RNS.vendor.platformutils.is_darwin(): - self.icon = self.sideband.asset_dir+"/icon_macos_formed.png" - else: - self.icon = self.sideband.asset_dir+"/icon.png" + FONT_PATH = os.path.join(self.sideband.asset_dir, "fonts") + if RNS.vendor.platformutils.is_darwin(): self.icon = os.path.join(self.sideband.asset_dir, "icon_macos_formed.png") + else: self.icon = os.path.join(self.sideband.asset_dir, "icon.png") self.announces_view = None @@ -2422,11 +2420,11 @@ class SidebandApp(MDApp): return if audio_field[0] == LXMF.AM_OPUS_OGG: - temp_path = self.sideband.rec_cache+"/msg.ogg" + temp_path = os.path.join(self.sideband.rec_cache, "msg.ogg") with open(temp_path, "wb") as af: af.write(self.last_msg_audio) elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200: - temp_path = self.sideband.rec_cache+"/msg.ogg" + temp_path = os.path.join(self.sideband.rec_cache, "msg.ogg") from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 target_rate = 48000 @@ -2459,11 +2457,12 @@ class SidebandApp(MDApp): if self.sideband.ui_recording: return self.sideband.ui_started_recording() + self.recording_started = time.time() if self.sideband.config["hq_ptt"]: self.audio_msg_mode = LXMF.AM_OPUS_OGG else: self.audio_msg_mode = LXMF.AM_CODEC2_2400 if not hasattr(self, "ptt_recorder") or self.ptt_recorder == None: - self.ptt_recording_path = self.sideband.rec_cache+"/ptt_recording.ogg" + self.ptt_recording_path = os.path.join(self.sideband.rec_cache, "ptt_recording.ogg") self.ptt_recorder = FileRecorder(self.ptt_recording_path, profile=Opus.PROFILE_VOICE_HIGH, gain=2.0, skip=0.075, ease_in=0.125, filters=[BandPass(300, 8500), AGC(target_level=-15.0)]) @@ -2488,6 +2487,7 @@ class SidebandApp(MDApp): el_button.line_color=mdc("BlueGray","500") el_icon.theme_text_color="Custom" el_icon.text_color=mdc("BlueGray","500") + def job(): try: self.ptt_recorder.stop() @@ -2497,9 +2497,16 @@ class SidebandApp(MDApp): RNS.trace_exception(e) self.sideband.ui_stopped_recording() - if self.message_process_audio(self.ptt_recording_path): - if self.outbound_mode_command: self.outbound_mode_reset() - self.message_send_action() + if self.recording_started != None: + duration = time.time() - self.recording_started + self.recording_started = None + if duration < 0.6: RNS.log(f"Discarding recording, only {RNS.prettyshorttime(duration)} of audio", RNS.LOG_WARNING) + else: + if os.path.isfile(self.ptt_recording_path): + if self.message_process_audio(self.ptt_recording_path): + if self.outbound_mode_command: self.outbound_mode_reset() + self.message_send_action() + threading.Thread(target=job, daemon=True).start() def message_process_audio(self, input_path): @@ -2546,7 +2553,7 @@ class SidebandApp(MDApp): ap_duration = time.time() - ap_start RNS.log("Audio processing complete in "+RNS.prettytime(ap_duration), RNS.LOG_DEBUG) - export_path = self.sideband.rec_cache+"/recording.enc" + export_path = os.path.join(self.sideband.rec_cache, "recording.enc") with open(export_path, "wb") as export_file: export_file.write(encoded) self.attach_path = export_path @@ -2658,7 +2665,7 @@ class SidebandApp(MDApp): self.rec_dialog.rec_item = rec_item self.rec_dialog.play_item = play_item self.rec_dialog.save_item = save_item - self.rec_dialog.file_path = self.sideband.rec_cache+"/recording.ogg" + self.rec_dialog.file_path = os.path.join(self.sideband.rec_cache, "recording.ogg") def message_record_audio_action(self): ss = int(dp(18)) @@ -3178,7 +3185,7 @@ class SidebandApp(MDApp): threading.Thread(target=lj, daemon=True).start() self.information_screen.ids.information_scrollview.effect_cls = ScrollEffect - self.information_screen.ids.information_logo.icon = self.sideband.asset_dir+"/rns_256.png" + self.information_screen.ids.information_logo.icon = os.path.join(self.sideband.asset_dir, "rns_256.png") str_comps = " - [b]Reticulum[/b] (Reticulum License)\n - [b]LXMF[/b] (Reticulum 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)" diff --git a/sbapp/sideband/audioproc.py b/sbapp/sideband/audioproc.py index 4fbf4bd..215fcd8 100644 --- a/sbapp/sideband/audioproc.py +++ b/sbapp/sideband/audioproc.py @@ -1,6 +1,5 @@ import os import io -import sh import math import time import struct @@ -9,15 +8,11 @@ import RNS import LXMF if RNS.vendor.platformutils.is_android(): - from pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter - from pydub import AudioSegment + from LXST.Codecs.libs.pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter + from LXST.Codecs.libs.pydub import AudioSegment else: - if RNS.vendor.platformutils.is_linux(): - from sbapp.pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter - else: - from pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter - - from sbapp.pydub import AudioSegment + from LXST.Codecs.libs.pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter + from LXST.Codecs.libs.pydub import AudioSegment codec2_modes = { # LXMF.AM_CODEC2_450PWB: ???, # No bindings @@ -102,30 +97,8 @@ def samples_to_wav(samples=None, file_path=None): def voice_processing(input_path): try: - return None # Moving to LXST native processing - # ffmpeg = None - # ffmpeg = sh.ffmpeg - # if ffmpeg: - # filters = "atrim=start=0.075, afade=t=in:st=0:d=0.085, highpass=f=250, lowpass=f=3000, speechnorm=e=12.5:r=0.0001:l=1" - # output_bitrate = "12k" - # opus_apptype = "audio" - # output_path = input_path.replace(".ogg","")+".p.ogg" - # args = [ - # "-i", input_path, "-filter:a", filters, - # "-c:a", "libopus", "-application", opus_apptype, - # "-vbr", "on","-b:a", output_bitrate, output_path] - # try: - # try: - # os.unlink(output_path) - # except: - # pass - # ffmpeg(*args) - # return output_path - # except Exception as e: - # RNS.log("Could not process audio with ffmpeg", RNS.LOG_ERROR) - # RNS.trace_exception(e) - # return None + return None except Exception as e: return None diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 01d71d6..5d4a787 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -202,13 +202,12 @@ class SidebandCore(): self.default_config_template = rns_config if config_path == None: - self.app_dir = plyer.storagepath.get_home_dir()+"/.config/sideband" - if self.app_dir.startswith("file://"): - self.app_dir = self.app_dir.replace("file://", "") + self.app_dir = os.path.join(plyer.storagepath.get_home_dir(), ".config", "sideband") + if self.app_dir.startswith("file://"): self.app_dir = self.app_dir.replace("file://", "") else: self.app_dir = config_path - self.cache_dir = self.app_dir+"/cache" + self.cache_dir = os.path.join(self.app_dir, "cache") self.rns_configdir = rns_config_path @@ -217,10 +216,10 @@ class SidebandCore(): core_path = core_path.replace("core.pyc", "core.py") if RNS.vendor.platformutils.is_android(): - self.app_dir = android_app_dir+"/io.unsigned.sideband/files/" - self.cache_dir = self.app_dir+"/cache" - self.rns_configdir = self.app_dir+"/app_storage/reticulum" - self.asset_dir = self.app_dir+"/app/assets" + self.app_dir = os.path.join(android_app_dir, "io.unsigned.sideband", "files") + self.cache_dir = os.path.join(self.app_dir, "cache") + self.rns_configdir = os.path.join(self.app_dir, "app_storage", "reticulum") + self.asset_dir = os.path.join(self.app_dir, "app", "assets") elif RNS.vendor.platformutils.is_darwin(): self.asset_dir = core_path.replace("/sideband/core.py", "/assets") elif RNS.vendor.platformutils.get_platform() == "linux": @@ -228,40 +227,41 @@ class SidebandCore(): elif RNS.vendor.platformutils.is_windows(): self.asset_dir = core_path.replace("\\sideband\\core.py", "\\assets") else: - self.asset_dir = plyer.storagepath.get_application_dir()+"/sbapp/assets" + self.asset_dir = os.path.join(plyer.storagepath.get_application_dir(), "sbapp", "assets") - self.map_cache = self.cache_dir+"/maps" + self.map_cache = os.path.join(self.cache_dir, "maps") if not os.path.isdir(self.map_cache): os.makedirs(self.map_cache) - self.rec_cache = self.cache_dir+"/rec" + self.rec_cache = os.path.join(self.cache_dir, "rec") if not os.path.isdir(self.rec_cache): os.makedirs(self.rec_cache) - self.share_cache = self.cache_dir+"/share" + self.share_cache = os.path.join(self.cache_dir, "share") if not os.path.isdir(self.share_cache): os.makedirs(self.share_cache) - self.icon = self.asset_dir+"/icon.png" - self.icon_48 = self.asset_dir+"/icon_48.png" - self.icon_32 = self.asset_dir+"/icon_32.png" - self.icon_macos = self.asset_dir+"/icon_macos.png" - self.notification_icon = self.asset_dir+"/notification_icon.png" - self.notif_icon_black = self.asset_dir+"/notification_icon_black.png" + self.icon = os.path.join(self.asset_dir, "icon.png") + self.icon_48 = os.path.join(self.asset_dir, "icon_48.png") + self.icon_32 = os.path.join(self.asset_dir, "icon_32.png") + self.icon_macos = os.path.join(self.asset_dir, "icon_macos.png") + self.icon_windows = os.path.join(self.asset_dir, "icon.ico") + self.notification_icon = os.path.join(self.asset_dir, "notification_icon.png") + self.notif_icon_black = os.path.join(self.asset_dir, "notification_icon_black.png") os.environ["TELEMETER_GEOID_PATH"] = os.path.join(self.asset_dir, "geoids") - if not os.path.isdir(self.app_dir+"/app_storage"): - os.makedirs(self.app_dir+"/app_storage") + if not os.path.isdir(os.path.join(self.app_dir, "app_storage")): + os.makedirs(os.path.join(self.app_dir, "app_storage")) - self.config_path = self.app_dir+"/app_storage/sideband_config" - self.identity_path = self.app_dir+"/app_storage/primary_identity" - self.db_path = self.app_dir+"/app_storage/sideband.db" - self.lxmf_storage = self.app_dir+"/app_storage/" - self.log_dir = self.app_dir+"/app_storage/" - self.tmp_dir = self.app_dir+"/app_storage/tmp" - self.exports_dir = self.app_dir+"/exports" - self.telemetry_exclude_path = self.app_dir+"/app_storage/collector_response_excluded" + self.config_path = os.path.join(self.app_dir, "app_storage", "sideband_config") + self.identity_path = os.path.join(self.app_dir, "app_storage", "primary_identity") + self.db_path = os.path.join(self.app_dir, "app_storage", "sideband.db") + self.lxmf_storage = os.path.join(self.app_dir, "app_storage") + self.log_dir = os.path.join(self.app_dir, "app_storage") + self.tmp_dir = os.path.join(self.app_dir, "app_storage", "tmp") + self.exports_dir = os.path.join(self.app_dir, "exports") + self.telemetry_exclude_path = os.path.join(self.app_dir, "app_storage", "collector_response_excluded") if RNS.vendor.platformutils.is_android(): self.webshare_dir = "./share/" @@ -269,8 +269,8 @@ class SidebandCore(): sideband_dir = os.path.dirname(os.path.abspath(__file__)) self.webshare_dir = os.path.abspath(os.path.join(sideband_dir, "..", "share")) - 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.webshare_ssl_key_path = os.path.join(self.app_dir, "app_storage", "ssl_key.pem") + self.webshare_ssl_cert_path = os.path.join(self.app_dir, "app_storage", "ssl_cert.pem") self.mqtt = None self.mqtt_handle_lock = threading.Lock() @@ -319,9 +319,9 @@ class SidebandCore(): if RNS.vendor.platformutils.is_android(): if self.config["config_template"] != None: try: - if not os.path.isfile(self.rns_configdir+"/config_template_invalid"): + if not os.path.isfile(os.path.join(self.rns_configdir, "config_template_invalid")): if self.is_service: - with open(self.rns_configdir+"/config_template_invalid", "w") as invalidation_file: + with open(os.path.join(self.rns_configdir, "config_template_invalid"), "w") as invalidation_file: invalidation_file.write("\n") ct = self.config["config_template"] @@ -342,7 +342,7 @@ class SidebandCore(): # Initialise Reticulum configuration if RNS.vendor.platformutils.get_platform() == "android": try: - self.rns_configdir = self.app_dir+"/app_storage/reticulum" + self.rns_configdir = os.path.join(self.app_dir, "app_storage", "reticulum") if not os.path.isdir(self.rns_configdir): os.makedirs(self.rns_configdir) @@ -354,7 +354,7 @@ class SidebandCore(): RNS.log("Not enabling Reticulum Transport") generated_config = self.config_template.replace("TRANSPORT_IS_ENABLED", "No") - config_file = open(self.rns_configdir+"/config", "wb") + config_file = open(os.path.join(self.rns_configdir, "config"), "wb") config_file.write(generated_config.encode("utf-8")) config_file.close() @@ -389,10 +389,10 @@ class SidebandCore(): app_entry_dir = os.path.expanduser("~/.local/share/applications") icon_dir = os.path.expanduser("~/.local/share/icons/hicolor/512x512/apps") de_filename = "io.unsigned.sideband.desktop" - de_source = self.asset_dir+"/"+de_filename - de_target = app_entry_dir+"/"+de_filename - icn_source = self.asset_dir+"/icon.png" - icn_target = icon_dir+"/io.unsigned.sideband.png" + de_source = os.path.join(self.asset_dir, de_filename) + de_target = os.path.join(app_entry_dir, de_filename) + icn_source = os.path.join(self.asset_dir, "icon.png") + icn_target = os.path.join(icon_dir, "io.unsigned.sideband.png") if os.path.isdir(local_share_dir): if not os.path.exists(app_entry_dir): os.makedirs(app_entry_dir) @@ -435,13 +435,13 @@ class SidebandCore(): def clear_tmp_dir(self): if os.path.isdir(self.tmp_dir): for file in os.listdir(self.tmp_dir): - fpath = self.tmp_dir+"/"+file + fpath = os.path.join(self.tmp_dir, file) os.unlink(fpath) def clear_exports_dir(self): if os.path.isdir(self.exports_dir): for file in os.listdir(self.exports_dir): - fpath = self.exports_dir+"/"+file + fpath = os.path.join(self.exports_dir, file) RNS.log("Clearing "+str(fpath)) os.unlink(fpath) @@ -637,7 +637,7 @@ class SidebandCore(): if not "classic_message_colors" in self.config: self.config["classic_message_colors"] = False if not "display_style_in_contact_list" in self.config: self.config["display_style_in_contact_list"] = True if not "lxm_limit_1mb" in self.config: self.config["lxm_limit_1mb"] = True - if not "hq_ptt" in self.config: self.config["hq_ptt"] = False + if not "hq_ptt" in self.config: self.config["hq_ptt"] = True 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 "confirm_calls" in self.config: self.config["confirm_calls"] = True @@ -811,7 +811,7 @@ class SidebandCore(): with open(self.config_path, "wb") as config_file: config_file.write(msgpack.packb(self.config)) self.saving_configuration = False if RNS.vendor.platformutils.is_android(): - boot_toggle_path = self.app_dir+"/app_storage/boot_toggle" + boot_toggle_path = os.path.join(self.app_dir, "app_storage", "boot_toggle") boot_toggle_exists = os.path.isfile(boot_toggle_path) if self.config["start_at_boot"] == True and not boot_toggle_exists: with open(boot_toggle_path, "w") as f: f.write("true") @@ -942,12 +942,11 @@ class SidebandCore(): if notifications_permitted: try: if RNS.vendor.platformutils.get_platform() == "android": - if self.is_service: - self.owner_service.android_notification(title, content, group=group, context_id=context_id) - else: - plyer.notification.notify(title, content, notification_icon=self.notification_icon, context_override=None) + if self.is_service: self.owner_service.android_notification(title, content, group=group, context_id=context_id) + else: plyer.notification.notify(title, content, notification_icon=self.notification_icon, context_override=None) else: - plyer.notification.notify(title, content, app_icon=self.icon_32) + if not RNS.vendor.platformutils.is_windows(): plyer.notification.notify(title, content, app_name="Sideband", app_icon=self.icon_48) + else: plyer.notification.notify(title, content, app_name="Sideband", app_icon=self.icon_windows) except Exception as e: RNS.log("An error occurred while posting a notification to the operating system: {e}", RNS.LOG_ERROR) @@ -4113,8 +4112,8 @@ class SidebandCore(): if RNS.vendor.platformutils.is_android(): if self.is_service: - if os.path.isfile(self.rns_configdir+"/config_template_invalid"): - os.unlink(self.rns_configdir+"/config_template_invalid") + if os.path.isfile(os.path.join(self.rns_configdir, "config_template_invalid")): + os.unlink(os.path.join(self.rns_configdir, "config_template_invalid")) else: pass @@ -5003,11 +5002,11 @@ class SidebandCore(): return if audio_field[0] == LXMF.AM_OPUS_OGG: - temp_path = self.rec_cache+"/ptt_msg.ogg" + temp_path = os.path.join(self.rec_cache, "ptt_msg.ogg") with open(temp_path, "wb") as af: af.write(self.last_msg_audio) elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200: - temp_path = self.rec_cache+"/ptt_msg.ogg" + temp_path = os.path.join(self.rec_cache, "ptt_msg.ogg") from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 target_rate = 48000 diff --git a/setup.py b/setup.py index 28c14fc..5cafe98 100644 --- a/setup.py +++ b/setup.py @@ -120,10 +120,9 @@ setuptools.setup( "pillow>=10.2.0", "qrcode", "materialyoucolor>=2.0.7", - "ffpyplayer", "sh", "numpy>=2.0.0", - "lxst>=0.4.2", + "lxst>=0.4.4", "mistune>=3.0.2", "beautifulsoup4", "pycodec2>=4.1.0", From c727abe1eff90abb032c5f3e9d1328595bb19e54 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 13:46:15 +0100 Subject: [PATCH 205/271] Cleanup dependencies --- Makefile | 12 ++++++++++++ README.md | 9 ++++++--- sbapp/main.py | 12 ++++++++---- setup.py | 8 +++----- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/Makefile b/Makefile index 6f5ed59..b74a4b5 100644 --- a/Makefile +++ b/Makefile @@ -24,6 +24,18 @@ cleanbuildozer: cleanall: clean cleanbuildozer +remove_symlinks: + @echo Removing symlinks for build... + -rm ./RNS + -rm ./LXST + -rm ./LXMF + +create_symlinks: + @echo Creating symlinks... + -ln -s ../Reticulum/RNS ./RNS + -ln -s ../LXST/LXST ./LXST + -ln -s ../LXMF/LXMF ./LXMF + preparewheel: pyclean . $(MAKE) -C sbapp cleanrns diff --git a/README.md b/README.md index 2272c88..114ed01 100644 --- a/README.md +++ b/README.md @@ -204,11 +204,11 @@ If you install Sideband from the DMG file, it is still recommended to install th ```bash # Install Reticulum and utilities with pip: -pip3 install rns +pip3 install rns --user # On some versions, you may need to use the # flag --break-system-packages to install: -pip3 install rns --break-system-packages +pip3 install rns --user --break-system-packages ``` If you do not have Python and `pip` available, [download and install it](https://www.python.org/downloads/) first. @@ -223,7 +223,10 @@ To install Sideband via `pip`, follow these instructions: ```bash # Install Sideband and dependencies on macOS using pip: -pip3 install sbapp +pip3 install sbapp --user + +# Or, if your Python environment is externally managed: +pip3 install sbapp --user --break-system-packages # Run Sideband from the terminal: ################################# diff --git a/sbapp/main.py b/sbapp/main.py index 0a4cec8..0fdffbd 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -4109,12 +4109,14 @@ class SidebandApp(MDApp): info = "Sideband is connected via a shared Reticulum instance running on this system.\n\n" info += "To get connectivity status, use the [b]rnstatus[/b] utility.\n\n" info += "To configure connectivity, edit the configuration file located at:\n\n" - info += str(RNS.Reticulum.configpath) + if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) + else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) else: info = "Sideband is currently running a standalone or master Reticulum instance on this system.\n\n" info += "To get connectivity status, use the [b]rnstatus[/b] utility.\n\n" info += "To configure connectivity, edit the configuration file located at:\n\n" - info += str(RNS.Reticulum.configpath) + if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) + else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) self.connectivity_screen.ids.connectivity_info.text = info @@ -4438,11 +4440,13 @@ class SidebandApp(MDApp): if self.sideband.reticulum.is_connected_to_shared_instance: info = "Sideband is connected via a shared Reticulum instance running on this system.\n\n" info += "To configure hardware parameters, edit the configuration file located at:\n\n" - info += str(RNS.Reticulum.configpath) + if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) + else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) else: info = "Sideband is currently running a standalone or master Reticulum instance on this system.\n\n" info += "To configure hardware parameters, edit the configuration file located at:\n\n" - info += str(RNS.Reticulum.configpath) + if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) + else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) self.hardware_screen.ids.hardware_info.text = info diff --git a/setup.py b/setup.py index 5cafe98..58970b3 100644 --- a/setup.py +++ b/setup.py @@ -116,17 +116,15 @@ setuptools.setup( install_requires=[ "rns>=1.0.4", "lxmf>=0.9.3", + "lxst>=0.4.4", "kivy>=2.3.0", + "numpy>=2.0.0", "pillow>=10.2.0", + "mistune>=3.0.2", "qrcode", "materialyoucolor>=2.0.7", - "sh", - "numpy>=2.0.0", - "lxst>=0.4.4", - "mistune>=3.0.2", "beautifulsoup4", "pycodec2>=4.1.0", - "pyaudio;sys.platform=='linux'", "pyobjus;sys.platform=='darwin'", "pyogg;sys.platform=='Windows' and sys.platform!='win32'", "audioop-lts>=0.2.1;python_version>='3.13'" From 65e08a9d41ed4d0a4e222d4afbe678a47cb901ca Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 13:57:16 +0100 Subject: [PATCH 206/271] Cleanup unneeded dependencies --- Makefile | 6 +- sbapp/plyer/__init__.py | 5 +- sbapp/plyer/facades/__init__.py | 4 +- sbapp/plyer/facades/audio.py | 104 ----- sbapp/plyer/platforms/android/audio.py | 108 ----- sbapp/plyer/platforms/ios/__init__.py | 0 sbapp/plyer/platforms/ios/accelerometer.py | 34 -- sbapp/plyer/platforms/ios/barometer.py | 31 -- sbapp/plyer/platforms/ios/battery.py | 47 -- sbapp/plyer/platforms/ios/brightness.py | 27 -- sbapp/plyer/platforms/ios/call.py | 29 -- sbapp/plyer/platforms/ios/camera.py | 52 --- sbapp/plyer/platforms/ios/compass.py | 43 -- sbapp/plyer/platforms/ios/email.py | 52 --- sbapp/plyer/platforms/ios/filechooser.py | 81 ---- sbapp/plyer/platforms/ios/flash.py | 50 --- sbapp/plyer/platforms/ios/gps.py | 80 ---- sbapp/plyer/platforms/ios/gravity.py | 31 -- sbapp/plyer/platforms/ios/gyroscope.py | 55 --- sbapp/plyer/platforms/ios/keystore.py | 23 - sbapp/plyer/platforms/ios/maps.py | 78 ---- sbapp/plyer/platforms/ios/sms.py | 43 -- .../plyer/platforms/ios/spatialorientation.py | 31 -- sbapp/plyer/platforms/ios/storagepath.py | 62 --- sbapp/plyer/platforms/ios/tts.py | 37 -- sbapp/plyer/platforms/ios/uniqueid.py | 27 -- sbapp/plyer/platforms/ios/vibrator.py | 43 -- sbapp/plyer/platforms/linux/audio.py | 139 ------ sbapp/plyer/platforms/macosx/audio.py | 128 ------ sbapp/plyer/platforms/win/audio.py | 413 ------------------ 30 files changed, 6 insertions(+), 1857 deletions(-) delete mode 100644 sbapp/plyer/facades/audio.py delete mode 100644 sbapp/plyer/platforms/android/audio.py delete mode 100644 sbapp/plyer/platforms/ios/__init__.py delete mode 100644 sbapp/plyer/platforms/ios/accelerometer.py delete mode 100644 sbapp/plyer/platforms/ios/barometer.py delete mode 100644 sbapp/plyer/platforms/ios/battery.py delete mode 100644 sbapp/plyer/platforms/ios/brightness.py delete mode 100644 sbapp/plyer/platforms/ios/call.py delete mode 100644 sbapp/plyer/platforms/ios/camera.py delete mode 100644 sbapp/plyer/platforms/ios/compass.py delete mode 100644 sbapp/plyer/platforms/ios/email.py delete mode 100644 sbapp/plyer/platforms/ios/filechooser.py delete mode 100644 sbapp/plyer/platforms/ios/flash.py delete mode 100644 sbapp/plyer/platforms/ios/gps.py delete mode 100644 sbapp/plyer/platforms/ios/gravity.py delete mode 100644 sbapp/plyer/platforms/ios/gyroscope.py delete mode 100644 sbapp/plyer/platforms/ios/keystore.py delete mode 100644 sbapp/plyer/platforms/ios/maps.py delete mode 100644 sbapp/plyer/platforms/ios/sms.py delete mode 100644 sbapp/plyer/platforms/ios/spatialorientation.py delete mode 100644 sbapp/plyer/platforms/ios/storagepath.py delete mode 100644 sbapp/plyer/platforms/ios/tts.py delete mode 100644 sbapp/plyer/platforms/ios/uniqueid.py delete mode 100644 sbapp/plyer/platforms/ios/vibrator.py delete mode 100644 sbapp/plyer/platforms/linux/audio.py delete mode 100644 sbapp/plyer/platforms/macosx/audio.py delete mode 100644 sbapp/plyer/platforms/win/audio.py diff --git a/Makefile b/Makefile index b74a4b5..7b08d25 100644 --- a/Makefile +++ b/Makefile @@ -40,8 +40,10 @@ preparewheel: pyclean . $(MAKE) -C sbapp cleanrns -build_wheel: - python3 setup.py sdist bdist_wheel +compile_wheel: + python3 setup.py bdist_wheel + +build_wheel: remove_symlinks compile_wheel create_symlinks build_win_exe: python -m PyInstaller sideband.spec --noconfirm diff --git a/sbapp/plyer/__init__.py b/sbapp/plyer/__init__.py index 9bfb190..9859034 100644 --- a/sbapp/plyer/__init__.py +++ b/sbapp/plyer/__init__.py @@ -5,7 +5,7 @@ Plyer ''' __all__ = ( - 'accelerometer', 'audio', 'barometer', 'battery', 'bluetooth', + 'accelerometer', 'barometer', 'battery', 'bluetooth', 'brightness', 'call', 'camera', 'compass', 'cpu', 'email', 'filechooser', 'flash', 'gps', 'gravity', 'gyroscope', 'humidity', 'irblaster', 'keystore', 'light', 'notification', 'orientation', 'processors', @@ -29,9 +29,6 @@ accelerometer = Proxy('accelerometer', facades.Accelerometer) #: Keyring proxy to :class::`plyer.facades.Keystore` keystore = Proxy('keystore', facades.Keystore) -#: Audio proxy to :class:`plyer.facades.Audio` -audio = Proxy('audio', facades.Audio) - #: Barometer proxy to :class:`plyer.facades.Barometer` barometer = Proxy('barometer', facades.Barometer) diff --git a/sbapp/plyer/facades/__init__.py b/sbapp/plyer/facades/__init__.py index 81a0f63..88f3985 100644 --- a/sbapp/plyer/facades/__init__.py +++ b/sbapp/plyer/facades/__init__.py @@ -6,7 +6,7 @@ Interface of all the features available. ''' -__all__ = ('Accelerometer', 'Audio', 'Barometer', 'Battery', 'Call', 'Camera', +__all__ = ('Accelerometer', 'Barometer', 'Battery', 'Call', 'Camera', 'Compass', 'Email', 'FileChooser', 'GPS', 'Gravity', 'Gyroscope', 'IrBlaster', 'Light', 'Orientation', 'Notification', 'Proximity', 'Sms', 'TTS', 'UniqueID', 'Vibrator', 'Wifi', 'Flash', 'CPU', @@ -17,7 +17,6 @@ __all__ = ('Accelerometer', 'Audio', 'Barometer', 'Battery', 'Call', 'Camera', import RNS if RNS.vendor.platformutils.is_android(): from plyer.facades.accelerometer import Accelerometer - from plyer.facades.audio import Audio from plyer.facades.barometer import Barometer from plyer.facades.battery import Battery from plyer.facades.call import Call @@ -53,7 +52,6 @@ if RNS.vendor.platformutils.is_android(): from plyer.facades.devicename import DeviceName else: from sbapp.plyer.facades.accelerometer import Accelerometer - from sbapp.plyer.facades.audio import Audio from sbapp.plyer.facades.barometer import Barometer from sbapp.plyer.facades.battery import Battery from sbapp.plyer.facades.call import Call diff --git a/sbapp/plyer/facades/audio.py b/sbapp/plyer/facades/audio.py deleted file mode 100644 index 0394037..0000000 --- a/sbapp/plyer/facades/audio.py +++ /dev/null @@ -1,104 +0,0 @@ -''' -Audio -===== - -The :class:`Audio` is used for recording audio. - -Default path for recording is set in platform implementation. - -.. note:: - On Android the `RECORD_AUDIO`, `WAKE_LOCK` permissions are needed. - -Simple Examples ---------------- - -To get the file path:: - - >>> audio.file_path - '/sdcard/testrecorder.3gp' - -To set the file path:: - - >>> import os - >>> current_list = os.listdir('.') - ['/sdcard/testrecorder.3gp', '/sdcard/testrecorder1.3gp', - '/sdcard/testrecorder2.3gp', '/sdcard/testrecorder3.3gp'] - >>> file_path = current_list[2] - >>> audio.file_path = file_path - -To start recording:: - - >>> from plyer import audio - >>> audio.start() - -To stop recording:: - - >>> audio.stop() - -To play recording:: - - >>> audio.play() - -Supported Platforms -------------------- -Android, Windows, macOS - -''' - - -class Audio: - ''' - Audio facade. - ''' - - state = 'ready' - _file_path = '' - - def __init__(self, file_path=None): - super().__init__() - self._file_path = file_path or self._file_path - - def start(self): - ''' - Start record. - ''' - self._start() - self.state = 'recording' - - def stop(self): - ''' - Stop record. - ''' - self._stop() - self.state = 'ready' - - def play(self): - ''' - Play current recording. - ''' - self._play() - self.state = 'playing' - - @property - def file_path(self): - return self._file_path - - @file_path.setter - def file_path(self, location): - ''' - Location of the recording. - ''' - assert isinstance(location, str), 'Location must be string or unicode' - self._file_path = location - - # private - - def _start(self): - raise IOError("JUICE") - raise NotImplementedError() - - def _stop(self): - raise NotImplementedError() - - def _play(self): - raise NotImplementedError() diff --git a/sbapp/plyer/platforms/android/audio.py b/sbapp/plyer/platforms/android/audio.py deleted file mode 100644 index 33a0a0d..0000000 --- a/sbapp/plyer/platforms/android/audio.py +++ /dev/null @@ -1,108 +0,0 @@ -import time -import threading -from jnius import autoclass - -from plyer.facades.audio import Audio - -# Recorder Classes -MediaRecorder = autoclass('android.media.MediaRecorder') -AudioSource = autoclass('android.media.MediaRecorder$AudioSource') -OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat') -AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder') - -# Player Classes -MediaPlayer = autoclass('android.media.MediaPlayer') - - -class AndroidAudio(Audio): - '''Audio for android. - - For recording audio we use MediaRecorder Android class. - For playing audio we use MediaPlayer Android class. - ''' - - def __init__(self, file_path=None): - default_path = None - super().__init__(file_path or default_path) - - self._recorder = None - self._player = None - self._check_thread = None - self._finished_callback = None - self._format = "opus" - self.is_playing = False - - def _check_playback(self): - while self._player and self._player.isPlaying(): - time.sleep(0.25) - - self.is_playing = False - - if self._finished_callback and callable(self._finished_callback): - self._check_thread = None - self._finished_callback(self) - - - def _start(self): - self._recorder = MediaRecorder() - if self._format == "aac": - self._recorder.setAudioSource(AudioSource.DEFAULT) - self._recorder.setAudioSamplingRate(48000) - self._recorder.setAudioEncodingBitRate(64000) - self._recorder.setAudioChannels(1) - self._recorder.setOutputFormat(OutputFormat.MPEG_4) - self._recorder.setAudioEncoder(AudioEncoder.AAC) - - else: - self._recorder.setAudioSource(AudioSource.DEFAULT) - self._recorder.setAudioSamplingRate(48000) - self._recorder.setAudioEncodingBitRate(12000) - self._recorder.setAudioChannels(1) - self._recorder.setOutputFormat(OutputFormat.OGG) - self._recorder.setAudioEncoder(AudioEncoder.OPUS) - - self._recorder.setOutputFile(self.file_path) - - self._recorder.prepare() - self._recorder.start() - - def _stop(self): - if self._recorder: - try: - self._recorder.stop() - self._recorder.release() - except Exception as e: - print("Could not stop recording: "+str(e)) - - self._recorder = None - - if self._player: - try: - self._player.stop() - self._player.release() - except Exception as e: - print("Could not stop playback: "+str(e)) - - self._player = None - - self.is_playing = False - - def _play(self): - self._player = MediaPlayer() - self._player.setDataSource(self.file_path) - self._player.prepare() - self._player.start() - self.is_playing = True - - self._check_thread = threading.Thread(target=self._check_playback, daemon=True) - self._check_thread.start() - - def reload(self): - self._stop() - - def playing(self): - return self.is_playing - - -def instance(): - return AndroidAudio() diff --git a/sbapp/plyer/platforms/ios/__init__.py b/sbapp/plyer/platforms/ios/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/sbapp/plyer/platforms/ios/accelerometer.py b/sbapp/plyer/platforms/ios/accelerometer.py deleted file mode 100644 index 0f61f2b..0000000 --- a/sbapp/plyer/platforms/ios/accelerometer.py +++ /dev/null @@ -1,34 +0,0 @@ -''' -iOS accelerometer ------------------ - -Taken from: http://pyobjus.readthedocs.org/en/latest/pyobjus_ios.html \ - #accessing-accelerometer -''' - -from sbapp.plyer.facades import Accelerometer -from pyobjus import autoclass - - -class IosAccelerometer(Accelerometer): - - def __init__(self): - super().__init__() - self.bridge = autoclass('bridge').alloc().init() - self.bridge.motionManager.setAccelerometerUpdateInterval_(0.1) - - def _enable(self): - self.bridge.startAccelerometer() - - def _disable(self): - self.bridge.stopAccelerometer() - - def _get_acceleration(self): - return ( - self.bridge.ac_x, - self.bridge.ac_y, - self.bridge.ac_z) - - -def instance(): - return IosAccelerometer() diff --git a/sbapp/plyer/platforms/ios/barometer.py b/sbapp/plyer/platforms/ios/barometer.py deleted file mode 100644 index 9ec8d6e..0000000 --- a/sbapp/plyer/platforms/ios/barometer.py +++ /dev/null @@ -1,31 +0,0 @@ -''' -iOS Barometer -------------- -''' - -from sbapp.plyer.facades import Barometer -from pyobjus import autoclass - - -class iOSBarometer(Barometer): - - def __init__(self): - super().__init__() - self.bridge = autoclass('bridge').alloc().init() - - def _enable(self): - self.bridge.startRelativeAltitude() - - def _disable(self): - self.bridge.stopRelativeAltitude() - - def _get_pressure(self): - ''' - 1 kPa = 10 hPa - ''' - return ( - self.bridge.pressure * 10) - - -def instance(): - return iOSBarometer() diff --git a/sbapp/plyer/platforms/ios/battery.py b/sbapp/plyer/platforms/ios/battery.py deleted file mode 100644 index d7fa5d8..0000000 --- a/sbapp/plyer/platforms/ios/battery.py +++ /dev/null @@ -1,47 +0,0 @@ -''' -Module of iOS API for plyer.battery. -''' - -from pyobjus import autoclass -from pyobjus.dylib_manager import load_framework -from sbapp.plyer.facades import Battery - -load_framework('/System/Library/Frameworks/UIKit.framework') -UIDevice = autoclass('UIDevice') - - -class IOSBattery(Battery): - ''' - Implementation of iOS battery API. - ''' - - def __init__(self): - super().__init__() - self.device = UIDevice.currentDevice() - - def _get_state(self): - status = {"isCharging": None, "percentage": None} - - if not self.device.batteryMonitoringEnabled: - self.device.setBatteryMonitoringEnabled_(True) - - if self.device.batteryState == 0: - is_charging = None - elif self.device.batteryState == 2: - is_charging = True - else: - is_charging = False - - percentage = self.device.batteryLevel * 100. - - status['isCharging'] = is_charging - status['percentage'] = percentage - - return status - - -def instance(): - ''' - Instance for facade proxy. - ''' - return IOSBattery() diff --git a/sbapp/plyer/platforms/ios/brightness.py b/sbapp/plyer/platforms/ios/brightness.py deleted file mode 100644 index f4a70f4..0000000 --- a/sbapp/plyer/platforms/ios/brightness.py +++ /dev/null @@ -1,27 +0,0 @@ -''' -iOS Brightness --------------- -''' - -from pyobjus import autoclass -from sbapp.plyer.facades import Brightness -from pyobjus.dylib_manager import load_framework - -load_framework('/System/Library/Frameworks/UIKit.framework') -UIScreen = autoclass('UIScreen') - - -class iOSBrightness(Brightness): - - def __init__(self): - self.screen = UIScreen.mainScreen() - - def _current_level(self): - return self.screen.brightness * 100 - - def set_level(self, level): - self.screen.brightness = level / 100 - - -def instance(): - return iOSBrightness() diff --git a/sbapp/plyer/platforms/ios/call.py b/sbapp/plyer/platforms/ios/call.py deleted file mode 100644 index 9999d6a..0000000 --- a/sbapp/plyer/platforms/ios/call.py +++ /dev/null @@ -1,29 +0,0 @@ -''' -IOS Call ----------- -''' - -from sbapp.plyer.facades import Call -from pyobjus import autoclass, objc_str - -NSURL = autoclass('NSURL') -NSString = autoclass('NSString') -UIApplication = autoclass('UIApplication') - - -class IOSCall(Call): - - def _makecall(self, **kwargs): - tel = kwargs.get('tel') - url = "tel://" + tel - nsurl = NSURL.alloc().initWithString_(objc_str(url)) - - UIApplication.sharedApplication().openURL_(nsurl) - - def _dialcall(self, **kwargs): - pass - # Not possible, Access not provided by iPhone SDK - - -def instance(): - return IOSCall() diff --git a/sbapp/plyer/platforms/ios/camera.py b/sbapp/plyer/platforms/ios/camera.py deleted file mode 100644 index a61bd96..0000000 --- a/sbapp/plyer/platforms/ios/camera.py +++ /dev/null @@ -1,52 +0,0 @@ -from os import remove -from sbapp.plyer.facades import Camera - -from sbapp.plyer.utils import reify - - -class iOSCamera(Camera): - - @reify - def photos(self): - # pyPhotoLibrary is a ios recipe/module that - # interacts with the gallery and the camera on ios. - from photolibrary import PhotosLibrary - return PhotosLibrary() - - def _take_picture(self, on_complete, filename=None): - assert on_complete is not None - self.on_complete = on_complete - self.filename = filename - photos = self.photos - - if not photos.isCameraAvailable(): - # no camera hardware - return False - - photos.bind(on_image_captured=self.capture_callback) - self._capture_filename = filename - photos.capture_image(filename) - return True - - def capture_callback(self, photolibrary): - # Image was chosen - - # unbind - self.photos.unbind(on_image_captured=self.capture_callback) - - if self.on_complete(self.filename): - self._remove(self.filename) - - def _take_video(self, on_complete, filename=None): - assert on_complete is not None - raise NotImplementedError - - def _remove(self, fn): - try: - remove(fn) - except OSError: - print('Could not remove photo!') - - -def instance(): - return iOSCamera() diff --git a/sbapp/plyer/platforms/ios/compass.py b/sbapp/plyer/platforms/ios/compass.py deleted file mode 100644 index a5c865f..0000000 --- a/sbapp/plyer/platforms/ios/compass.py +++ /dev/null @@ -1,43 +0,0 @@ -''' -iOS Compass ------------ -''' - -from sbapp.plyer.facades import Compass -from pyobjus import autoclass - - -class IosCompass(Compass): - - def __init__(self): - super().__init__() - self.bridge = autoclass('bridge').alloc().init() - self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1) - self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) - - def _enable(self): - self.bridge.startMagnetometer() - self.bridge.startDeviceMotionWithReferenceFrame() - - def _disable(self): - self.bridge.stopMagnetometer() - self.bridge.stopDeviceMotion() - - def _get_orientation(self): - return ( - self.bridge.mf_x, - self.bridge.mf_y, - self.bridge.mf_z) - - def _get_field_uncalib(self): - return ( - self.bridge.mg_x, - self.bridge.mg_y, - self.bridge.mg_z, - self.bridge.mg_x - self.bridge.mf_x, - self.bridge.mg_y - self.bridge.mf_y, - self.bridge.mg_z - self.bridge.mf_z) - - -def instance(): - return IosCompass() diff --git a/sbapp/plyer/platforms/ios/email.py b/sbapp/plyer/platforms/ios/email.py deleted file mode 100644 index ec54860..0000000 --- a/sbapp/plyer/platforms/ios/email.py +++ /dev/null @@ -1,52 +0,0 @@ -''' -Module of iOS API for plyer.email. -''' - -try: - from urllib.parse import quote -except ImportError: - from urllib import quote - -from sbapp.plyer.facades import Email -from pyobjus import autoclass, objc_str -from pyobjus.dylib_manager import load_framework - -load_framework('/System/Library/Frameworks/UIKit.framework') - -NSURL = autoclass('NSURL') -NSString = autoclass('NSString') -UIApplication = autoclass('UIApplication') - - -class IOSEmail(Email): - ''' - Implementation of iOS battery API. - ''' - - def _send(self, **kwargs): - recipient = kwargs.get('recipient') - subject = kwargs.get('subject') - text = kwargs.get('text') - - uri = "mailto:" - if recipient: - uri += str(recipient) - if subject: - uri += "?" if "?" not in uri else "&" - uri += "subject=" - uri += quote(str(subject)) - if text: - uri += "?" if "?" not in uri else "&" - uri += "body=" - uri += quote(str(text)) - - nsurl = NSURL.alloc().initWithString_(objc_str(uri)) - - UIApplication.sharedApplication().openURL_(nsurl) - - -def instance(): - ''' - Instance for facade proxy. - ''' - return IOSEmail() diff --git a/sbapp/plyer/platforms/ios/filechooser.py b/sbapp/plyer/platforms/ios/filechooser.py deleted file mode 100644 index 0320d6c..0000000 --- a/sbapp/plyer/platforms/ios/filechooser.py +++ /dev/null @@ -1,81 +0,0 @@ -''' -IOS file chooser --------------------- - -This module houses the iOS implementation of the plyer FileChooser. - -.. versionadded:: 1.4.4 -''' - -from sbapp.plyer.facades import FileChooser -from pyobjus import autoclass, protocol -from pyobjus.dylib_manager import load_framework - - -load_framework('/System/Library/Frameworks/Photos.framework') - - -class IOSFileChooser(FileChooser): - ''' - FileChooser implementation for IOS using - the built-in file browser via UIImagePickerController. - - .. versionadded:: 1.4.0 - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._on_selection = None - - def _file_selection_dialog(self, *args, **kwargs): - """ - Function called when action is required, A "mode" parameter specifies - which and is one of "open", "save" or "dir". - """ - self._on_selection = kwargs["on_selection"] - if kwargs["mode"] == "open": - self._open() - else: - raise NotImplementedError() - - def _get_picker(self): - """ - Return an instantiated and configured UIImagePickerController. - """ - picker = autoclass("UIImagePickerController") - po = picker.alloc().init() - po.sourceType = 0 - po.delegate = self - return po - - def _open(self): - """ - Launch the native iOS file browser. Upon selection, the - `imagePickerController_didFinishPickingMediaWithInfo_` delegate is - called where we close the file browser and handle the result. - """ - picker = self._get_picker() - UIApplication = autoclass('UIApplication') - vc = UIApplication.sharedApplication().keyWindow.rootViewController() - vc.presentViewController_animated_completion_(picker, True, None) - - @protocol('UIImagePickerControllerDelegate') - def imagePickerController_didFinishPickingMediaWithInfo_( - self, image_picker, frozen_dict): - """ - Delegate which handles the result of the image selection process. - """ - image_picker.dismissViewControllerAnimated_completion_(True, None) - - # Note: We need to call this Objective C class as there is currently - # no way to call a non-class function via pyobjus. And here, - # we have to use the `UIImagePNGRepresentation` to get the png - # representation. For this, please ensure you are using an - # appropriate version of kivy-ios. - native_image_picker = autoclass("NativeImagePicker").alloc().init() - path = native_image_picker.writeToPNG_(frozen_dict) - self._on_selection([path.UTF8String()]) - - -def instance(): - return IOSFileChooser() diff --git a/sbapp/plyer/platforms/ios/flash.py b/sbapp/plyer/platforms/ios/flash.py deleted file mode 100644 index 17f59f1..0000000 --- a/sbapp/plyer/platforms/ios/flash.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -""" -Flash ------ -""" -from sbapp.plyer.facades import Flash -from pyobjus import autoclass - -NSString = autoclass("NSString") -AVCaptureDevice = autoclass("AVCaptureDevice") -AVMediaTypeVideo = NSString.alloc().initWithUTF8String_("vide") -AVCaptureTorchModeOff = 0 -AVCaptureTorchModeOn = 1 - - -class IosFlash(Flash): - _camera = None - - def _on(self): - if self._camera is None: - self._camera_open() - if not self._camera: - return - self._camera.lockForConfiguration_(None) - try: - self._camera.setTorchMode(AVCaptureTorchModeOn) - finally: - self._camera.unlockForConfiguration() - - def _off(self): - if not self._camera: - return - self._camera.lockForConfiguration_(None) - try: - self._camera.setTorchMode(AVCaptureTorchModeOff) - finally: - self._camera.unlockForConfiguration() - - def _release(self): - pass - - def _camera_open(self): - device = AVCaptureDevice.defaultDeviceWithMediaType_(AVMediaTypeVideo) - if not device: - return - self._camera = device - - -def instance(): - return IosFlash() diff --git a/sbapp/plyer/platforms/ios/gps.py b/sbapp/plyer/platforms/ios/gps.py deleted file mode 100644 index d7ee0a7..0000000 --- a/sbapp/plyer/platforms/ios/gps.py +++ /dev/null @@ -1,80 +0,0 @@ -''' -iOS GPS ------------ -''' - -from pyobjus import autoclass, protocol -from pyobjus.dylib_manager import load_framework -from sbapp.plyer.facades import GPS - -load_framework('/System/Library/Frameworks/CoreLocation.framework') -CLLocationManager = autoclass('CLLocationManager') - - -class IosGPS(GPS): - def _configure(self): - if not hasattr(self, '_location_manager'): - self._location_manager = CLLocationManager.alloc().init() - - def _start(self, **kwargs): - self._location_manager.delegate = self - - self._location_manager.requestWhenInUseAuthorization() - # NSLocationWhenInUseUsageDescription key must exist in Info.plist - # file. When the authorization prompt is displayed your app goes - # into pause mode and if your app doesn't support background mode - # it will crash. - self._location_manager.startUpdatingLocation() - - def _stop(self): - self._location_manager.stopUpdatingLocation() - - @protocol('CLLocationManagerDelegate') - def locationManager_didChangeAuthorizationStatus_(self, manager, status): - if self.on_status: - s_status = '' - provider_status = '' - provider = 'standard-ios-provider' - if status == 0: - provider_status = 'provider-disabled' - s_status = 'notDetermined' - elif status == 1: - provider_status = 'provider-enabled' - s_status = 'restricted' - elif status == 2: - provider_status = 'provider-disabled' - s_status = 'denied' - elif status == 3: - provider_status = 'provider-enabled' - s_status = 'authorizedAlways' - elif status == 4: - provider_status = 'provider-enabled' - s_status = 'authorizedWhenInUse' - self.on_status(provider_status, '{}: {}'.format( - provider, s_status)) - - @protocol('CLLocationManagerDelegate') - def locationManager_didUpdateLocations_(self, manager, locations): - location = manager.location - - description = location.description.UTF8String() - split_description = description.split('<')[-1].split('>')[0].split(',') - - lat, lon = [float(coord) for coord in split_description] - acc = float(description.split(' +/- ')[-1].split('m ')[0]) - - speed = location.speed - altitude = location.altitude - course = location.course - - self.on_location( - lat=lat, - lon=lon, - speed=speed, - bearing=course, - altitude=altitude, - accuracy=acc) - - -def instance(): - return IosGPS() diff --git a/sbapp/plyer/platforms/ios/gravity.py b/sbapp/plyer/platforms/ios/gravity.py deleted file mode 100644 index 9452bda..0000000 --- a/sbapp/plyer/platforms/ios/gravity.py +++ /dev/null @@ -1,31 +0,0 @@ -''' -iOS Gravity ------------ - -''' - -from sbapp.plyer.facades import Gravity -from pyobjus import autoclass - - -class iOSGravity(Gravity): - - def __init__(self): - self.bridge = autoclass('bridge').alloc().init() - self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) - - def _enable(self): - self.bridge.startDeviceMotion() - - def _disable(self): - self.bridge.stopDeviceMotion() - - def _get_gravity(self): - return ( - self.bridge.g_x, - self.bridge.g_y, - self.bridge.g_z) - - -def instance(): - return iOSGravity() diff --git a/sbapp/plyer/platforms/ios/gyroscope.py b/sbapp/plyer/platforms/ios/gyroscope.py deleted file mode 100644 index 367e1bf..0000000 --- a/sbapp/plyer/platforms/ios/gyroscope.py +++ /dev/null @@ -1,55 +0,0 @@ -''' -iOS Gyroscope ---------------------- -''' - -from sbapp.plyer.facades import Gyroscope -from pyobjus import autoclass - -from pyobjus.dylib_manager import load_framework - -load_framework('/System/Library/Frameworks/UIKit.framework') -UIDevice = autoclass('UIDevice') - -device = UIDevice.currentDevice() - - -class IosGyroscope(Gyroscope): - - def __init__(self): - super().__init__() - self.bridge = autoclass('bridge').alloc().init() - - if int(device.systemVersion.UTF8String().split('.')[0]) <= 4: - self.bridge.motionManager.setGyroscopeUpdateInterval_(0.1) - else: - self.bridge.motionManager.setGyroUpdateInterval_(0.1) - - self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) - - def _enable(self): - self.bridge.startGyroscope() - self.bridge.startDeviceMotion() - - def _disable(self): - self.bridge.stopGyroscope() - self.bridge.stopDeviceMotion() - - def _get_orientation(self): - return ( - self.bridge.rotation_rate_x, - self.bridge.rotation_rate_y, - self.bridge.rotation_rate_z) - - def _get_rotation_uncalib(self): - return ( - self.bridge.gy_x, - self.bridge.gy_y, - self.bridge.gy_z, - self.bridge.gy_x - self.bridge.rotation_rate_x, - self.bridge.gy_y - self.bridge.rotation_rate_y, - self.bridge.gy_z - self.bridge.rotation_rate_z) - - -def instance(): - return IosGyroscope() diff --git a/sbapp/plyer/platforms/ios/keystore.py b/sbapp/plyer/platforms/ios/keystore.py deleted file mode 100644 index a18cde2..0000000 --- a/sbapp/plyer/platforms/ios/keystore.py +++ /dev/null @@ -1,23 +0,0 @@ -from sbapp.plyer.facades import Keystore -from pyobjus import autoclass, objc_str - -NSUserDefaults = autoclass('NSUserDefaults') - - -class IosKeystore(Keystore): - - def _set_key(self, servicename, key, value, **kwargs): - NSUserDefaults.standardUserDefaults().setObject_forKey_( - objc_str(value), objc_str(key)) - - def _get_key(self, servicename, key, **kwargs): - ret = NSUserDefaults.standardUserDefaults().stringForKey_( - objc_str(key)) - if ret is not None: - return ret.UTF8String() - else: - return ret - - -def instance(): - return IosKeystore() diff --git a/sbapp/plyer/platforms/ios/maps.py b/sbapp/plyer/platforms/ios/maps.py deleted file mode 100644 index dac01d5..0000000 --- a/sbapp/plyer/platforms/ios/maps.py +++ /dev/null @@ -1,78 +0,0 @@ -''' -Module of iOS API for plyer.maps. -''' - -import webbrowser -from sbapp.plyer.facades import Maps -from urllib.parse import quote_plus - - -class iOSMaps(Maps): - ''' - Implementation of iOS Maps API. - ''' - - def _open_by_address(self, address, **kwargs): - ''' - :param address: An address string that geolocation can understand. - ''' - - address = quote_plus(address, safe=',') - maps_address = 'http://maps.apple.com/?address=' + address - - webbrowser.open(maps_address) - - def _open_by_lat_long(self, latitude, longitude, **kwargs): - ''' - Open a coordinate span denoting a latitudinal delta and a - longitudinal delta (similar to MKCoordinateSpan) - - :param name: (optional), will set the name of the dropped pin - ''' - - name = kwargs.get("name", "Selected Location") - maps_address = 'http://maps.apple.com/?ll={},{}&q={}'.format( - latitude, longitude, name) - - webbrowser.open(maps_address) - - def _search(self, query, **kwargs): - ''' - :param query: A string that describes the search object (ex. "Pizza") - - :param latitude: (optional), narrow down query within area, - MUST BE USED WITH LONGITUDE - - :param longitude: (optional), narrow down query within area, - MUST BE USED WITH LATITUDE - ''' - - latitude = kwargs.get('latitude') - longitude = kwargs.get('longitude') - - query = quote_plus(query, safe=',') - maps_address = 'http://maps.apple.com/?q=' + query - - if latitude is not None and longitude is not None: - maps_address += '&sll={},{}'.format(latitude, longitude) - - webbrowser.open(maps_address) - - def _route(self, saddr, daddr, **kwargs): - ''' - :param saddr: can be given as 'address' or 'lat,long' - :param daddr: can be given as 'address' or 'lat,long' - ''' - saddr = quote_plus(saddr, safe=',') - daddr = quote_plus(daddr, safe=',') - - maps_address = 'http://maps.apple.com/?saddr={}&daddr={}'.format( - saddr, daddr) - webbrowser.open(maps_address) - - -def instance(): - ''' - Instance for facade proxy. - ''' - return iOSMaps() diff --git a/sbapp/plyer/platforms/ios/sms.py b/sbapp/plyer/platforms/ios/sms.py deleted file mode 100644 index fc6b1b4..0000000 --- a/sbapp/plyer/platforms/ios/sms.py +++ /dev/null @@ -1,43 +0,0 @@ -''' -IOS Sms ----------- -''' - -from sbapp.plyer.facades import Sms -from pyobjus import autoclass, objc_str -from pyobjus.dylib_manager import load_framework - -NSURL = autoclass('NSURL') -NSString = autoclass('NSString') -UIApplication = autoclass('UIApplication') -load_framework('/System/Library/Frameworks/MessageUI.framework') - - -class IOSSms(Sms): - - def _send(self, **kwargs): - ''' - This method provides sending messages to recipients. - - Expects 2 parameters in kwargs: - - recipient: String type - - message: String type - - Opens a message interface with recipient and message information. - ''' - recipient = kwargs.get('recipient') - message = kwargs.get('message') - url = "sms:" - if recipient: - # Apple has not supported multiple recipients yet. - url += str(recipient) - if message: - # Apple has to supported it yet. - pass - - nsurl = NSURL.alloc().initWithString_(objc_str(url)) - UIApplication.sharedApplication().openURL_(nsurl) - - -def instance(): - return IOSSms() diff --git a/sbapp/plyer/platforms/ios/spatialorientation.py b/sbapp/plyer/platforms/ios/spatialorientation.py deleted file mode 100644 index 7c6d9cc..0000000 --- a/sbapp/plyer/platforms/ios/spatialorientation.py +++ /dev/null @@ -1,31 +0,0 @@ -''' -iOS Spatial Orientation ------------------------ - -''' - -from sbapp.plyer.facades import SpatialOrientation -from pyobjus import autoclass - - -class iOSSpatialOrientation(SpatialOrientation): - - def __init__(self): - self.bridge = autoclass('bridge').alloc().init() - self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) - - def _enable_listener(self): - self.bridge.startDeviceMotion() - - def _disable_listener(self): - self.bridge.stopDeviceMotion() - - def _get_orientation(self): - return ( - self.bridge.sp_yaw, - self.bridge.sp_pitch, - self.bridge.sp_roll) - - -def instance(): - return iOSSpatialOrientation() diff --git a/sbapp/plyer/platforms/ios/storagepath.py b/sbapp/plyer/platforms/ios/storagepath.py deleted file mode 100644 index c69a083..0000000 --- a/sbapp/plyer/platforms/ios/storagepath.py +++ /dev/null @@ -1,62 +0,0 @@ -''' -iOS Storage Path --------------------- -''' - -from sbapp.plyer.facades import StoragePath -from pyobjus import autoclass -import os - -NSFileManager = autoclass('NSFileManager') - -# Directory constants (NSSearchPathDirectory enumeration) -NSApplicationDirectory = 1 -NSDocumentDirectory = 9 -NSDownloadsDirectory = 15 -NSMoviesDirectory = 17 -NSMusicDirectory = 18 -NSPicturesDirectory = 19 - - -class iOSStoragePath(StoragePath): - - def __init__(self): - self.defaultManager = NSFileManager.defaultManager() - - def _get_home_dir(self): - return os.path.expanduser('~/') - - def _get_external_storage_dir(self): - return 'This feature is not implemented for this platform.' - - def _get_root_dir(self): - return 'This feature is not implemented for this platform.' - - def _get_documents_dir(self): - return self.defaultManager.URLsForDirectory_inDomains_( - NSDocumentDirectory, 1).firstObject().absoluteString.UTF8String() - - def _get_downloads_dir(self): - return self.defaultManager.URLsForDirectory_inDomains_( - NSDownloadsDirectory, 1).firstObject().absoluteString.UTF8String() - - def _get_videos_dir(self): - return self.defaultManager.URLsForDirectory_inDomains_( - NSMoviesDirectory, 1).firstObject().absoluteString.UTF8String() - - def _get_music_dir(self): - return self.defaultManager.URLsForDirectory_inDomains_( - NSMusicDirectory, 1).firstObject().absoluteString.UTF8String() - - def _get_pictures_dir(self): - return self.defaultManager.URLsForDirectory_inDomains_( - NSPicturesDirectory, 1).firstObject().absoluteString.UTF8String() - - def _get_application_dir(self): - return self.defaultManager.URLsForDirectory_inDomains_( - NSApplicationDirectory, 1).firstObject().absoluteString.\ - UTF8String() - - -def instance(): - return iOSStoragePath() diff --git a/sbapp/plyer/platforms/ios/tts.py b/sbapp/plyer/platforms/ios/tts.py deleted file mode 100644 index 510399d..0000000 --- a/sbapp/plyer/platforms/ios/tts.py +++ /dev/null @@ -1,37 +0,0 @@ -from pyobjus import autoclass, objc_str -from pyobjus.dylib_manager import load_framework - -from sbapp.plyer.facades import TTS - -load_framework('/System/Library/Frameworks/AVFoundation.framework') -AVSpeechUtterance = autoclass('AVSpeechUtterance') -AVSpeechSynthesizer = autoclass('AVSpeechSynthesizer') -AVSpeechSynthesisVoice = autoclass('AVSpeechSynthesisVoice') - - -class iOSTextToSpeech(TTS): - def __init__(self): - super().__init__() - self.synth = AVSpeechSynthesizer.alloc().init() - self.voice = None - - def _set_locale(self, locale="en-US"): - self.voice = AVSpeechSynthesisVoice.voiceWithLanguage_( - objc_str(locale) - ) - - def _speak(self, **kwargs): - message = kwargs.get('message') - - if not self.voice: - self._set_locale() - - utterance = \ - AVSpeechUtterance.speechUtteranceWithString_(objc_str(message)) - - utterance.voice = self.voice - self.synth.speakUtterance_(utterance) - - -def instance(): - return iOSTextToSpeech() diff --git a/sbapp/plyer/platforms/ios/uniqueid.py b/sbapp/plyer/platforms/ios/uniqueid.py deleted file mode 100644 index e9fa815..0000000 --- a/sbapp/plyer/platforms/ios/uniqueid.py +++ /dev/null @@ -1,27 +0,0 @@ -''' -Module of iOS API for plyer.uniqueid. -''' - -from pyobjus import autoclass -from pyobjus.dylib_manager import load_framework -from sbapp.plyer.facades import UniqueID - -load_framework('/System/Library/Frameworks/UIKit.framework') -UIDevice = autoclass('UIDevice') - - -class IOSUniqueID(UniqueID): - ''' - Implementation of iOS uniqueid API. - ''' - - def _get_uid(self): - uuid = UIDevice.currentDevice().identifierForVendor.UUIDString() - return uuid.UTF8String() - - -def instance(): - ''' - Instance for facade proxy. - ''' - return IOSUniqueID() diff --git a/sbapp/plyer/platforms/ios/vibrator.py b/sbapp/plyer/platforms/ios/vibrator.py deleted file mode 100644 index 05c12c5..0000000 --- a/sbapp/plyer/platforms/ios/vibrator.py +++ /dev/null @@ -1,43 +0,0 @@ -'''Implementation Vibrator for iOS. - -Install: Add AudioToolbox framework to your application. -''' - -import ctypes -from sbapp.plyer.facades import Vibrator - - -class IosVibrator(Vibrator): - '''iOS Vibrator class. - - iOS doesn't support any feature. - All time, pattern, repetition are ignored. - ''' - - def __init__(self): - super().__init__() - try: - self._func = ctypes.CDLL(None).AudioServicesPlaySystemSound - except AttributeError: - self._func = None - - def _vibrate(self, time=None, **kwargs): - # kSystemSoundID_Vibrate is 0x00000FFF - self._func(0xFFF) - - def _pattern(self, pattern=None, repeat=None, **kwargs): - self._vibrate() - - def _exists(self, **kwargs): - return self._func is not None - - def _cancel(self, **kwargs): - pass - - -def instance(): - '''Returns Vibrator - - :return: instance of class IosVibrator - ''' - return IosVibrator() diff --git a/sbapp/plyer/platforms/linux/audio.py b/sbapp/plyer/platforms/linux/audio.py deleted file mode 100644 index 091e9e5..0000000 --- a/sbapp/plyer/platforms/linux/audio.py +++ /dev/null @@ -1,139 +0,0 @@ -import time -import threading -import RNS -import io -from sbapp.plyer.facades.audio import Audio -from ffpyplayer.player import MediaPlayer -from sbapp.pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter -import pyaudio - -class LinuxAudio(Audio): - - def __init__(self, file_path=None): - default_path = None - super().__init__(file_path or default_path) - - self._recorder = None - self._player = None - self._check_thread = None - self._finished_callback = None - self._loaded_path = None - self.sound = None - self.pa = None - self.is_playing = False - self.recorder = None - self.should_record = False - - def _check_playback(self): - run = True - while run and self.sound != None and not self.sound.get_pause(): - time.sleep(0.25) - if self.duration: - pts = self.sound.get_pts() - if pts > self.duration: - run = False - - self.is_playing = False - - if self._finished_callback and callable(self._finished_callback): - self._check_thread = None - self._finished_callback(self) - - def _record_job(self): - samples_per_second = self.default_rate; - bytes_per_sample = 2; frame_duration_ms = 20 - opus_buffered_encoder = OpusBufferedEncoder() - opus_buffered_encoder.set_application("voip") - opus_buffered_encoder.set_sampling_frequency(samples_per_second) - opus_buffered_encoder.set_channels(1) - opus_buffered_encoder.set_frame_size(frame_duration_ms) - ogg_opus_writer = OggOpusWriter(self._file_path, opus_buffered_encoder) - - frame_duration = frame_duration_ms/1000 - frame_size = int(frame_duration * samples_per_second) - bytes_per_frame = frame_size*bytes_per_sample - - read_bytes = 0 - pcm_buf = b"" - should_continue = True - while self.should_record and self.recorder: - samples_available = self.recorder.get_read_available() - bytes_available = samples_available*bytes_per_sample - if bytes_available > 0: - read_req = bytes_per_frame - len(pcm_buf) - read_n = min(bytes_available, read_req) - read_s = read_n//bytes_per_sample - rb = self.recorder.read(read_s); read_bytes += len(rb) - pcm_buf += rb - - if len(pcm_buf) == bytes_per_frame: - ogg_opus_writer.write(memoryview(bytearray(pcm_buf))) - # RNS.log("Wrote frame of "+str(len(pcm_buf))+", expected size "+str(bytes_per_frame)) - pcm_buf = b"" - - # Finish up anything left in buffer - time.sleep(frame_duration) - samples_available = self.recorder.get_read_available() - bytes_available = samples_available*bytes_per_sample - if bytes_available > 0: - read_req = bytes_per_frame - len(pcm_buf) - read_n = min(bytes_available, read_req) - read_s = read_n//bytes_per_sample - rb = self.recorder.read(read_s); read_bytes += len(rb) - pcm_buf += rb - - if len(pcm_buf) == bytes_per_frame: - ogg_opus_writer.write(memoryview(bytearray(pcm_buf))) - # RNS.log("Wrote frame of "+str(len(pcm_buf))+", expected size "+str(bytes_per_frame)) - pcm_buf = b"" - - ogg_opus_writer.close() - if self.recorder: - self.recorder.close() - - def _start(self): - self.should_record = True - if self.pa == None: - self.pa = pyaudio.PyAudio() - self.default_input_device = self.pa.get_default_input_device_info() - self.default_rate = 48000 - # self.default_rate = int(self.default_input_device["defaultSampleRate"]) - if self.recorder: - self.recorder.close() - self.recorder = None - self.recorder = self.pa.open(self.default_rate, 1, pyaudio.paInt16, input=True) - threading.Thread(target=self._record_job, daemon=True).start() - - def _stop(self): - if self.should_record == True: - self.should_record = False - - elif self.sound != None: - self.sound.set_pause(True) - self.sound.seek(0, relative=False) - self.is_playing = False - - def _play(self): - self.sound = MediaPlayer(self._file_path) - self.metadata = self.sound.get_metadata() - self.duration = self.metadata["duration"] - if self.duration == None: - time.sleep(0.15) - self.metadata = self.sound.get_metadata() - self.duration = self.metadata["duration"] - - self._loaded_path = self._file_path - self.is_playing = True - - self._check_thread = threading.Thread(target=self._check_playback, daemon=True) - self._check_thread.start() - - def reload(self): - self._loaded_path = None - - def playing(self): - return self.is_playing - - -def instance(): - return LinuxAudio() diff --git a/sbapp/plyer/platforms/macosx/audio.py b/sbapp/plyer/platforms/macosx/audio.py deleted file mode 100644 index 1f2069e..0000000 --- a/sbapp/plyer/platforms/macosx/audio.py +++ /dev/null @@ -1,128 +0,0 @@ -from os.path import join - -from pyobjus import autoclass -from pyobjus.dylib_manager import INCLUDE, load_framework - -from sbapp.plyer.facades import Audio -from sbapp.plyer.platforms.macosx.storagepath import OSXStoragePath - -import threading - -load_framework(INCLUDE.Foundation) -load_framework(INCLUDE.AVFoundation) - -AVAudioPlayer = autoclass("AVAudioPlayer") -AVAudioRecorder = autoclass("AVAudioRecorder") -AVAudioFormat = autoclass("AVAudioFormat") -NSString = autoclass('NSString') -NSURL = autoclass('NSURL') -NSError = autoclass('NSError').alloc() - - -class OSXAudio(Audio): - def __init__(self, file_path=None): - default_path = None - super().__init__(file_path or default_path) - - self._recorder = None - self._player = None - self._current_file = None - - self._check_thread = None - self._finished_callback = None - self._loaded_path = None - self.is_playing = False - self.sound = None - self.pa = None - self.is_playing = False - self.recorder = None - self.should_record = False - - def _check_playback(self): - while self._player and self._player.isPlaying: - time.sleep(0.25) - - if self._finished_callback and callable(self._finished_callback): - self._check_thread = None - self._finished_callback(self) - - def _start(self): - # Conversion of Python file path string to Objective-C NSString - file_path_NSString = NSString.alloc() - file_path_NSString = file_path_NSString.initWithUTF8String_( - self._file_path - ) - - # Definition of Objective-C NSURL object for the output record file - # specified by NSString file path - file_NSURL = NSURL.alloc() - file_NSURL = file_NSURL.initWithString_(file_path_NSString) - - # Internal audio file format specification - af = AVAudioFormat.alloc() - af = af.initWithCommonFormat_sampleRate_channels_interleaved_( - 1, 44100.0, 1, True - ) - - # Audio recorder instance initialization with specified file NSURL - # and audio file format - self._recorder = AVAudioRecorder.alloc() - self._recorder = self._recorder.initWithURL_format_error_( - file_NSURL, af, NSError - ) - - if not self._recorder: - raise Exception(NSError.code, NSError.domain) - - self._recorder.record() - - # Setting the currently recorded file as current file - # for using it as a parameter in audio player - self._current_file = file_NSURL - - def _stop(self): - if self._recorder: - self._recorder.stop() - self._recorder = None - - if self._player: - self._player.stop() - self._player = None - - def _play(self): - # Conversion of Python file path string to Objective-C NSString - file_path_NSString = NSString.alloc() - file_path_NSString = file_path_NSString.initWithUTF8String_( - self._file_path - ) - - # Definition of Objective-C NSURL object for the output record file - # specified by NSString file path - file_NSURL = NSURL.alloc() - file_NSURL = file_NSURL.initWithString_(file_path_NSString) - self._current_file = file_NSURL - - # Audio player instance initialization with the file NSURL - # of the last recorded audio file - self._player = AVAudioPlayer.alloc() - self._player = self._player.initWithContentsOfURL_error_( - self._current_file, NSError - ) - - if not self._player: - raise Exception(NSError.code, NSError.domain) - - self._player.play() - - self._check_thread = threading.Thread(target=self._check_playback, daemon=True) - self._check_thread.start() - - def reload(self): - self._loaded_path = None - - def playing(self): - return self.is_playing - - -def instance(): - return OSXAudio() diff --git a/sbapp/plyer/platforms/win/audio.py b/sbapp/plyer/platforms/win/audio.py deleted file mode 100644 index c74d97d..0000000 --- a/sbapp/plyer/platforms/win/audio.py +++ /dev/null @@ -1,413 +0,0 @@ -''' -Documentation: -http://docs.microsoft.com/en-us/windows/desktop/Multimedia - -.. versionadded:: 1.4.0 -''' - -from os.path import join - -from ctypes import windll -from ctypes import ( - sizeof, c_void_p, c_ulonglong, c_ulong, - c_wchar_p, byref, Structure, create_string_buffer -) -from ctypes.wintypes import DWORD, UINT - -from sbapp.plyer.facades import Audio -from sbapp.plyer.platforms.win.storagepath import WinStoragePath - -# DWORD_PTR i.e. ULONG_PTR, 32/64bit -ULONG_PTR = c_ulonglong if sizeof(c_void_p) == 8 else c_ulong - -# device specific symbols -MCI_OPEN = 0x803 -MCI_OPEN_TYPE = 0x2000 -MCI_OPEN_ELEMENT = 512 -MCI_RECORD = 0x80F -MCI_STOP = 0x808 -MCI_SAVE = 0x813 -MCI_PLAY = 0x806 -MCI_CLOSE = 0x804 - -# recorder specific symbols -MCI_FROM = 4 -MCI_TO = 8 -MCI_WAIT = 2 -MCI_SAVE_FILE = 256 - - -class MCI_OPEN_PARMS(Structure): - ''' - Struct for MCI_OPEN message parameters. - - .. versionadded:: 1.4.0 - ''' - - _fields_ = [ - ('mciOpenParms', ULONG_PTR), - ('wDeviceID', UINT), - ('lpstrDeviceType', c_wchar_p), - ('lpstrElementName', c_wchar_p), - ('lpstrAlias', c_wchar_p) - ] - - -class MCI_RECORD_PARMS(Structure): - ''' - Struct for MCI_RECORD message parameters. - - http://docs.microsoft.com/en-us/windows/desktop/Multimedia/mci-record-parms - - .. versionadded:: 1.4.0 - ''' - - _fields_ = [ - ('dwCallback', ULONG_PTR), - ('dwFrom', DWORD), - ('dwTo', DWORD) - ] - - -class MCI_SAVE_PARMS(Structure): - ''' - Struct for MCI_SAVE message parameters. - - http://docs.microsoft.com/en-us/windows/desktop/Multimedia/mci-save-parms - - .. versionadded:: 1.4.0 - ''' - - _fields_ = [ - ('dwCallback', ULONG_PTR), - ('lpfilename', c_wchar_p) - ] - - -class MCI_PLAY_PARMS(Structure): - ''' - Struct for MCI_PLAY message parameters. - - http://docs.microsoft.com/en-us/windows/desktop/Multimedia/mci-play-parms - - .. versionadded:: 1.4.0 - ''' - - _fields_ = [ - ('dwCallback', ULONG_PTR), - ('dwFrom', DWORD), - ('dwTo', DWORD) - ] - - -def send_command(device, msg, flags, params): - ''' - Generic mciSendCommandW() wrapper with error handler. - All parameters are required as for mciSendCommandW(). - In case of no `params` passed, use `None`, that value - won't be dereferenced. - - .. versionadded:: 1.4.0 - ''' - - multimedia = windll.winmm - send_command_w = multimedia.mciSendCommandW - get_error = multimedia.mciGetErrorStringW - - # error text buffer - # by API specification 128 is max, however the API sometimes - # kind of does not respect the documented bounds and returns - # more characters than buffer length...?! - error_len = 128 - - # big enough to prevent API accidentally segfaulting - error_text = create_string_buffer(error_len * 2) - - # open a recording device with a new file - error_code = send_command_w( - device, # device ID - msg, - flags, - - # reference to parameters structure or original value - # in case of params=False/0/None/... - byref(params) if params else params - ) - - # handle error messages if any - if error_code: - # device did not open, raise an exception - get_error(error_code, byref(error_text), error_len) - error_text = error_text.raw.replace(b'\x00', b'').decode('utf-8') - - # either it can close already open device or it will fail because - # the device is in non-closable state, but the end result is the same - # and it makes no sense to parse MCI_CLOSE's error in this case - send_command_w(device, MCI_CLOSE, 0, None) - raise Exception(error_code, error_text) - - # return params struct because some commands write into it - # to pass some values out of the local function scope - return params - - -class WinRecorder: - ''' - Generic wrapper for MCI_RECORD handling the filenames and device closing - in the same approach like it is used for other platforms. - - .. versionadded:: 1.4.0 - ''' - - def __init__(self, device, filename): - self._device = device - self._filename = filename - - @property - def device(self): - ''' - Public property returning device ID. - - .. versionadded:: 1.4.0 - ''' - return self._device - - @property - def filename(self): - ''' - Public property returning filename for current recording. - - .. versionadded:: 1.4.0 - ''' - return self._filename - - def record(self): - ''' - Start recording a WAV sound. - - .. versionadded:: 1.4.0 - ''' - send_command( - device=self.device, - msg=MCI_RECORD, - flags=0, - params=None - ) - - def stop(self): - ''' - Stop recording and save the data to a file path - self.filename. Wait until the file is written. - Close the device afterwards. - - .. versionadded:: 1.4.0 - ''' - - # stop the recording first - send_command( - device=self.device, - msg=MCI_STOP, - flags=MCI_WAIT, - params=None - ) - - # choose filename for the WAV file - save_params = MCI_SAVE_PARMS() - save_params.lpfilename = self.filename - - # save the sound data to a file and wait - # until it ends writing to the file - send_command( - device=self.device, - msg=MCI_SAVE, - flags=MCI_SAVE_FILE | MCI_WAIT, - params=save_params - ) - - # close the recording device - send_command( - device=self.device, - msg=MCI_CLOSE, - flags=0, - params=None - ) - - -class WinPlayer: - ''' - Generic wrapper for MCI_PLAY handling the device closing. - - .. versionadded:: 1.4.0 - ''' - - def __init__(self, device): - self._device = device - - @property - def device(self): - ''' - Public property returning device ID. - - .. versionadded:: 1.4.0 - ''' - return self._device - - def play(self): - ''' - Start playing a WAV sound. - - .. versionadded:: 1.4.0 - ''' - play_params = MCI_PLAY_PARMS() - play_params.dwFrom = 0 - - send_command( - device=self.device, - msg=MCI_PLAY, - flags=MCI_FROM, - params=play_params - ) - - def stop(self): - ''' - Stop playing a WAV sound and close the device. - - .. versionadded:: 1.4.0 - ''' - send_command( - device=self.device, - msg=MCI_STOP, - flags=MCI_WAIT, - params=None - ) - - # close the playing device - send_command( - device=self.device, - msg=MCI_CLOSE, - flags=0, - params=None - ) - - -class WinAudio(Audio): - ''' - Windows implementation of audio recording and audio playing. - - .. versionadded:: 1.4.0 - ''' - - def __init__(self, file_path=None): - # default path unless specified otherwise - default_path = join( - WinStoragePath().get_music_dir(), - 'audio.wav' - ) - super().__init__(file_path or default_path) - - self._recorder = None - self._player = None - self._current_file = None - self._check_thread = None - self._finished_callback = None - self._loaded_path = None - self.is_playing = False - self.sound = None - self.pa = None - self.is_playing = False - self.recorder = None - self.should_record = False - - def _start(self): - ''' - Start recording a WAV sound in the background asynchronously. - - .. versionadded:: 1.4.0 - ''' - - # clean everything before recording in case - # there is a different device open - self._stop() - - # create structure and set device parameters - open_params = MCI_OPEN_PARMS() - open_params.lpstrDeviceType = 'waveaudio' - open_params.lpstrElementName = '' - - # open a new device for recording - open_params = send_command( - device=0, # device ID before opening - msg=MCI_OPEN, - - # empty filename in lpstrElementName - # device type in lpstrDeviceType - flags=MCI_OPEN_ELEMENT | MCI_OPEN_TYPE, - params=open_params - ) - - # get recorder with device id and path for saving - self._recorder = WinRecorder( - device=open_params.wDeviceID, - filename=self._file_path - ) - self._recorder.record() - - # Setting the currently recorded file as current file - # for using it as a parameter in audio player - self._current_file = self._recorder.filename - - def _stop(self): - ''' - Stop recording or playing of a WAV sound. - - .. versionadded:: 1.4.0 - ''' - - if self._recorder: - self._recorder.stop() - self._recorder = None - - if self._player: - self._player.stop() - self._player = None - - def _play(self): - ''' - Play a WAV sound from a file. Prioritize latest recorded file before - default file path from WinAudio. - - .. versionadded:: 1.4.0 - ''' - - # create structure and set device parameters - open_params = MCI_OPEN_PARMS() - open_params.lpstrDeviceType = 'waveaudio' - open_params.lpstrElementName = self._current_file or self._file_path - - # open a new device for playing - open_params = send_command( - device=0, # device ID before opening - msg=MCI_OPEN, - - # existing filename in lpstrElementName - # device type in lpstrDeviceType - flags=MCI_OPEN_ELEMENT | MCI_OPEN_TYPE, - params=open_params - ) - - # get recorder with device id and path for saving - self._player = WinPlayer(device=open_params.wDeviceID) - self._player.play() - - def reload(self): - self._loaded_path = None - - def playing(self): - return self.is_playing - - -def instance(): - ''' - Instance for facade proxy. - ''' - return WinAudio() From 3560b4c142a0deb931e0cc5f3d85830ca86d2c6d Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 13:58:13 +0100 Subject: [PATCH 207/271] Cleanup unneeded dependencies --- sbapp/pydub/__init__.py | 1 - sbapp/pydub/audio_segment.py | 1399 ----------------- sbapp/pydub/effects.py | 341 ----- sbapp/pydub/exceptions.py | 32 - sbapp/pydub/generators.py | 142 -- sbapp/pydub/logging_utils.py | 14 - sbapp/pydub/playback.py | 71 - sbapp/pydub/pyaudioop.py | 553 ------- sbapp/pydub/scipy_effects.py | 175 --- sbapp/pydub/silence.py | 182 --- sbapp/pydub/utils.py | 434 ------ sbapp/pyogg/__init__.py | 108 -- sbapp/pyogg/audio_file.py | 59 - sbapp/pyogg/flac.py | 2061 -------------------------- sbapp/pyogg/flac_file.py | 114 -- sbapp/pyogg/flac_file_stream.py | 141 -- sbapp/pyogg/library_loader.py | 147 -- sbapp/pyogg/ogg.py | 672 --------- sbapp/pyogg/ogg_opus_writer.py | 421 ------ sbapp/pyogg/opus.py | 1377 ----------------- sbapp/pyogg/opus_buffered_encoder.py | 407 ----- sbapp/pyogg/opus_decoder.py | 273 ---- sbapp/pyogg/opus_encoder.py | 358 ----- sbapp/pyogg/opus_file.py | 106 -- sbapp/pyogg/opus_file_stream.py | 127 -- sbapp/pyogg/py.typed | 1 - sbapp/pyogg/pyogg_error.py | 2 - sbapp/pyogg/vorbis.py | 855 ----------- sbapp/pyogg/vorbis_file.py | 161 -- sbapp/pyogg/vorbis_file_stream.py | 110 -- 30 files changed, 10844 deletions(-) delete mode 100644 sbapp/pydub/__init__.py delete mode 100644 sbapp/pydub/audio_segment.py delete mode 100644 sbapp/pydub/effects.py delete mode 100644 sbapp/pydub/exceptions.py delete mode 100644 sbapp/pydub/generators.py delete mode 100644 sbapp/pydub/logging_utils.py delete mode 100644 sbapp/pydub/playback.py delete mode 100644 sbapp/pydub/pyaudioop.py delete mode 100644 sbapp/pydub/scipy_effects.py delete mode 100644 sbapp/pydub/silence.py delete mode 100644 sbapp/pydub/utils.py delete mode 100644 sbapp/pyogg/__init__.py delete mode 100644 sbapp/pyogg/audio_file.py delete mode 100644 sbapp/pyogg/flac.py delete mode 100644 sbapp/pyogg/flac_file.py delete mode 100644 sbapp/pyogg/flac_file_stream.py delete mode 100644 sbapp/pyogg/library_loader.py delete mode 100644 sbapp/pyogg/ogg.py delete mode 100644 sbapp/pyogg/ogg_opus_writer.py delete mode 100644 sbapp/pyogg/opus.py delete mode 100644 sbapp/pyogg/opus_buffered_encoder.py delete mode 100644 sbapp/pyogg/opus_decoder.py delete mode 100644 sbapp/pyogg/opus_encoder.py delete mode 100644 sbapp/pyogg/opus_file.py delete mode 100644 sbapp/pyogg/opus_file_stream.py delete mode 100644 sbapp/pyogg/py.typed delete mode 100644 sbapp/pyogg/pyogg_error.py delete mode 100644 sbapp/pyogg/vorbis.py delete mode 100644 sbapp/pyogg/vorbis_file.py delete mode 100644 sbapp/pyogg/vorbis_file_stream.py diff --git a/sbapp/pydub/__init__.py b/sbapp/pydub/__init__.py deleted file mode 100644 index 65e30b4..0000000 --- a/sbapp/pydub/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .audio_segment import AudioSegment \ No newline at end of file diff --git a/sbapp/pydub/audio_segment.py b/sbapp/pydub/audio_segment.py deleted file mode 100644 index 14ea46e..0000000 --- a/sbapp/pydub/audio_segment.py +++ /dev/null @@ -1,1399 +0,0 @@ -from __future__ import division - -import array -import os -import subprocess -from tempfile import TemporaryFile, NamedTemporaryFile -import wave -import sys -import struct -from .logging_utils import log_conversion, log_subprocess_output -from .utils import mediainfo_json, fsdecode -import base64 -from collections import namedtuple - -try: - from StringIO import StringIO -except: - from io import StringIO - -from io import BytesIO - -try: - from itertools import izip -except: - izip = zip - -from .utils import ( - _fd_or_path_or_tempfile, - db_to_float, - ratio_to_db, - get_encoder_name, - get_array_type, - audioop, -) -from .exceptions import ( - TooManyMissingFrames, - InvalidDuration, - InvalidID3TagVersion, - InvalidTag, - CouldntDecodeError, - CouldntEncodeError, - MissingAudioParameter, -) - -if sys.version_info >= (3, 0): - basestring = str - xrange = range - StringIO = BytesIO - - -class ClassPropertyDescriptor(object): - - def __init__(self, fget, fset=None): - self.fget = fget - self.fset = fset - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - return self.fget.__get__(obj, klass)() - - def __set__(self, obj, value): - if not self.fset: - raise AttributeError("can't set attribute") - type_ = type(obj) - return self.fset.__get__(obj, type_)(value) - - def setter(self, func): - if not isinstance(func, (classmethod, staticmethod)): - func = classmethod(func) - self.fset = func - return self - - -def classproperty(func): - if not isinstance(func, (classmethod, staticmethod)): - func = classmethod(func) - - return ClassPropertyDescriptor(func) - - -AUDIO_FILE_EXT_ALIASES = { - "m4a": "mp4", - "wave": "wav", -} - -WavSubChunk = namedtuple('WavSubChunk', ['id', 'position', 'size']) -WavData = namedtuple('WavData', ['audio_format', 'channels', 'sample_rate', - 'bits_per_sample', 'raw_data']) - - -def extract_wav_headers(data): - # def search_subchunk(data, subchunk_id): - pos = 12 # The size of the RIFF chunk descriptor - subchunks = [] - while pos + 8 <= len(data) and len(subchunks) < 10: - subchunk_id = data[pos:pos + 4] - subchunk_size = struct.unpack_from(' 2**32: - raise CouldntDecodeError("Unable to process >4GB files") - - # Set the file size in the RIFF chunk descriptor - data[4:8] = struct.pack(' b'\x7f'[0]]) - old_bytes = struct.pack(pack_fmt, b0, b1, b2) - byte_buffer.write(old_bytes) - - self._data = byte_buffer.getvalue() - self.sample_width = 4 - self.frame_width = self.channels * self.sample_width - - super(AudioSegment, self).__init__(*args, **kwargs) - - @property - def raw_data(self): - """ - public access to the raw audio data as a bytestring - """ - return self._data - - def get_array_of_samples(self, array_type_override=None): - """ - returns the raw_data as an array of samples - """ - if array_type_override is None: - array_type_override = self.array_type - return array.array(array_type_override, self._data) - - @property - def array_type(self): - return get_array_type(self.sample_width * 8) - - def __len__(self): - """ - returns the length of this audio segment in milliseconds - """ - return round(1000 * (self.frame_count() / self.frame_rate)) - - def __eq__(self, other): - try: - return self._data == other._data - except: - return False - - def __hash__(self): - return hash(AudioSegment) ^ hash((self.channels, self.frame_rate, self.sample_width, self._data)) - - def __ne__(self, other): - return not (self == other) - - def __iter__(self): - return (self[i] for i in xrange(len(self))) - - def __getitem__(self, millisecond): - if isinstance(millisecond, slice): - if millisecond.step: - return ( - self[i:i + millisecond.step] - for i in xrange(*millisecond.indices(len(self))) - ) - - start = millisecond.start if millisecond.start is not None else 0 - end = millisecond.stop if millisecond.stop is not None \ - else len(self) - - start = min(start, len(self)) - end = min(end, len(self)) - else: - start = millisecond - end = millisecond + 1 - - start = self._parse_position(start) * self.frame_width - end = self._parse_position(end) * self.frame_width - data = self._data[start:end] - - # ensure the output is as long as the requester is expecting - expected_length = end - start - missing_frames = (expected_length - len(data)) // self.frame_width - if missing_frames: - if missing_frames > self.frame_count(ms=2): - raise TooManyMissingFrames( - "You should never be filling in " - " more than 2 ms with silence here, " - "missing frames: %s" % missing_frames) - silence = audioop.mul(data[:self.frame_width], - self.sample_width, 0) - data += (silence * missing_frames) - - return self._spawn(data) - - def get_sample_slice(self, start_sample=None, end_sample=None): - """ - Get a section of the audio segment by sample index. - - NOTE: Negative indices do *not* address samples backword - from the end of the audio segment like a python list. - This is intentional. - """ - max_val = int(self.frame_count()) - - def bounded(val, default): - if val is None: - return default - if val < 0: - return 0 - if val > max_val: - return max_val - return val - - start_i = bounded(start_sample, 0) * self.frame_width - end_i = bounded(end_sample, max_val) * self.frame_width - - data = self._data[start_i:end_i] - return self._spawn(data) - - def __add__(self, arg): - if isinstance(arg, AudioSegment): - return self.append(arg, crossfade=0) - else: - return self.apply_gain(arg) - - def __radd__(self, rarg): - """ - Permit use of sum() builtin with an iterable of AudioSegments - """ - if rarg == 0: - return self - raise TypeError("Gains must be the second addend after the " - "AudioSegment") - - def __sub__(self, arg): - if isinstance(arg, AudioSegment): - raise TypeError("AudioSegment objects can't be subtracted from " - "each other") - else: - return self.apply_gain(-arg) - - def __mul__(self, arg): - """ - If the argument is an AudioSegment, overlay the multiplied audio - segment. - - If it's a number, just use the string multiply operation to repeat the - audio. - - The following would return an AudioSegment that contains the - audio of audio_seg eight times - - `audio_seg * 8` - """ - if isinstance(arg, AudioSegment): - return self.overlay(arg, position=0, loop=True) - else: - return self._spawn(data=self._data * arg) - - def _spawn(self, data, overrides={}): - """ - Creates a new audio segment using the metadata from the current one - and the data passed in. Should be used whenever an AudioSegment is - being returned by an operation that would alters the current one, - since AudioSegment objects are immutable. - """ - # accept lists of data chunks - if isinstance(data, list): - data = b''.join(data) - - if isinstance(data, array.array): - try: - data = data.tobytes() - except: - data = data.tostring() - - # accept file-like objects - if hasattr(data, 'read'): - if hasattr(data, 'seek'): - data.seek(0) - data = data.read() - - metadata = { - 'sample_width': self.sample_width, - 'frame_rate': self.frame_rate, - 'frame_width': self.frame_width, - 'channels': self.channels - } - metadata.update(overrides) - return self.__class__(data=data, metadata=metadata) - - @classmethod - def _sync(cls, *segs): - channels = max(seg.channels for seg in segs) - frame_rate = max(seg.frame_rate for seg in segs) - sample_width = max(seg.sample_width for seg in segs) - - return tuple( - seg.set_channels(channels).set_frame_rate(frame_rate).set_sample_width(sample_width) - for seg in segs - ) - - def _parse_position(self, val): - if val < 0: - val = len(self) - abs(val) - val = self.frame_count(ms=len(self)) if val == float("inf") else \ - self.frame_count(ms=val) - return int(val) - - @classmethod - def empty(cls): - return cls(b'', metadata={ - "channels": 1, - "sample_width": 1, - "frame_rate": 1, - "frame_width": 1 - }) - - @classmethod - def silent(cls, duration=1000, frame_rate=11025): - """ - Generate a silent audio segment. - duration specified in milliseconds (default duration: 1000ms, default frame_rate: 11025). - """ - frames = int(frame_rate * (duration / 1000.0)) - data = b"\0\0" * frames - return cls(data, metadata={"channels": 1, - "sample_width": 2, - "frame_rate": frame_rate, - "frame_width": 2}) - - @classmethod - def from_mono_audiosegments(cls, *mono_segments): - if not len(mono_segments): - raise ValueError("At least one AudioSegment instance is required") - - segs = cls._sync(*mono_segments) - - if segs[0].channels != 1: - raise ValueError( - "AudioSegment.from_mono_audiosegments requires all arguments are mono AudioSegment instances") - - channels = len(segs) - sample_width = segs[0].sample_width - frame_rate = segs[0].frame_rate - - frame_count = max(int(seg.frame_count()) for seg in segs) - data = array.array( - segs[0].array_type, - b'\0' * (frame_count * sample_width * channels) - ) - - for i, seg in enumerate(segs): - data[i::channels] = seg.get_array_of_samples() - - return cls( - data, - channels=channels, - sample_width=sample_width, - frame_rate=frame_rate, - ) - - @classmethod - def from_file_using_temporary_files(cls, file, format=None, codec=None, parameters=None, start_second=None, duration=None, **kwargs): - orig_file = file - file, close_file = _fd_or_path_or_tempfile(file, 'rb', tempfile=False) - - if format: - format = format.lower() - format = AUDIO_FILE_EXT_ALIASES.get(format, format) - - def is_format(f): - f = f.lower() - if format == f: - return True - if isinstance(orig_file, basestring): - return orig_file.lower().endswith(".{0}".format(f)) - if isinstance(orig_file, bytes): - return orig_file.lower().endswith((".{0}".format(f)).encode('utf8')) - return False - - if is_format("wav"): - try: - obj = cls._from_safe_wav(file) - if close_file: - file.close() - if start_second is None and duration is None: - return obj - elif start_second is not None and duration is None: - return obj[start_second*1000:] - elif start_second is None and duration is not None: - return obj[:duration*1000] - else: - return obj[start_second*1000:(start_second+duration)*1000] - except: - file.seek(0) - elif is_format("raw") or is_format("pcm"): - sample_width = kwargs['sample_width'] - frame_rate = kwargs['frame_rate'] - channels = kwargs['channels'] - metadata = { - 'sample_width': sample_width, - 'frame_rate': frame_rate, - 'channels': channels, - 'frame_width': channels * sample_width - } - obj = cls(data=file.read(), metadata=metadata) - if close_file: - file.close() - if start_second is None and duration is None: - return obj - elif start_second is not None and duration is None: - return obj[start_second * 1000:] - elif start_second is None and duration is not None: - return obj[:duration * 1000] - else: - return obj[start_second * 1000:(start_second + duration) * 1000] - - input_file = NamedTemporaryFile(mode='wb', delete=False) - try: - input_file.write(file.read()) - except(OSError): - input_file.flush() - input_file.close() - input_file = NamedTemporaryFile(mode='wb', delete=False, buffering=2 ** 31 - 1) - if close_file: - file.close() - close_file = True - file = open(orig_file, buffering=2 ** 13 - 1, mode='rb') - reader = file.read(2 ** 31 - 1) - while reader: - input_file.write(reader) - reader = file.read(2 ** 31 - 1) - input_file.flush() - if close_file: - file.close() - - output = NamedTemporaryFile(mode="rb", delete=False) - - conversion_command = [cls.converter, - '-y', # always overwrite existing files - ] - - # If format is not defined - # ffmpeg/avconv will detect it automatically - if format: - conversion_command += ["-f", format] - - if codec: - # force audio decoder - conversion_command += ["-acodec", codec] - - conversion_command += [ - "-i", input_file.name, # input_file options (filename last) - "-vn", # Drop any video streams if there are any - "-f", "wav" # output options (filename last) - ] - - if start_second is not None: - conversion_command += ["-ss", str(start_second)] - - if duration is not None: - conversion_command += ["-t", str(duration)] - - conversion_command += [output.name] - - if parameters is not None: - # extend arguments with arbitrary set - conversion_command.extend(parameters) - - log_conversion(conversion_command) - - with open(os.devnull, 'rb') as devnull: - p = subprocess.Popen(conversion_command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p_out, p_err = p.communicate() - - log_subprocess_output(p_out) - log_subprocess_output(p_err) - - try: - if p.returncode != 0: - raise CouldntDecodeError( - "Decoding failed. ffmpeg returned error code: {0}\n\nOutput from ffmpeg/avlib:\n\n{1}".format( - p.returncode, p_err.decode(errors='ignore') )) - obj = cls._from_safe_wav(output) - finally: - input_file.close() - output.close() - os.unlink(input_file.name) - os.unlink(output.name) - - if start_second is None and duration is None: - return obj - elif start_second is not None and duration is None: - return obj[0:] - elif start_second is None and duration is not None: - return obj[:duration * 1000] - else: - return obj[0:duration * 1000] - - - @classmethod - def from_file(cls, file, format=None, codec=None, parameters=None, start_second=None, duration=None, **kwargs): - orig_file = file - try: - filename = fsdecode(file) - except TypeError: - filename = None - file, close_file = _fd_or_path_or_tempfile(file, 'rb', tempfile=False) - - if format: - format = format.lower() - format = AUDIO_FILE_EXT_ALIASES.get(format, format) - - def is_format(f): - f = f.lower() - if format == f: - return True - - if filename: - return filename.lower().endswith(".{0}".format(f)) - - return False - - if is_format("wav"): - try: - if start_second is None and duration is None: - return cls._from_safe_wav(file) - elif start_second is not None and duration is None: - return cls._from_safe_wav(file)[start_second*1000:] - elif start_second is None and duration is not None: - return cls._from_safe_wav(file)[:duration*1000] - else: - return cls._from_safe_wav(file)[start_second*1000:(start_second+duration)*1000] - except: - file.seek(0) - elif is_format("raw") or is_format("pcm"): - sample_width = kwargs['sample_width'] - frame_rate = kwargs['frame_rate'] - channels = kwargs['channels'] - metadata = { - 'sample_width': sample_width, - 'frame_rate': frame_rate, - 'channels': channels, - 'frame_width': channels * sample_width - } - if start_second is None and duration is None: - return cls(data=file.read(), metadata=metadata) - elif start_second is not None and duration is None: - return cls(data=file.read(), metadata=metadata)[start_second*1000:] - elif start_second is None and duration is not None: - return cls(data=file.read(), metadata=metadata)[:duration*1000] - else: - return cls(data=file.read(), metadata=metadata)[start_second*1000:(start_second+duration)*1000] - - conversion_command = [cls.converter, - '-y', # always overwrite existing files - ] - - # If format is not defined - # ffmpeg/avconv will detect it automatically - if format: - conversion_command += ["-f", format] - - if codec: - # force audio decoder - conversion_command += ["-acodec", codec] - - read_ahead_limit = kwargs.get('read_ahead_limit', -1) - if filename: - conversion_command += ["-i", filename] - stdin_parameter = None - stdin_data = None - else: - if cls.converter == 'ffmpeg': - conversion_command += ["-read_ahead_limit", str(read_ahead_limit), - "-i", "cache:pipe:0"] - else: - conversion_command += ["-i", "-"] - stdin_parameter = subprocess.PIPE - stdin_data = file.read() - - if codec: - info = None - else: - info = mediainfo_json(orig_file, read_ahead_limit=read_ahead_limit) - if info: - audio_streams = [x for x in info['streams'] - if x['codec_type'] == 'audio'] - # This is a workaround for some ffprobe versions that always say - # that mp3/mp4/aac/webm/ogg files contain fltp samples - audio_codec = audio_streams[0].get('codec_name') - if (audio_streams[0].get('sample_fmt') == 'fltp' and - audio_codec in ['mp3', 'mp4', 'aac', 'webm', 'ogg']): - bits_per_sample = 16 - else: - bits_per_sample = audio_streams[0]['bits_per_sample'] - if bits_per_sample == 8: - acodec = 'pcm_u8' - else: - acodec = 'pcm_s%dle' % bits_per_sample - - conversion_command += ["-acodec", acodec] - - conversion_command += [ - "-vn", # Drop any video streams if there are any - "-f", "wav" # output options (filename last) - ] - - if start_second is not None: - conversion_command += ["-ss", str(start_second)] - - if duration is not None: - conversion_command += ["-t", str(duration)] - - conversion_command += ["-"] - - if parameters is not None: - # extend arguments with arbitrary set - conversion_command.extend(parameters) - - log_conversion(conversion_command) - - p = subprocess.Popen(conversion_command, stdin=stdin_parameter, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p_out, p_err = p.communicate(input=stdin_data) - - if p.returncode != 0 or len(p_out) == 0: - if close_file: - file.close() - raise CouldntDecodeError( - "Decoding failed. ffmpeg returned error code: {0}\n\nOutput from ffmpeg/avlib:\n\n{1}".format( - p.returncode, p_err.decode(errors='ignore') )) - - p_out = bytearray(p_out) - fix_wav_headers(p_out) - p_out = bytes(p_out) - obj = cls(p_out) - - if close_file: - file.close() - - if start_second is None and duration is None: - return obj - elif start_second is not None and duration is None: - return obj[0:] - elif start_second is None and duration is not None: - return obj[:duration * 1000] - else: - return obj[0:duration * 1000] - - @classmethod - def from_mp3(cls, file, parameters=None): - return cls.from_file(file, 'mp3', parameters=parameters) - - @classmethod - def from_flv(cls, file, parameters=None): - return cls.from_file(file, 'flv', parameters=parameters) - - @classmethod - def from_ogg(cls, file, parameters=None): - return cls.from_file(file, 'ogg', parameters=parameters) - - @classmethod - def from_wav(cls, file, parameters=None): - return cls.from_file(file, 'wav', parameters=parameters) - - @classmethod - def from_raw(cls, file, **kwargs): - return cls.from_file(file, 'raw', sample_width=kwargs['sample_width'], frame_rate=kwargs['frame_rate'], - channels=kwargs['channels']) - - @classmethod - def _from_safe_wav(cls, file): - file, close_file = _fd_or_path_or_tempfile(file, 'rb', tempfile=False) - file.seek(0) - obj = cls(data=file) - if close_file: - file.close() - return obj - - def export(self, out_f=None, format='mp3', codec=None, bitrate=None, parameters=None, tags=None, id3v2_version='4', - cover=None): - """ - Export an AudioSegment to a file with given options - - out_f (string): - Path to destination audio file. Also accepts os.PathLike objects on - python >= 3.6 - - format (string) - Format for destination audio file. - ('mp3', 'wav', 'raw', 'ogg' or other ffmpeg/avconv supported files) - - codec (string) - Codec used to encode the destination file. - - bitrate (string) - Bitrate used when encoding destination file. (64, 92, 128, 256, 312k...) - Each codec accepts different bitrate arguments so take a look at the - ffmpeg documentation for details (bitrate usually shown as -b, -ba or - -a:b). - - parameters (list of strings) - Aditional ffmpeg/avconv parameters - - tags (dict) - Set metadata information to destination files - usually used as tags. ({title='Song Title', artist='Song Artist'}) - - id3v2_version (string) - Set ID3v2 version for tags. (default: '4') - - cover (file) - Set cover for audio file from image file. (png or jpg) - """ - id3v2_allowed_versions = ['3', '4'] - - if format == "raw" and (codec is not None or parameters is not None): - raise AttributeError( - 'Can not invoke ffmpeg when export format is "raw"; ' - 'specify an ffmpeg raw format like format="s16le" instead ' - 'or call export(format="raw") with no codec or parameters') - - out_f, _ = _fd_or_path_or_tempfile(out_f, 'wb+') - out_f.seek(0) - - if format == "raw": - out_f.write(self._data) - out_f.seek(0) - return out_f - - # wav with no ffmpeg parameters can just be written directly to out_f - easy_wav = format == "wav" and codec is None and parameters is None - - if easy_wav: - data = out_f - else: - data = NamedTemporaryFile(mode="wb", delete=False) - - pcm_for_wav = self._data - if self.sample_width == 1: - # convert to unsigned integers for wav - pcm_for_wav = audioop.bias(self._data, 1, 128) - - wave_data = wave.open(data, 'wb') - wave_data.setnchannels(self.channels) - wave_data.setsampwidth(self.sample_width) - wave_data.setframerate(self.frame_rate) - # For some reason packing the wave header struct with - # a float in python 2 doesn't throw an exception - wave_data.setnframes(int(self.frame_count())) - wave_data.writeframesraw(pcm_for_wav) - wave_data.close() - - # for easy wav files, we're done (wav data is written directly to out_f) - if easy_wav: - out_f.seek(0) - return out_f - - output = NamedTemporaryFile(mode="w+b", delete=False) - - # build converter command to export - conversion_command = [ - self.converter, - '-y', # always overwrite existing files - "-f", "wav", "-i", data.name, # input options (filename last) - ] - - if codec is None: - codec = self.DEFAULT_CODECS.get(format, None) - - if cover is not None: - if cover.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff')) and format == "mp3": - conversion_command.extend(["-i", cover, "-map", "0", "-map", "1", "-c:v", "mjpeg"]) - else: - raise AttributeError( - "Currently cover images are only supported by MP3 files. The allowed image formats are: .tif, .jpg, .bmp, .jpeg and .png.") - - if codec is not None: - # force audio encoder - conversion_command.extend(["-acodec", codec]) - - if bitrate is not None: - conversion_command.extend(["-b:a", bitrate]) - - if parameters is not None: - # extend arguments with arbitrary set - conversion_command.extend(parameters) - - if tags is not None: - if not isinstance(tags, dict): - raise InvalidTag("Tags must be a dictionary.") - else: - # Extend converter command with tags - # print(tags) - for key, value in tags.items(): - conversion_command.extend( - ['-metadata', '{0}={1}'.format(key, value)]) - - if format == 'mp3': - # set id3v2 tag version - if id3v2_version not in id3v2_allowed_versions: - raise InvalidID3TagVersion( - "id3v2_version not allowed, allowed versions: %s" % id3v2_allowed_versions) - conversion_command.extend([ - "-id3v2_version", id3v2_version - ]) - - if sys.platform == 'darwin' and codec == 'mp3': - conversion_command.extend(["-write_xing", "0"]) - - conversion_command.extend([ - "-f", format, output.name, # output options (filename last) - ]) - - log_conversion(conversion_command) - - # read stdin / write stdout - with open(os.devnull, 'rb') as devnull: - p = subprocess.Popen(conversion_command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p_out, p_err = p.communicate() - - log_subprocess_output(p_out) - log_subprocess_output(p_err) - - if p.returncode != 0: - raise CouldntEncodeError( - "Encoding failed. ffmpeg/avlib returned error code: {0}\n\nCommand:{1}\n\nOutput from ffmpeg/avlib:\n\n{2}".format( - p.returncode, conversion_command, p_err.decode(errors='ignore') )) - - output.seek(0) - out_f.write(output.read()) - - data.close() - output.close() - - os.unlink(data.name) - os.unlink(output.name) - - out_f.seek(0) - return out_f - - def get_frame(self, index): - frame_start = index * self.frame_width - frame_end = frame_start + self.frame_width - return self._data[frame_start:frame_end] - - def frame_count(self, ms=None): - """ - returns the number of frames for the given number of milliseconds, or - if not specified, the number of frames in the whole AudioSegment - """ - if ms is not None: - return ms * (self.frame_rate / 1000.0) - else: - return float(len(self._data) // self.frame_width) - - def set_sample_width(self, sample_width): - if sample_width == self.sample_width: - return self - - frame_width = self.channels * sample_width - - return self._spawn( - audioop.lin2lin(self._data, self.sample_width, sample_width), - overrides={'sample_width': sample_width, 'frame_width': frame_width} - ) - - def set_frame_rate(self, frame_rate): - if frame_rate == self.frame_rate: - return self - - if self._data: - converted, _ = audioop.ratecv(self._data, self.sample_width, - self.channels, self.frame_rate, - frame_rate, None) - else: - converted = self._data - - return self._spawn(data=converted, - overrides={'frame_rate': frame_rate}) - - def set_channels(self, channels): - if channels == self.channels: - return self - - if channels == 2 and self.channels == 1: - fn = audioop.tostereo - frame_width = self.frame_width * 2 - fac = 1 - converted = fn(self._data, self.sample_width, fac, fac) - elif channels == 1 and self.channels == 2: - fn = audioop.tomono - frame_width = self.frame_width // 2 - fac = 0.5 - converted = fn(self._data, self.sample_width, fac, fac) - elif channels == 1: - channels_data = [seg.get_array_of_samples() for seg in self.split_to_mono()] - frame_count = int(self.frame_count()) - converted = array.array( - channels_data[0].typecode, - b'\0' * (frame_count * self.sample_width) - ) - for raw_channel_data in channels_data: - for i in range(frame_count): - converted[i] += raw_channel_data[i] // self.channels - frame_width = self.frame_width // self.channels - elif self.channels == 1: - dup_channels = [self for iChannel in range(channels)] - return AudioSegment.from_mono_audiosegments(*dup_channels) - else: - raise ValueError( - "AudioSegment.set_channels only supports mono-to-multi channel and multi-to-mono channel conversion") - - return self._spawn(data=converted, - overrides={ - 'channels': channels, - 'frame_width': frame_width}) - - def split_to_mono(self): - if self.channels == 1: - return [self] - - samples = self.get_array_of_samples() - - mono_channels = [] - for i in range(self.channels): - samples_for_current_channel = samples[i::self.channels] - - try: - mono_data = samples_for_current_channel.tobytes() - except AttributeError: - mono_data = samples_for_current_channel.tostring() - - mono_channels.append( - self._spawn(mono_data, overrides={"channels": 1, "frame_width": self.sample_width}) - ) - - return mono_channels - - @property - def rms(self): - return audioop.rms(self._data, self.sample_width) - - @property - def dBFS(self): - rms = self.rms - if not rms: - return -float("infinity") - return ratio_to_db(self.rms / self.max_possible_amplitude) - - @property - def max(self): - return audioop.max(self._data, self.sample_width) - - @property - def max_possible_amplitude(self): - bits = self.sample_width * 8 - max_possible_val = (2 ** bits) - - # since half is above 0 and half is below the max amplitude is divided - return max_possible_val / 2 - - @property - def max_dBFS(self): - return ratio_to_db(self.max, self.max_possible_amplitude) - - @property - def duration_seconds(self): - return self.frame_rate and self.frame_count() / self.frame_rate or 0.0 - - def get_dc_offset(self, channel=1): - """ - Returns a value between -1.0 and 1.0 representing the DC offset of a - channel (1 for left, 2 for right). - """ - if not 1 <= channel <= 2: - raise ValueError("channel value must be 1 (left) or 2 (right)") - - if self.channels == 1: - data = self._data - elif channel == 1: - data = audioop.tomono(self._data, self.sample_width, 1, 0) - else: - data = audioop.tomono(self._data, self.sample_width, 0, 1) - - return float(audioop.avg(data, self.sample_width)) / self.max_possible_amplitude - - def remove_dc_offset(self, channel=None, offset=None): - """ - Removes DC offset of given channel. Calculates offset if it's not given. - Offset values must be in range -1.0 to 1.0. If channel is None, removes - DC offset from all available channels. - """ - if channel and not 1 <= channel <= 2: - raise ValueError("channel value must be None, 1 (left) or 2 (right)") - - if offset and not -1.0 <= offset <= 1.0: - raise ValueError("offset value must be in range -1.0 to 1.0") - - if offset: - offset = int(round(offset * self.max_possible_amplitude)) - - def remove_data_dc(data, off): - if not off: - off = audioop.avg(data, self.sample_width) - return audioop.bias(data, self.sample_width, -off) - - if self.channels == 1: - return self._spawn(data=remove_data_dc(self._data, offset)) - - left_channel = audioop.tomono(self._data, self.sample_width, 1, 0) - right_channel = audioop.tomono(self._data, self.sample_width, 0, 1) - - if not channel or channel == 1: - left_channel = remove_data_dc(left_channel, offset) - - if not channel or channel == 2: - right_channel = remove_data_dc(right_channel, offset) - - left_channel = audioop.tostereo(left_channel, self.sample_width, 1, 0) - right_channel = audioop.tostereo(right_channel, self.sample_width, 0, 1) - - return self._spawn(data=audioop.add(left_channel, right_channel, - self.sample_width)) - - def apply_gain(self, volume_change): - return self._spawn(data=audioop.mul(self._data, self.sample_width, - db_to_float(float(volume_change)))) - - def overlay(self, seg, position=0, loop=False, times=None, gain_during_overlay=None): - """ - Overlay the provided segment on to this segment starting at the - specificed position and using the specfied looping beahvior. - - seg (AudioSegment): - The audio segment to overlay on to this one. - - position (optional int): - The position to start overlaying the provided segment in to this - one. - - loop (optional bool): - Loop seg as many times as necessary to match this segment's length. - Overrides loops param. - - times (optional int): - Loop seg the specified number of times or until it matches this - segment's length. 1 means once, 2 means twice, ... 0 would make the - call a no-op - gain_during_overlay (optional int): - Changes this segment's volume by the specified amount during the - duration of time that seg is overlaid on top of it. When negative, - this has the effect of 'ducking' the audio under the overlay. - """ - - if loop: - # match loop=True's behavior with new times (count) mechinism. - times = -1 - elif times is None: - # no times specified, just once through - times = 1 - elif times == 0: - # it's a no-op, make a copy since we never mutate - return self._spawn(self._data) - - output = StringIO() - - seg1, seg2 = AudioSegment._sync(self, seg) - sample_width = seg1.sample_width - spawn = seg1._spawn - - output.write(seg1[:position]._data) - - # drop down to the raw data - seg1 = seg1[position:]._data - seg2 = seg2._data - pos = 0 - seg1_len = len(seg1) - seg2_len = len(seg2) - while times: - remaining = max(0, seg1_len - pos) - if seg2_len >= remaining: - seg2 = seg2[:remaining] - seg2_len = remaining - # we've hit the end, we're done looping (if we were) and this - # is our last go-around - times = 1 - - if gain_during_overlay: - seg1_overlaid = seg1[pos:pos + seg2_len] - seg1_adjusted_gain = audioop.mul(seg1_overlaid, self.sample_width, - db_to_float(float(gain_during_overlay))) - output.write(audioop.add(seg1_adjusted_gain, seg2, sample_width)) - else: - output.write(audioop.add(seg1[pos:pos + seg2_len], seg2, - sample_width)) - pos += seg2_len - - # dec times to break our while loop (eventually) - times -= 1 - - output.write(seg1[pos:]) - - return spawn(data=output) - - def append(self, seg, crossfade=100): - seg1, seg2 = AudioSegment._sync(self, seg) - - if not crossfade: - return seg1._spawn(seg1._data + seg2._data) - elif crossfade > len(self): - raise ValueError("Crossfade is longer than the original AudioSegment ({}ms > {}ms)".format( - crossfade, len(self) - )) - elif crossfade > len(seg): - raise ValueError("Crossfade is longer than the appended AudioSegment ({}ms > {}ms)".format( - crossfade, len(seg) - )) - - xf = seg1[-crossfade:].fade(to_gain=-120, start=0, end=float('inf')) - xf *= seg2[:crossfade].fade(from_gain=-120, start=0, end=float('inf')) - - output = TemporaryFile() - - output.write(seg1[:-crossfade]._data) - output.write(xf._data) - output.write(seg2[crossfade:]._data) - - output.seek(0) - obj = seg1._spawn(data=output) - output.close() - return obj - - def fade(self, to_gain=0, from_gain=0, start=None, end=None, - duration=None): - """ - Fade the volume of this audio segment. - - to_gain (float): - resulting volume_change in db - - start (int): - default = beginning of the segment - when in this segment to start fading in milliseconds - - end (int): - default = end of the segment - when in this segment to start fading in milliseconds - - duration (int): - default = until the end of the audio segment - the duration of the fade - """ - if None not in [duration, end, start]: - raise TypeError('Only two of the three arguments, "start", ' - '"end", and "duration" may be specified') - - # no fade == the same audio - if to_gain == 0 and from_gain == 0: - return self - - start = min(len(self), start) if start is not None else None - end = min(len(self), end) if end is not None else None - - if start is not None and start < 0: - start += len(self) - if end is not None and end < 0: - end += len(self) - - if duration is not None and duration < 0: - raise InvalidDuration("duration must be a positive integer") - - if duration: - if start is not None: - end = start + duration - elif end is not None: - start = end - duration - else: - duration = end - start - - from_power = db_to_float(from_gain) - - output = [] - - # original data - up until the crossfade portion, as is - before_fade = self[:start]._data - if from_gain != 0: - before_fade = audioop.mul(before_fade, - self.sample_width, - from_power) - output.append(before_fade) - - gain_delta = db_to_float(to_gain) - from_power - - # fades longer than 100ms can use coarse fading (one gain step per ms), - # shorter fades will have audible clicks so they use precise fading - # (one gain step per sample) - if duration > 100: - scale_step = gain_delta / duration - - for i in range(duration): - volume_change = from_power + (scale_step * i) - chunk = self[start + i] - chunk = audioop.mul(chunk._data, - self.sample_width, - volume_change) - - output.append(chunk) - else: - start_frame = self.frame_count(ms=start) - end_frame = self.frame_count(ms=end) - fade_frames = end_frame - start_frame - scale_step = gain_delta / fade_frames - - for i in range(int(fade_frames)): - volume_change = from_power + (scale_step * i) - sample = self.get_frame(int(start_frame + i)) - sample = audioop.mul(sample, self.sample_width, volume_change) - - output.append(sample) - - # original data after the crossfade portion, at the new volume - after_fade = self[end:]._data - if to_gain != 0: - after_fade = audioop.mul(after_fade, - self.sample_width, - db_to_float(to_gain)) - output.append(after_fade) - - return self._spawn(data=output) - - def fade_out(self, duration): - return self.fade(to_gain=-120, duration=duration, end=float('inf')) - - def fade_in(self, duration): - return self.fade(from_gain=-120, duration=duration, start=0) - - def reverse(self): - return self._spawn( - data=audioop.reverse(self._data, self.sample_width) - ) - - def _repr_html_(self): - src = """ - - """ - fh = self.export() - data = base64.b64encode(fh.read()).decode('ascii') - return src.format(base64=data) - - -from . import effects diff --git a/sbapp/pydub/effects.py b/sbapp/pydub/effects.py deleted file mode 100644 index 0210521..0000000 --- a/sbapp/pydub/effects.py +++ /dev/null @@ -1,341 +0,0 @@ -import sys -import math -import array -from .utils import ( - db_to_float, - ratio_to_db, - register_pydub_effect, - make_chunks, - audioop, - get_min_max_value -) -from .silence import split_on_silence -from .exceptions import TooManyMissingFrames, InvalidDuration - -if sys.version_info >= (3, 0): - xrange = range - - -@register_pydub_effect -def apply_mono_filter_to_each_channel(seg, filter_fn): - n_channels = seg.channels - - channel_segs = seg.split_to_mono() - channel_segs = [filter_fn(channel_seg) for channel_seg in channel_segs] - - out_data = seg.get_array_of_samples() - for channel_i, channel_seg in enumerate(channel_segs): - for sample_i, sample in enumerate(channel_seg.get_array_of_samples()): - index = (sample_i * n_channels) + channel_i - out_data[index] = sample - - return seg._spawn(out_data) - - -@register_pydub_effect -def normalize(seg, headroom=0.1): - """ - headroom is how close to the maximum volume to boost the signal up to (specified in dB) - """ - peak_sample_val = seg.max - - # if the max is 0, this audio segment is silent, and can't be normalized - if peak_sample_val == 0: - return seg - - target_peak = seg.max_possible_amplitude * db_to_float(-headroom) - - needed_boost = ratio_to_db(target_peak / peak_sample_val) - return seg.apply_gain(needed_boost) - - -@register_pydub_effect -def speedup(seg, playback_speed=1.5, chunk_size=150, crossfade=25): - # we will keep audio in 150ms chunks since one waveform at 20Hz is 50ms long - # (20 Hz is the lowest frequency audible to humans) - - # portion of AUDIO TO KEEP. if playback speed is 1.25 we keep 80% (0.8) and - # discard 20% (0.2) - atk = 1.0 / playback_speed - - if playback_speed < 2.0: - # throwing out more than half the audio - keep 50ms chunks - ms_to_remove_per_chunk = int(chunk_size * (1 - atk) / atk) - else: - # throwing out less than half the audio - throw out 50ms chunks - ms_to_remove_per_chunk = int(chunk_size) - chunk_size = int(atk * chunk_size / (1 - atk)) - - # the crossfade cannot be longer than the amount of audio we're removing - crossfade = min(crossfade, ms_to_remove_per_chunk - 1) - - # DEBUG - #print("chunk: {0}, rm: {1}".format(chunk_size, ms_to_remove_per_chunk)) - - chunks = make_chunks(seg, chunk_size + ms_to_remove_per_chunk) - if len(chunks) < 2: - raise Exception("Could not speed up AudioSegment, it was too short {2:0.2f}s for the current settings:\n{0}ms chunks at {1:0.1f}x speedup".format( - chunk_size, playback_speed, seg.duration_seconds)) - - # we'll actually truncate a bit less than we calculated to make up for the - # crossfade between chunks - ms_to_remove_per_chunk -= crossfade - - # we don't want to truncate the last chunk since it is not guaranteed to be - # the full chunk length - last_chunk = chunks[-1] - chunks = [chunk[:-ms_to_remove_per_chunk] for chunk in chunks[:-1]] - - out = chunks[0] - for chunk in chunks[1:]: - out = out.append(chunk, crossfade=crossfade) - - out += last_chunk - return out - - -@register_pydub_effect -def strip_silence(seg, silence_len=1000, silence_thresh=-16, padding=100): - if padding > silence_len: - raise InvalidDuration("padding cannot be longer than silence_len") - - chunks = split_on_silence(seg, silence_len, silence_thresh, padding) - crossfade = padding / 2 - - if not len(chunks): - return seg[0:0] - - seg = chunks[0] - for chunk in chunks[1:]: - seg = seg.append(chunk, crossfade=crossfade) - - return seg - - -@register_pydub_effect -def compress_dynamic_range(seg, threshold=-20.0, ratio=4.0, attack=5.0, release=50.0): - """ - Keyword Arguments: - - threshold - default: -20.0 - Threshold in dBFS. default of -20.0 means -20dB relative to the - maximum possible volume. 0dBFS is the maximum possible value so - all values for this argument sould be negative. - - ratio - default: 4.0 - Compression ratio. Audio louder than the threshold will be - reduced to 1/ratio the volume. A ratio of 4.0 is equivalent to - a setting of 4:1 in a pro-audio compressor like the Waves C1. - - attack - default: 5.0 - Attack in milliseconds. How long it should take for the compressor - to kick in once the audio has exceeded the threshold. - - release - default: 50.0 - Release in milliseconds. How long it should take for the compressor - to stop compressing after the audio has falled below the threshold. - - - For an overview of Dynamic Range Compression, and more detailed explanation - of the related terminology, see: - - http://en.wikipedia.org/wiki/Dynamic_range_compression - """ - - thresh_rms = seg.max_possible_amplitude * db_to_float(threshold) - - look_frames = int(seg.frame_count(ms=attack)) - def rms_at(frame_i): - return seg.get_sample_slice(frame_i - look_frames, frame_i).rms - def db_over_threshold(rms): - if rms == 0: return 0.0 - db = ratio_to_db(rms / thresh_rms) - return max(db, 0) - - output = [] - - # amount to reduce the volume of the audio by (in dB) - attenuation = 0.0 - - attack_frames = seg.frame_count(ms=attack) - release_frames = seg.frame_count(ms=release) - for i in xrange(int(seg.frame_count())): - rms_now = rms_at(i) - - # with a ratio of 4.0 this means the volume will exceed the threshold by - # 1/4 the amount (of dB) that it would otherwise - max_attenuation = (1 - (1.0 / ratio)) * db_over_threshold(rms_now) - - attenuation_inc = max_attenuation / attack_frames - attenuation_dec = max_attenuation / release_frames - - if rms_now > thresh_rms and attenuation <= max_attenuation: - attenuation += attenuation_inc - attenuation = min(attenuation, max_attenuation) - else: - attenuation -= attenuation_dec - attenuation = max(attenuation, 0) - - frame = seg.get_frame(i) - if attenuation != 0.0: - frame = audioop.mul(frame, - seg.sample_width, - db_to_float(-attenuation)) - - output.append(frame) - - return seg._spawn(data=b''.join(output)) - - -# Invert the phase of the signal. - -@register_pydub_effect - -def invert_phase(seg, channels=(1, 1)): - """ - channels- specifies which channel (left or right) to reverse the phase of. - Note that mono AudioSegments will become stereo. - """ - if channels == (1, 1): - inverted = audioop.mul(seg._data, seg.sample_width, -1.0) - return seg._spawn(data=inverted) - - else: - if seg.channels == 2: - left, right = seg.split_to_mono() - else: - raise Exception("Can't implicitly convert an AudioSegment with " + str(seg.channels) + " channels to stereo.") - - if channels == (1, 0): - left = left.invert_phase() - else: - right = right.invert_phase() - - return seg.from_mono_audiosegments(left, right) - - - -# High and low pass filters based on implementation found on Stack Overflow: -# http://stackoverflow.com/questions/13882038/implementing-simple-high-and-low-pass-filters-in-c - -@register_pydub_effect -def low_pass_filter(seg, cutoff): - """ - cutoff - Frequency (in Hz) where higher frequency signal will begin to - be reduced by 6dB per octave (doubling in frequency) above this point - """ - RC = 1.0 / (cutoff * 2 * math.pi) - dt = 1.0 / seg.frame_rate - - alpha = dt / (RC + dt) - - original = seg.get_array_of_samples() - filteredArray = array.array(seg.array_type, original) - - frame_count = int(seg.frame_count()) - - last_val = [0] * seg.channels - for i in range(seg.channels): - last_val[i] = filteredArray[i] = original[i] - - for i in range(1, frame_count): - for j in range(seg.channels): - offset = (i * seg.channels) + j - last_val[j] = last_val[j] + (alpha * (original[offset] - last_val[j])) - filteredArray[offset] = int(last_val[j]) - - return seg._spawn(data=filteredArray) - - -@register_pydub_effect -def high_pass_filter(seg, cutoff): - """ - cutoff - Frequency (in Hz) where lower frequency signal will begin to - be reduced by 6dB per octave (doubling in frequency) below this point - """ - RC = 1.0 / (cutoff * 2 * math.pi) - dt = 1.0 / seg.frame_rate - - alpha = RC / (RC + dt) - - minval, maxval = get_min_max_value(seg.sample_width * 8) - - original = seg.get_array_of_samples() - filteredArray = array.array(seg.array_type, original) - - frame_count = int(seg.frame_count()) - - last_val = [0] * seg.channels - for i in range(seg.channels): - last_val[i] = filteredArray[i] = original[i] - - for i in range(1, frame_count): - for j in range(seg.channels): - offset = (i * seg.channels) + j - offset_minus_1 = ((i-1) * seg.channels) + j - - last_val[j] = alpha * (last_val[j] + original[offset] - original[offset_minus_1]) - filteredArray[offset] = int(min(max(last_val[j], minval), maxval)) - - return seg._spawn(data=filteredArray) - - -@register_pydub_effect -def pan(seg, pan_amount): - """ - pan_amount should be between -1.0 (100% left) and +1.0 (100% right) - - When pan_amount == 0.0 the left/right balance is not changed. - - Panning does not alter the *perceived* loundness, but since loudness - is decreasing on one side, the other side needs to get louder to - compensate. When panned hard left, the left channel will be 3dB louder. - """ - if not -1.0 <= pan_amount <= 1.0: - raise ValueError("pan_amount should be between -1.0 (100% left) and +1.0 (100% right)") - - max_boost_db = ratio_to_db(2.0) - boost_db = abs(pan_amount) * max_boost_db - - boost_factor = db_to_float(boost_db) - reduce_factor = db_to_float(max_boost_db) - boost_factor - - reduce_db = ratio_to_db(reduce_factor) - - # Cut boost in half (max boost== 3dB) - in reality 2 speakers - # do not sum to a full 6 dB. - boost_db = boost_db / 2.0 - - if pan_amount < 0: - return seg.apply_gain_stereo(boost_db, reduce_db) - else: - return seg.apply_gain_stereo(reduce_db, boost_db) - - -@register_pydub_effect -def apply_gain_stereo(seg, left_gain=0.0, right_gain=0.0): - """ - left_gain - amount of gain to apply to the left channel (in dB) - right_gain - amount of gain to apply to the right channel (in dB) - - note: mono audio segments will be converted to stereo - """ - if seg.channels == 1: - left = right = seg - elif seg.channels == 2: - left, right = seg.split_to_mono() - - l_mult_factor = db_to_float(left_gain) - r_mult_factor = db_to_float(right_gain) - - left_data = audioop.mul(left._data, left.sample_width, l_mult_factor) - left_data = audioop.tostereo(left_data, left.sample_width, 1, 0) - - right_data = audioop.mul(right._data, right.sample_width, r_mult_factor) - right_data = audioop.tostereo(right_data, right.sample_width, 0, 1) - - output = audioop.add(left_data, right_data, seg.sample_width) - - return seg._spawn(data=output, - overrides={'channels': 2, - 'frame_width': 2 * seg.sample_width}) diff --git a/sbapp/pydub/exceptions.py b/sbapp/pydub/exceptions.py deleted file mode 100644 index 79d0743..0000000 --- a/sbapp/pydub/exceptions.py +++ /dev/null @@ -1,32 +0,0 @@ -class PydubException(Exception): - """ - Base class for any Pydub exception - """ - - -class TooManyMissingFrames(PydubException): - pass - - -class InvalidDuration(PydubException): - pass - - -class InvalidTag(PydubException): - pass - - -class InvalidID3TagVersion(PydubException): - pass - - -class CouldntDecodeError(PydubException): - pass - - -class CouldntEncodeError(PydubException): - pass - - -class MissingAudioParameter(PydubException): - pass diff --git a/sbapp/pydub/generators.py b/sbapp/pydub/generators.py deleted file mode 100644 index b04cb4c..0000000 --- a/sbapp/pydub/generators.py +++ /dev/null @@ -1,142 +0,0 @@ -""" -Each generator will return float samples from -1.0 to 1.0, which can be -converted to actual audio with 8, 16, 24, or 32 bit depth using the -SiganlGenerator.to_audio_segment() method (on any of it's subclasses). - -See Wikipedia's "waveform" page for info on some of the generators included -here: http://en.wikipedia.org/wiki/Waveform -""" - -import math -import array -import itertools -import random -from .audio_segment import AudioSegment -from .utils import ( - db_to_float, - get_frame_width, - get_array_type, - get_min_max_value -) - - - -class SignalGenerator(object): - def __init__(self, sample_rate=44100, bit_depth=16): - self.sample_rate = sample_rate - self.bit_depth = bit_depth - - def to_audio_segment(self, duration=1000.0, volume=0.0): - """ - Duration in milliseconds - (default: 1 second) - Volume in DB relative to maximum amplitude - (default 0.0 dBFS, which is the maximum value) - """ - minval, maxval = get_min_max_value(self.bit_depth) - sample_width = get_frame_width(self.bit_depth) - array_type = get_array_type(self.bit_depth) - - gain = db_to_float(volume) - sample_count = int(self.sample_rate * (duration / 1000.0)) - - sample_data = (int(val * maxval * gain) for val in self.generate()) - sample_data = itertools.islice(sample_data, 0, sample_count) - - data = array.array(array_type, sample_data) - - try: - data = data.tobytes() - except: - data = data.tostring() - - return AudioSegment(data=data, metadata={ - "channels": 1, - "sample_width": sample_width, - "frame_rate": self.sample_rate, - "frame_width": sample_width, - }) - - def generate(self): - raise NotImplementedError("SignalGenerator subclasses must implement the generate() method, and *should not* call the superclass implementation.") - - - -class Sine(SignalGenerator): - def __init__(self, freq, **kwargs): - super(Sine, self).__init__(**kwargs) - self.freq = freq - - def generate(self): - sine_of = (self.freq * 2 * math.pi) / self.sample_rate - sample_n = 0 - while True: - yield math.sin(sine_of * sample_n) - sample_n += 1 - - - -class Pulse(SignalGenerator): - def __init__(self, freq, duty_cycle=0.5, **kwargs): - super(Pulse, self).__init__(**kwargs) - self.freq = freq - self.duty_cycle = duty_cycle - - def generate(self): - sample_n = 0 - - # in samples - cycle_length = self.sample_rate / float(self.freq) - pulse_length = cycle_length * self.duty_cycle - - while True: - if (sample_n % cycle_length) < pulse_length: - yield 1.0 - else: - yield -1.0 - sample_n += 1 - - - -class Square(Pulse): - def __init__(self, freq, **kwargs): - kwargs['duty_cycle'] = 0.5 - super(Square, self).__init__(freq, **kwargs) - - - -class Sawtooth(SignalGenerator): - def __init__(self, freq, duty_cycle=1.0, **kwargs): - super(Sawtooth, self).__init__(**kwargs) - self.freq = freq - self.duty_cycle = duty_cycle - - def generate(self): - sample_n = 0 - - # in samples - cycle_length = self.sample_rate / float(self.freq) - midpoint = cycle_length * self.duty_cycle - ascend_length = midpoint - descend_length = cycle_length - ascend_length - - while True: - cycle_position = sample_n % cycle_length - if cycle_position < midpoint: - yield (2 * cycle_position / ascend_length) - 1.0 - else: - yield 1.0 - (2 * (cycle_position - midpoint) / descend_length) - sample_n += 1 - - - -class Triangle(Sawtooth): - def __init__(self, freq, **kwargs): - kwargs['duty_cycle'] = 0.5 - super(Triangle, self).__init__(freq, **kwargs) - - -class WhiteNoise(SignalGenerator): - def generate(self): - while True: - yield (random.random() * 2) - 1.0 diff --git a/sbapp/pydub/logging_utils.py b/sbapp/pydub/logging_utils.py deleted file mode 100644 index a312bd2..0000000 --- a/sbapp/pydub/logging_utils.py +++ /dev/null @@ -1,14 +0,0 @@ -""" - -""" -import logging - -converter_logger = logging.getLogger("pydub.converter") - -def log_conversion(conversion_command): - converter_logger.debug("subprocess.call(%s)", repr(conversion_command)) - -def log_subprocess_output(output): - if output: - for line in output.rstrip().splitlines(): - converter_logger.debug('subprocess output: %s', line.rstrip()) diff --git a/sbapp/pydub/playback.py b/sbapp/pydub/playback.py deleted file mode 100644 index 72ce4a5..0000000 --- a/sbapp/pydub/playback.py +++ /dev/null @@ -1,71 +0,0 @@ -""" -Support for playing AudioSegments. Pyaudio will be used if it's installed, -otherwise will fallback to ffplay. Pyaudio is a *much* nicer solution, but -is tricky to install. See my notes on installing pyaudio in a virtualenv (on -OSX 10.10): https://gist.github.com/jiaaro/9767512210a1d80a8a0d -""" - -import subprocess -from tempfile import NamedTemporaryFile -from .utils import get_player_name, make_chunks - -def _play_with_ffplay(seg): - PLAYER = get_player_name() - with NamedTemporaryFile("w+b", suffix=".wav") as f: - seg.export(f.name, "wav") - subprocess.call([PLAYER, "-nodisp", "-autoexit", "-hide_banner", f.name]) - - -def _play_with_pyaudio(seg): - import pyaudio - - p = pyaudio.PyAudio() - stream = p.open(format=p.get_format_from_width(seg.sample_width), - channels=seg.channels, - rate=seg.frame_rate, - output=True) - - # Just in case there were any exceptions/interrupts, we release the resource - # So as not to raise OSError: Device Unavailable should play() be used again - try: - # break audio into half-second chunks (to allows keyboard interrupts) - for chunk in make_chunks(seg, 500): - stream.write(chunk._data) - finally: - stream.stop_stream() - stream.close() - - p.terminate() - - -def _play_with_simpleaudio(seg): - import simpleaudio - return simpleaudio.play_buffer( - seg.raw_data, - num_channels=seg.channels, - bytes_per_sample=seg.sample_width, - sample_rate=seg.frame_rate - ) - - -def play(audio_segment): - try: - playback = _play_with_simpleaudio(audio_segment) - try: - playback.wait_done() - except KeyboardInterrupt: - playback.stop() - except ImportError: - pass - else: - return - - try: - _play_with_pyaudio(audio_segment) - return - except ImportError: - pass - else: - return - - _play_with_ffplay(audio_segment) diff --git a/sbapp/pydub/pyaudioop.py b/sbapp/pydub/pyaudioop.py deleted file mode 100644 index 9b1e2fb..0000000 --- a/sbapp/pydub/pyaudioop.py +++ /dev/null @@ -1,553 +0,0 @@ -try: - from __builtin__ import max as builtin_max - from __builtin__ import min as builtin_min -except ImportError: - from builtins import max as builtin_max - from builtins import min as builtin_min -import math -import struct -try: - from fractions import gcd -except ImportError: # Python 3.9+ - from math import gcd -from ctypes import create_string_buffer - - -class error(Exception): - pass - - -def _check_size(size): - if size != 1 and size != 2 and size != 4: - raise error("Size should be 1, 2 or 4") - - -def _check_params(length, size): - _check_size(size) - if length % size != 0: - raise error("not a whole number of frames") - - -def _sample_count(cp, size): - return len(cp) / size - - -def _get_samples(cp, size, signed=True): - for i in range(_sample_count(cp, size)): - yield _get_sample(cp, size, i, signed) - - -def _struct_format(size, signed): - if size == 1: - return "b" if signed else "B" - elif size == 2: - return "h" if signed else "H" - elif size == 4: - return "i" if signed else "I" - - -def _get_sample(cp, size, i, signed=True): - fmt = _struct_format(size, signed) - start = i * size - end = start + size - return struct.unpack_from(fmt, buffer(cp)[start:end])[0] - - -def _put_sample(cp, size, i, val, signed=True): - fmt = _struct_format(size, signed) - struct.pack_into(fmt, cp, i * size, val) - - -def _get_maxval(size, signed=True): - if signed and size == 1: - return 0x7f - elif size == 1: - return 0xff - elif signed and size == 2: - return 0x7fff - elif size == 2: - return 0xffff - elif signed and size == 4: - return 0x7fffffff - elif size == 4: - return 0xffffffff - - -def _get_minval(size, signed=True): - if not signed: - return 0 - elif size == 1: - return -0x80 - elif size == 2: - return -0x8000 - elif size == 4: - return -0x80000000 - - -def _get_clipfn(size, signed=True): - maxval = _get_maxval(size, signed) - minval = _get_minval(size, signed) - return lambda val: builtin_max(min(val, maxval), minval) - - -def _overflow(val, size, signed=True): - minval = _get_minval(size, signed) - maxval = _get_maxval(size, signed) - if minval <= val <= maxval: - return val - - bits = size * 8 - if signed: - offset = 2**(bits-1) - return ((val + offset) % (2**bits)) - offset - else: - return val % (2**bits) - - -def getsample(cp, size, i): - _check_params(len(cp), size) - if not (0 <= i < len(cp) / size): - raise error("Index out of range") - return _get_sample(cp, size, i) - - -def max(cp, size): - _check_params(len(cp), size) - - if len(cp) == 0: - return 0 - - return builtin_max(abs(sample) for sample in _get_samples(cp, size)) - - -def minmax(cp, size): - _check_params(len(cp), size) - - max_sample, min_sample = 0, 0 - for sample in _get_samples(cp, size): - max_sample = builtin_max(sample, max_sample) - min_sample = builtin_min(sample, min_sample) - - return min_sample, max_sample - - -def avg(cp, size): - _check_params(len(cp), size) - sample_count = _sample_count(cp, size) - if sample_count == 0: - return 0 - return sum(_get_samples(cp, size)) / sample_count - - -def rms(cp, size): - _check_params(len(cp), size) - - sample_count = _sample_count(cp, size) - if sample_count == 0: - return 0 - - sum_squares = sum(sample**2 for sample in _get_samples(cp, size)) - return int(math.sqrt(sum_squares / sample_count)) - - -def _sum2(cp1, cp2, length): - size = 2 - total = 0 - for i in range(length): - total += getsample(cp1, size, i) * getsample(cp2, size, i) - return total - - -def findfit(cp1, cp2): - size = 2 - - if len(cp1) % 2 != 0 or len(cp2) % 2 != 0: - raise error("Strings should be even-sized") - - if len(cp1) < len(cp2): - raise error("First sample should be longer") - - len1 = _sample_count(cp1, size) - len2 = _sample_count(cp2, size) - - sum_ri_2 = _sum2(cp2, cp2, len2) - sum_aij_2 = _sum2(cp1, cp1, len2) - sum_aij_ri = _sum2(cp1, cp2, len2) - - result = (sum_ri_2 * sum_aij_2 - sum_aij_ri * sum_aij_ri) / sum_aij_2 - - best_result = result - best_i = 0 - - for i in range(1, len1 - len2 + 1): - aj_m1 = _get_sample(cp1, size, i - 1) - aj_lm1 = _get_sample(cp1, size, i + len2 - 1) - - sum_aij_2 += aj_lm1**2 - aj_m1**2 - sum_aij_ri = _sum2(buffer(cp1)[i*size:], cp2, len2) - - result = (sum_ri_2 * sum_aij_2 - sum_aij_ri * sum_aij_ri) / sum_aij_2 - - if result < best_result: - best_result = result - best_i = i - - factor = _sum2(buffer(cp1)[best_i*size:], cp2, len2) / sum_ri_2 - - return best_i, factor - - -def findfactor(cp1, cp2): - size = 2 - - if len(cp1) % 2 != 0: - raise error("Strings should be even-sized") - - if len(cp1) != len(cp2): - raise error("Samples should be same size") - - sample_count = _sample_count(cp1, size) - - sum_ri_2 = _sum2(cp2, cp2, sample_count) - sum_aij_ri = _sum2(cp1, cp2, sample_count) - - return sum_aij_ri / sum_ri_2 - - -def findmax(cp, len2): - size = 2 - sample_count = _sample_count(cp, size) - - if len(cp) % 2 != 0: - raise error("Strings should be even-sized") - - if len2 < 0 or sample_count < len2: - raise error("Input sample should be longer") - - if sample_count == 0: - return 0 - - result = _sum2(cp, cp, len2) - best_result = result - best_i = 0 - - for i in range(1, sample_count - len2 + 1): - sample_leaving_window = getsample(cp, size, i - 1) - sample_entering_window = getsample(cp, size, i + len2 - 1) - - result -= sample_leaving_window**2 - result += sample_entering_window**2 - - if result > best_result: - best_result = result - best_i = i - - return best_i - - -def avgpp(cp, size): - _check_params(len(cp), size) - sample_count = _sample_count(cp, size) - - prevextremevalid = False - prevextreme = None - avg = 0 - nextreme = 0 - - prevval = getsample(cp, size, 0) - val = getsample(cp, size, 1) - - prevdiff = val - prevval - - for i in range(1, sample_count): - val = getsample(cp, size, i) - diff = val - prevval - - if diff * prevdiff < 0: - if prevextremevalid: - avg += abs(prevval - prevextreme) - nextreme += 1 - - prevextremevalid = True - prevextreme = prevval - - prevval = val - if diff != 0: - prevdiff = diff - - if nextreme == 0: - return 0 - - return avg / nextreme - - -def maxpp(cp, size): - _check_params(len(cp), size) - sample_count = _sample_count(cp, size) - - prevextremevalid = False - prevextreme = None - max = 0 - - prevval = getsample(cp, size, 0) - val = getsample(cp, size, 1) - - prevdiff = val - prevval - - for i in range(1, sample_count): - val = getsample(cp, size, i) - diff = val - prevval - - if diff * prevdiff < 0: - if prevextremevalid: - extremediff = abs(prevval - prevextreme) - if extremediff > max: - max = extremediff - prevextremevalid = True - prevextreme = prevval - - prevval = val - if diff != 0: - prevdiff = diff - - return max - - -def cross(cp, size): - _check_params(len(cp), size) - - crossings = 0 - last_sample = 0 - for sample in _get_samples(cp, size): - if sample <= 0 < last_sample or sample >= 0 > last_sample: - crossings += 1 - last_sample = sample - - return crossings - - -def mul(cp, size, factor): - _check_params(len(cp), size) - clip = _get_clipfn(size) - - result = create_string_buffer(len(cp)) - - for i, sample in enumerate(_get_samples(cp, size)): - sample = clip(int(sample * factor)) - _put_sample(result, size, i, sample) - - return result.raw - - -def tomono(cp, size, fac1, fac2): - _check_params(len(cp), size) - clip = _get_clipfn(size) - - sample_count = _sample_count(cp, size) - - result = create_string_buffer(len(cp) / 2) - - for i in range(0, sample_count, 2): - l_sample = getsample(cp, size, i) - r_sample = getsample(cp, size, i + 1) - - sample = (l_sample * fac1) + (r_sample * fac2) - sample = clip(sample) - - _put_sample(result, size, i / 2, sample) - - return result.raw - - -def tostereo(cp, size, fac1, fac2): - _check_params(len(cp), size) - - sample_count = _sample_count(cp, size) - - result = create_string_buffer(len(cp) * 2) - clip = _get_clipfn(size) - - for i in range(sample_count): - sample = _get_sample(cp, size, i) - - l_sample = clip(sample * fac1) - r_sample = clip(sample * fac2) - - _put_sample(result, size, i * 2, l_sample) - _put_sample(result, size, i * 2 + 1, r_sample) - - return result.raw - - -def add(cp1, cp2, size): - _check_params(len(cp1), size) - - if len(cp1) != len(cp2): - raise error("Lengths should be the same") - - clip = _get_clipfn(size) - sample_count = _sample_count(cp1, size) - result = create_string_buffer(len(cp1)) - - for i in range(sample_count): - sample1 = getsample(cp1, size, i) - sample2 = getsample(cp2, size, i) - - sample = clip(sample1 + sample2) - - _put_sample(result, size, i, sample) - - return result.raw - - -def bias(cp, size, bias): - _check_params(len(cp), size) - - result = create_string_buffer(len(cp)) - - for i, sample in enumerate(_get_samples(cp, size)): - sample = _overflow(sample + bias, size) - _put_sample(result, size, i, sample) - - return result.raw - - -def reverse(cp, size): - _check_params(len(cp), size) - sample_count = _sample_count(cp, size) - - result = create_string_buffer(len(cp)) - for i, sample in enumerate(_get_samples(cp, size)): - _put_sample(result, size, sample_count - i - 1, sample) - - return result.raw - - -def lin2lin(cp, size, size2): - _check_params(len(cp), size) - _check_size(size2) - - if size == size2: - return cp - - new_len = (len(cp) / size) * size2 - - result = create_string_buffer(new_len) - - for i in range(_sample_count(cp, size)): - sample = _get_sample(cp, size, i) - if size < size2: - sample = sample << (4 * size2 / size) - elif size > size2: - sample = sample >> (4 * size / size2) - - sample = _overflow(sample, size2) - - _put_sample(result, size2, i, sample) - - return result.raw - - -def ratecv(cp, size, nchannels, inrate, outrate, state, weightA=1, weightB=0): - _check_params(len(cp), size) - if nchannels < 1: - raise error("# of channels should be >= 1") - - bytes_per_frame = size * nchannels - frame_count = len(cp) / bytes_per_frame - - if bytes_per_frame / nchannels != size: - raise OverflowError("width * nchannels too big for a C int") - - if weightA < 1 or weightB < 0: - raise error("weightA should be >= 1, weightB should be >= 0") - - if len(cp) % bytes_per_frame != 0: - raise error("not a whole number of frames") - - if inrate <= 0 or outrate <= 0: - raise error("sampling rate not > 0") - - d = gcd(inrate, outrate) - inrate /= d - outrate /= d - - prev_i = [0] * nchannels - cur_i = [0] * nchannels - - if state is None: - d = -outrate - else: - d, samps = state - - if len(samps) != nchannels: - raise error("illegal state argument") - - prev_i, cur_i = zip(*samps) - prev_i, cur_i = list(prev_i), list(cur_i) - - q = frame_count / inrate - ceiling = (q + 1) * outrate - nbytes = ceiling * bytes_per_frame - - result = create_string_buffer(nbytes) - - samples = _get_samples(cp, size) - out_i = 0 - while True: - while d < 0: - if frame_count == 0: - samps = zip(prev_i, cur_i) - retval = result.raw - - # slice off extra bytes - trim_index = (out_i * bytes_per_frame) - len(retval) - retval = buffer(retval)[:trim_index] - - return (retval, (d, tuple(samps))) - - for chan in range(nchannels): - prev_i[chan] = cur_i[chan] - cur_i[chan] = samples.next() - - cur_i[chan] = ( - (weightA * cur_i[chan] + weightB * prev_i[chan]) - / (weightA + weightB) - ) - - frame_count -= 1 - d += outrate - - while d >= 0: - for chan in range(nchannels): - cur_o = ( - (prev_i[chan] * d + cur_i[chan] * (outrate - d)) - / outrate - ) - _put_sample(result, size, out_i, _overflow(cur_o, size)) - out_i += 1 - d -= inrate - - -def lin2ulaw(cp, size): - raise NotImplementedError() - - -def ulaw2lin(cp, size): - raise NotImplementedError() - - -def lin2alaw(cp, size): - raise NotImplementedError() - - -def alaw2lin(cp, size): - raise NotImplementedError() - - -def lin2adpcm(cp, size, state): - raise NotImplementedError() - - -def adpcm2lin(cp, size, state): - raise NotImplementedError() diff --git a/sbapp/pydub/scipy_effects.py b/sbapp/pydub/scipy_effects.py deleted file mode 100644 index abab2b4..0000000 --- a/sbapp/pydub/scipy_effects.py +++ /dev/null @@ -1,175 +0,0 @@ -""" -This module provides scipy versions of high_pass_filter, and low_pass_filter -as well as an additional band_pass_filter. - -Of course, you will need to install scipy for these to work. - -When this module is imported the high and low pass filters from this module -will be used when calling audio_segment.high_pass_filter() and -audio_segment.high_pass_filter() instead of the slower, less powerful versions -provided by pydub.effects. -""" -from scipy.signal import butter, sosfilt -from .utils import (register_pydub_effect,stereo_to_ms,ms_to_stereo) - - -def _mk_butter_filter(freq, type, order): - """ - Args: - freq: The cutoff frequency for highpass and lowpass filters. For - band filters, a list of [low_cutoff, high_cutoff] - type: "lowpass", "highpass", or "band" - order: nth order butterworth filter (default: 5th order). The - attenuation is -6dB/octave beyond the cutoff frequency (for 1st - order). A Higher order filter will have more attenuation, each level - adding an additional -6dB (so a 3rd order butterworth filter would - be -18dB/octave). - - Returns: - function which can filter a mono audio segment - - """ - def filter_fn(seg): - assert seg.channels == 1 - - nyq = 0.5 * seg.frame_rate - try: - freqs = [f / nyq for f in freq] - except TypeError: - freqs = freq / nyq - - sos = butter(order, freqs, btype=type, output='sos') - y = sosfilt(sos, seg.get_array_of_samples()) - - return seg._spawn(y.astype(seg.array_type)) - - return filter_fn - - -@register_pydub_effect -def band_pass_filter(seg, low_cutoff_freq, high_cutoff_freq, order=5): - filter_fn = _mk_butter_filter([low_cutoff_freq, high_cutoff_freq], 'band', order=order) - return seg.apply_mono_filter_to_each_channel(filter_fn) - - -@register_pydub_effect -def high_pass_filter(seg, cutoff_freq, order=5): - filter_fn = _mk_butter_filter(cutoff_freq, 'highpass', order=order) - return seg.apply_mono_filter_to_each_channel(filter_fn) - - -@register_pydub_effect -def low_pass_filter(seg, cutoff_freq, order=5): - filter_fn = _mk_butter_filter(cutoff_freq, 'lowpass', order=order) - return seg.apply_mono_filter_to_each_channel(filter_fn) - - -@register_pydub_effect -def _eq(seg, focus_freq, bandwidth=100, mode="peak", gain_dB=0, order=2): - """ - Args: - focus_freq - middle frequency or known frequency of band (in Hz) - bandwidth - range of the equalizer band - mode - Mode of Equalization(Peak/Notch(Bell Curve),High Shelf, Low Shelf) - order - Rolloff factor(1 - 6dB/Octave 2 - 12dB/Octave) - - Returns: - Equalized/Filtered AudioSegment - """ - filt_mode = ["peak", "low_shelf", "high_shelf"] - if mode not in filt_mode: - raise ValueError("Incorrect Mode Selection") - - if gain_dB >= 0: - if mode == "peak": - sec = band_pass_filter(seg, focus_freq - bandwidth/2, focus_freq + bandwidth/2, order = order) - seg = seg.overlay(sec - (3 - gain_dB)) - return seg - - if mode == "low_shelf": - sec = low_pass_filter(seg, focus_freq, order=order) - seg = seg.overlay(sec - (3 - gain_dB)) - return seg - - if mode == "high_shelf": - sec = high_pass_filter(seg, focus_freq, order=order) - seg = seg.overlay(sec - (3 - gain_dB)) - return seg - - if gain_dB < 0: - if mode == "peak": - sec = high_pass_filter(seg, focus_freq - bandwidth/2, order=order) - seg = seg.overlay(sec - (3 + gain_dB)) + gain_dB - sec = low_pass_filter(seg, focus_freq + bandwidth/2, order=order) - seg = seg.overlay(sec - (3 + gain_dB)) + gain_dB - return seg - - if mode == "low_shelf": - sec = high_pass_filter(seg, focus_freq, order=order) - seg = seg.overlay(sec - (3 + gain_dB)) + gain_dB - return seg - - if mode=="high_shelf": - sec=low_pass_filter(seg, focus_freq, order=order) - seg=seg.overlay(sec - (3 + gain_dB)) +gain_dB - return seg - - -@register_pydub_effect -def eq(seg, focus_freq, bandwidth=100, channel_mode="L+R", filter_mode="peak", gain_dB=0, order=2): - """ - Args: - focus_freq - middle frequency or known frequency of band (in Hz) - bandwidth - range of the equalizer band - channel_mode - Select Channels to be affected by the filter. - L+R - Standard Stereo Filter - L - Only Left Channel is Filtered - R - Only Right Channel is Filtered - M+S - Blumlien Stereo Filter(Mid-Side) - M - Only Mid Channel is Filtered - S - Only Side Channel is Filtered - Mono Audio Segments are completely filtered. - filter_mode - Mode of Equalization(Peak/Notch(Bell Curve),High Shelf, Low Shelf) - order - Rolloff factor(1 - 6dB/Octave 2 - 12dB/Octave) - - Returns: - Equalized/Filtered AudioSegment - """ - channel_modes = ["L+R", "M+S", "L", "R", "M", "S"] - if channel_mode not in channel_modes: - raise ValueError("Incorrect Channel Mode Selection") - - if seg.channels == 1: - return _eq(seg, focus_freq, bandwidth, filter_mode, gain_dB, order) - - if channel_mode == "L+R": - return _eq(seg, focus_freq, bandwidth, filter_mode, gain_dB, order) - - if channel_mode == "L": - seg = seg.split_to_mono() - seg = [_eq(seg[0], focus_freq, bandwidth, filter_mode, gain_dB, order), seg[1]] - return AudioSegment.from_mono_audio_segements(seg[0], seg[1]) - - if channel_mode == "R": - seg = seg.split_to_mono() - seg = [seg[0], _eq(seg[1], focus_freq, bandwidth, filter_mode, gain_dB, order)] - return AudioSegment.from_mono_audio_segements(seg[0], seg[1]) - - if channel_mode == "M+S": - seg = stereo_to_ms(seg) - seg = _eq(seg, focus_freq, bandwidth, filter_mode, gain_dB, order) - return ms_to_stereo(seg) - - if channel_mode == "M": - seg = stereo_to_ms(seg).split_to_mono() - seg = [_eq(seg[0], focus_freq, bandwidth, filter_mode, gain_dB, order), seg[1]] - seg = AudioSegment.from_mono_audio_segements(seg[0], seg[1]) - return ms_to_stereo(seg) - - if channel_mode == "S": - seg = stereo_to_ms(seg).split_to_mono() - seg = [seg[0], _eq(seg[1], focus_freq, bandwidth, filter_mode, gain_dB, order)] - seg = AudioSegment.from_mono_audio_segements(seg[0], seg[1]) - return ms_to_stereo(seg) - - diff --git a/sbapp/pydub/silence.py b/sbapp/pydub/silence.py deleted file mode 100644 index 0ad1499..0000000 --- a/sbapp/pydub/silence.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -Various functions for finding/manipulating silence in AudioSegments -""" -import itertools - -from .utils import db_to_float - - -def detect_silence(audio_segment, min_silence_len=1000, silence_thresh=-16, seek_step=1): - """ - Returns a list of all silent sections [start, end] in milliseconds of audio_segment. - Inverse of detect_nonsilent() - - audio_segment - the segment to find silence in - min_silence_len - the minimum length for any silent section - silence_thresh - the upper bound for how quiet is silent in dFBS - seek_step - step size for interating over the segment in ms - """ - seg_len = len(audio_segment) - - # you can't have a silent portion of a sound that is longer than the sound - if seg_len < min_silence_len: - return [] - - # convert silence threshold to a float value (so we can compare it to rms) - silence_thresh = db_to_float(silence_thresh) * audio_segment.max_possible_amplitude - - # find silence and add start and end indicies to the to_cut list - silence_starts = [] - - # check successive (1 sec by default) chunk of sound for silence - # try a chunk at every "seek step" (or every chunk for a seek step == 1) - last_slice_start = seg_len - min_silence_len - slice_starts = range(0, last_slice_start + 1, seek_step) - - # guarantee last_slice_start is included in the range - # to make sure the last portion of the audio is searched - if last_slice_start % seek_step: - slice_starts = itertools.chain(slice_starts, [last_slice_start]) - - for i in slice_starts: - audio_slice = audio_segment[i:i + min_silence_len] - if audio_slice.rms <= silence_thresh: - silence_starts.append(i) - - # short circuit when there is no silence - if not silence_starts: - return [] - - # combine the silence we detected into ranges (start ms - end ms) - silent_ranges = [] - - prev_i = silence_starts.pop(0) - current_range_start = prev_i - - for silence_start_i in silence_starts: - continuous = (silence_start_i == prev_i + seek_step) - - # sometimes two small blips are enough for one particular slice to be - # non-silent, despite the silence all running together. Just combine - # the two overlapping silent ranges. - silence_has_gap = silence_start_i > (prev_i + min_silence_len) - - if not continuous and silence_has_gap: - silent_ranges.append([current_range_start, - prev_i + min_silence_len]) - current_range_start = silence_start_i - prev_i = silence_start_i - - silent_ranges.append([current_range_start, - prev_i + min_silence_len]) - - return silent_ranges - - -def detect_nonsilent(audio_segment, min_silence_len=1000, silence_thresh=-16, seek_step=1): - """ - Returns a list of all nonsilent sections [start, end] in milliseconds of audio_segment. - Inverse of detect_silent() - - audio_segment - the segment to find silence in - min_silence_len - the minimum length for any silent section - silence_thresh - the upper bound for how quiet is silent in dFBS - seek_step - step size for interating over the segment in ms - """ - silent_ranges = detect_silence(audio_segment, min_silence_len, silence_thresh, seek_step) - len_seg = len(audio_segment) - - # if there is no silence, the whole thing is nonsilent - if not silent_ranges: - return [[0, len_seg]] - - # short circuit when the whole audio segment is silent - if silent_ranges[0][0] == 0 and silent_ranges[0][1] == len_seg: - return [] - - prev_end_i = 0 - nonsilent_ranges = [] - for start_i, end_i in silent_ranges: - nonsilent_ranges.append([prev_end_i, start_i]) - prev_end_i = end_i - - if end_i != len_seg: - nonsilent_ranges.append([prev_end_i, len_seg]) - - if nonsilent_ranges[0] == [0, 0]: - nonsilent_ranges.pop(0) - - return nonsilent_ranges - - -def split_on_silence(audio_segment, min_silence_len=1000, silence_thresh=-16, keep_silence=100, - seek_step=1): - """ - Returns list of audio segments from splitting audio_segment on silent sections - - audio_segment - original pydub.AudioSegment() object - - min_silence_len - (in ms) minimum length of a silence to be used for - a split. default: 1000ms - - silence_thresh - (in dBFS) anything quieter than this will be - considered silence. default: -16dBFS - - keep_silence - (in ms or True/False) leave some silence at the beginning - and end of the chunks. Keeps the sound from sounding like it - is abruptly cut off. - When the length of the silence is less than the keep_silence duration - it is split evenly between the preceding and following non-silent - segments. - If True is specified, all the silence is kept, if False none is kept. - default: 100ms - - seek_step - step size for interating over the segment in ms - """ - - # from the itertools documentation - def pairwise(iterable): - "s -> (s0,s1), (s1,s2), (s2, s3), ..." - a, b = itertools.tee(iterable) - next(b, None) - return zip(a, b) - - if isinstance(keep_silence, bool): - keep_silence = len(audio_segment) if keep_silence else 0 - - output_ranges = [ - [ start - keep_silence, end + keep_silence ] - for (start,end) - in detect_nonsilent(audio_segment, min_silence_len, silence_thresh, seek_step) - ] - - for range_i, range_ii in pairwise(output_ranges): - last_end = range_i[1] - next_start = range_ii[0] - if next_start < last_end: - range_i[1] = (last_end+next_start)//2 - range_ii[0] = range_i[1] - - return [ - audio_segment[ max(start,0) : min(end,len(audio_segment)) ] - for start,end in output_ranges - ] - - -def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10): - """ - Returns the millisecond/index that the leading silence ends. - - audio_segment - the segment to find silence in - silence_threshold - the upper bound for how quiet is silent in dFBS - chunk_size - chunk size for interating over the segment in ms - """ - trim_ms = 0 # ms - assert chunk_size > 0 # to avoid infinite loop - while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(sound): - trim_ms += chunk_size - - # if there is no end it should return the length of the segment - return min(trim_ms, len(sound)) - - diff --git a/sbapp/pydub/utils.py b/sbapp/pydub/utils.py deleted file mode 100644 index 740c500..0000000 --- a/sbapp/pydub/utils.py +++ /dev/null @@ -1,434 +0,0 @@ -from __future__ import division - -import json -import os -import re -import sys -from subprocess import Popen, PIPE -from math import log, ceil -from tempfile import TemporaryFile -from warnings import warn -from functools import wraps - -try: - import audioop -except ImportError: - import pyaudioop as audioop - -if sys.version_info >= (3, 0): - basestring = str - -FRAME_WIDTHS = { - 8: 1, - 16: 2, - 32: 4, -} -ARRAY_TYPES = { - 8: "b", - 16: "h", - 32: "i", -} -ARRAY_RANGES = { - 8: (-0x80, 0x7f), - 16: (-0x8000, 0x7fff), - 32: (-0x80000000, 0x7fffffff), -} - - -def get_frame_width(bit_depth): - return FRAME_WIDTHS[bit_depth] - - -def get_array_type(bit_depth, signed=True): - t = ARRAY_TYPES[bit_depth] - if not signed: - t = t.upper() - return t - - -def get_min_max_value(bit_depth): - return ARRAY_RANGES[bit_depth] - - -def _fd_or_path_or_tempfile(fd, mode='w+b', tempfile=True): - close_fd = False - if fd is None and tempfile: - fd = TemporaryFile(mode=mode) - close_fd = True - - if isinstance(fd, basestring): - fd = open(fd, mode=mode) - close_fd = True - - try: - if isinstance(fd, os.PathLike): - fd = open(fd, mode=mode) - close_fd = True - except AttributeError: - # module os has no attribute PathLike, so we're on python < 3.6. - # The protocol we're trying to support doesn't exist, so just pass. - pass - - return fd, close_fd - - -def db_to_float(db, using_amplitude=True): - """ - Converts the input db to a float, which represents the equivalent - ratio in power. - """ - db = float(db) - if using_amplitude: - return 10 ** (db / 20) - else: # using power - return 10 ** (db / 10) - - -def ratio_to_db(ratio, val2=None, using_amplitude=True): - """ - Converts the input float to db, which represents the equivalent - to the ratio in power represented by the multiplier passed in. - """ - ratio = float(ratio) - - # accept 2 values and use the ratio of val1 to val2 - if val2 is not None: - ratio = ratio / val2 - - # special case for multiply-by-zero (convert to silence) - if ratio == 0: - return -float('inf') - - if using_amplitude: - return 20 * log(ratio, 10) - else: # using power - return 10 * log(ratio, 10) - - -def register_pydub_effect(fn, name=None): - """ - decorator for adding pydub effects to the AudioSegment objects. - example use: - @register_pydub_effect - def normalize(audio_segment): - ... - or you can specify a name: - @register_pydub_effect("normalize") - def normalize_audio_segment(audio_segment): - ... - """ - if isinstance(fn, basestring): - name = fn - return lambda fn: register_pydub_effect(fn, name) - - if name is None: - name = fn.__name__ - - from .audio_segment import AudioSegment - setattr(AudioSegment, name, fn) - return fn - - -def make_chunks(audio_segment, chunk_length): - """ - Breaks an AudioSegment into chunks that are milliseconds - long. - if chunk_length is 50 then you'll get a list of 50 millisecond long audio - segments back (except the last one, which can be shorter) - """ - number_of_chunks = ceil(len(audio_segment) / float(chunk_length)) - return [audio_segment[i * chunk_length:(i + 1) * chunk_length] - for i in range(int(number_of_chunks))] - - -def which(program): - """ - Mimics behavior of UNIX which command. - """ - # Add .exe program extension for windows support - if os.name == "nt" and not program.endswith(".exe"): - program += ".exe" - - envdir_list = [os.curdir] + os.environ["PATH"].split(os.pathsep) - - for envdir in envdir_list: - program_path = os.path.join(envdir, program) - if os.path.isfile(program_path) and os.access(program_path, os.X_OK): - return program_path - - -def get_encoder_name(): - """ - Return enconder default application for system, either avconv or ffmpeg - """ - if which("avconv"): - return "avconv" - elif which("ffmpeg"): - return "ffmpeg" - else: - # should raise exception - warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning) - return "ffmpeg" - - -def get_player_name(): - """ - Return enconder default application for system, either avconv or ffmpeg - """ - if which("avplay"): - return "avplay" - elif which("ffplay"): - return "ffplay" - else: - # should raise exception - warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning) - return "ffplay" - - -def get_prober_name(): - """ - Return probe application, either avconv or ffmpeg - """ - if which("avprobe"): - return "avprobe" - elif which("ffprobe"): - return "ffprobe" - else: - # should raise exception - warn("Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work", RuntimeWarning) - return "ffprobe" - - -def fsdecode(filename): - """Wrapper for os.fsdecode which was introduced in python 3.2 .""" - - if sys.version_info >= (3, 2): - PathLikeTypes = (basestring, bytes) - if sys.version_info >= (3, 6): - PathLikeTypes += (os.PathLike,) - if isinstance(filename, PathLikeTypes): - return os.fsdecode(filename) - else: - if isinstance(filename, bytes): - return filename.decode(sys.getfilesystemencoding()) - if isinstance(filename, basestring): - return filename - - raise TypeError("type {0} not accepted by fsdecode".format(type(filename))) - - -def get_extra_info(stderr): - """ - avprobe sometimes gives more information on stderr than - on the json output. The information has to be extracted - from stderr of the format of: - ' Stream #0:0: Audio: flac, 88200 Hz, stereo, s32 (24 bit)' - or (macOS version): - ' Stream #0:0: Audio: vorbis' - ' 44100 Hz, stereo, fltp, 320 kb/s' - - :type stderr: str - :rtype: list of dict - """ - extra_info = {} - - re_stream = r'(?P +)Stream #0[:\.](?P([0-9]+))(?P.+)\n?(?! *Stream)((?P +)(?P.+))?' - for i in re.finditer(re_stream, stderr): - if i.group('space_end') is not None and len(i.group('space_start')) <= len( - i.group('space_end')): - content_line = ','.join([i.group('content_0'), i.group('content_1')]) - else: - content_line = i.group('content_0') - tokens = [x.strip() for x in re.split('[:,]', content_line) if x] - extra_info[int(i.group('stream_id'))] = tokens - return extra_info - - -def mediainfo_json(filepath, read_ahead_limit=-1): - """Return json dictionary with media info(codec, duration, size, bitrate...) from filepath - """ - prober = get_prober_name() - command_args = [ - "-v", "info", - "-show_format", - "-show_streams", - ] - try: - command_args += [fsdecode(filepath)] - stdin_parameter = None - stdin_data = None - except TypeError: - if prober == 'ffprobe': - command_args += ["-read_ahead_limit", str(read_ahead_limit), - "cache:pipe:0"] - else: - command_args += ["-"] - stdin_parameter = PIPE - file, close_file = _fd_or_path_or_tempfile(filepath, 'rb', tempfile=False) - file.seek(0) - stdin_data = file.read() - if close_file: - file.close() - - command = [prober, '-of', 'json'] + command_args - res = Popen(command, stdin=stdin_parameter, stdout=PIPE, stderr=PIPE) - output, stderr = res.communicate(input=stdin_data) - output = output.decode("utf-8", 'ignore') - stderr = stderr.decode("utf-8", 'ignore') - - info = json.loads(output) - - if not info: - # If ffprobe didn't give any information, just return it - # (for example, because the file doesn't exist) - return info - - extra_info = get_extra_info(stderr) - - audio_streams = [x for x in info['streams'] if x['codec_type'] == 'audio'] - if len(audio_streams) == 0: - return info - - # We just operate on the first audio stream in case there are more - stream = audio_streams[0] - - def set_property(stream, prop, value): - if prop not in stream or stream[prop] == 0: - stream[prop] = value - - for token in extra_info[stream['index']]: - m = re.match('([su]([0-9]{1,2})p?) \(([0-9]{1,2}) bit\)$', token) - m2 = re.match('([su]([0-9]{1,2})p?)( \(default\))?$', token) - if m: - set_property(stream, 'sample_fmt', m.group(1)) - set_property(stream, 'bits_per_sample', int(m.group(2))) - set_property(stream, 'bits_per_raw_sample', int(m.group(3))) - elif m2: - set_property(stream, 'sample_fmt', m2.group(1)) - set_property(stream, 'bits_per_sample', int(m2.group(2))) - set_property(stream, 'bits_per_raw_sample', int(m2.group(2))) - elif re.match('(flt)p?( \(default\))?$', token): - set_property(stream, 'sample_fmt', token) - set_property(stream, 'bits_per_sample', 32) - set_property(stream, 'bits_per_raw_sample', 32) - elif re.match('(dbl)p?( \(default\))?$', token): - set_property(stream, 'sample_fmt', token) - set_property(stream, 'bits_per_sample', 64) - set_property(stream, 'bits_per_raw_sample', 64) - return info - - -def mediainfo(filepath): - """Return dictionary with media info(codec, duration, size, bitrate...) from filepath - """ - - prober = get_prober_name() - command_args = [ - "-v", "quiet", - "-show_format", - "-show_streams", - filepath - ] - - command = [prober, '-of', 'old'] + command_args - res = Popen(command, stdout=PIPE) - output = res.communicate()[0].decode("utf-8") - - if res.returncode != 0: - command = [prober] + command_args - output = Popen(command, stdout=PIPE).communicate()[0].decode("utf-8") - - rgx = re.compile(r"(?:(?P.*?):)?(?P.*?)\=(?P.*?)$") - info = {} - - if sys.platform == 'win32': - output = output.replace("\r", "") - - for line in output.split("\n"): - # print(line) - mobj = rgx.match(line) - - if mobj: - # print(mobj.groups()) - inner_dict, key, value = mobj.groups() - - if inner_dict: - try: - info[inner_dict] - except KeyError: - info[inner_dict] = {} - info[inner_dict][key] = value - else: - info[key] = value - - return info - - -def cache_codecs(function): - cache = {} - - @wraps(function) - def wrapper(): - try: - return cache[0] - except: - cache[0] = function() - return cache[0] - - return wrapper - - -@cache_codecs -def get_supported_codecs(): - encoder = get_encoder_name() - command = [encoder, "-codecs"] - res = Popen(command, stdout=PIPE, stderr=PIPE) - output = res.communicate()[0].decode("utf-8") - if res.returncode != 0: - return [] - - if sys.platform == 'win32': - output = output.replace("\r", "") - - - rgx = re.compile(r"^([D.][E.][AVS.][I.][L.][S.]) (\w*) +(.*)") - decoders = set() - encoders = set() - for line in output.split('\n'): - match = rgx.match(line.strip()) - if not match: - continue - flags, codec, name = match.groups() - - if flags[0] == 'D': - decoders.add(codec) - - if flags[1] == 'E': - encoders.add(codec) - - return (decoders, encoders) - - -def get_supported_decoders(): - return get_supported_codecs()[0] - - -def get_supported_encoders(): - return get_supported_codecs()[1] - -def stereo_to_ms(audio_segment): - ''' - Left-Right -> Mid-Side - ''' - channel = audio_segment.split_to_mono() - channel = [channel[0].overlay(channel[1]), channel[0].overlay(channel[1].invert_phase())] - return AudioSegment.from_mono_audiosegments(channel[0], channel[1]) - -def ms_to_stereo(audio_segment): - ''' - Mid-Side -> Left-Right - ''' - channel = audio_segment.split_to_mono() - channel = [channel[0].overlay(channel[1]) - 3, channel[0].overlay(channel[1].invert_phase()) - 3] - return AudioSegment.from_mono_audiosegments(channel[0], channel[1]) - diff --git a/sbapp/pyogg/__init__.py b/sbapp/pyogg/__init__.py deleted file mode 100644 index a97b0d2..0000000 --- a/sbapp/pyogg/__init__.py +++ /dev/null @@ -1,108 +0,0 @@ -import ctypes - -from .pyogg_error import PyOggError -from .ogg import PYOGG_OGG_AVAIL -from .vorbis import PYOGG_VORBIS_AVAIL, PYOGG_VORBIS_FILE_AVAIL, PYOGG_VORBIS_ENC_AVAIL -from .opus import PYOGG_OPUS_AVAIL, PYOGG_OPUS_FILE_AVAIL, PYOGG_OPUS_ENC_AVAIL -from .flac import PYOGG_FLAC_AVAIL - - -#: PyOgg version number. Versions should comply with PEP440. -__version__ = '0.7' - - -if (PYOGG_OGG_AVAIL and PYOGG_VORBIS_AVAIL and PYOGG_VORBIS_FILE_AVAIL): - # VorbisFile - from .vorbis_file import VorbisFile - # VorbisFileStream - from .vorbis_file_stream import VorbisFileStream - -else: - class VorbisFile: # type: ignore - def __init__(*args, **kw): - if not PYOGG_OGG_AVAIL: - raise PyOggError("The Ogg library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - raise PyOggError("The Vorbis libraries weren't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - - class VorbisFileStream: # type: ignore - def __init__(*args, **kw): - if not PYOGG_OGG_AVAIL: - raise PyOggError("The Ogg library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - raise PyOggError("The Vorbis libraries weren't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - - - -if (PYOGG_OGG_AVAIL and PYOGG_OPUS_AVAIL and PYOGG_OPUS_FILE_AVAIL): - # OpusFile - from .opus_file import OpusFile - # OpusFileStream - from .opus_file_stream import OpusFileStream - -else: - class OpusFile: # type: ignore - def __init__(*args, **kw): - if not PYOGG_OGG_AVAIL: - raise PyOggError("The Ogg library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - if not PYOGG_OPUS_AVAIL: - raise PyOggError("The Opus library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - if not PYOGG_OPUS_FILE_AVAIL: - raise PyOggError("The OpusFile library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - raise PyOggError("Unknown initialisation error") - - class OpusFileStream: # type: ignore - def __init__(*args, **kw): - if not PYOGG_OGG_AVAIL: - raise PyOggError("The Ogg library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - if not PYOGG_OPUS_AVAIL: - raise PyOggError("The Opus library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - if not PYOGG_OPUS_FILE_AVAIL: - raise PyOggError("The OpusFile library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - raise PyOggError("Unknown initialisation error") - - -if PYOGG_OPUS_AVAIL: - # OpusEncoder - from .opus_encoder import OpusEncoder - # OpusBufferedEncoder - from .opus_buffered_encoder import OpusBufferedEncoder - # OpusDecoder - from .opus_decoder import OpusDecoder - -else: - class OpusEncoder: # type: ignore - def __init__(*args, **kw): - raise PyOggError("The Opus library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - - class OpusBufferedEncoder: # type: ignore - def __init__(*args, **kw): - raise PyOggError("The Opus library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - - class OpusDecoder: # type: ignore - def __init__(*args, **kw): - raise PyOggError("The Opus library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - -if (PYOGG_OGG_AVAIL and PYOGG_OPUS_AVAIL): - # OggOpusWriter - from .ogg_opus_writer import OggOpusWriter - -else: - class OggOpusWriter: # type: ignore - def __init__(*args, **kw): - if not PYOGG_OGG_AVAIL: - raise PyOggError("The Ogg library wasn't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - raise PyOggError("The Opus library was't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - - -if PYOGG_FLAC_AVAIL: - # FlacFile - from .flac_file import FlacFile - # FlacFileStream - from .flac_file_stream import FlacFileStream -else: - class FlacFile: # type: ignore - def __init__(*args, **kw): - raise PyOggError("The FLAC libraries weren't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") - - class FlacFileStream: # type: ignore - def __init__(*args, **kw): - raise PyOggError("The FLAC libraries weren't found or couldn't be loaded (maybe you're trying to use 64bit libraries with 32bit Python?)") diff --git a/sbapp/pyogg/audio_file.py b/sbapp/pyogg/audio_file.py deleted file mode 100644 index 4fb77a2..0000000 --- a/sbapp/pyogg/audio_file.py +++ /dev/null @@ -1,59 +0,0 @@ -from .pyogg_error import PyOggError - -class AudioFile: - """Abstract base class for audio files. - - This class is a base class for audio files (such as Vorbis, Opus, - and FLAC). It should not be instatiated directly. - """ - - def __init__(self): - raise PyOggError("AudioFile is an Abstract Base Class "+ - "and should not be instantiated") - - def as_array(self): - """Returns the buffer as a NumPy array. - - The shape of the returned array is in units of (number of - samples per channel, number of channels). - - The data type is either 8-bit or 16-bit signed integers, - depending on bytes_per_sample. - - The buffer is not copied, but rather the NumPy array - shares the memory with the buffer. - - """ - # Assumes that self.buffer is a one-dimensional array of - # bytes and that channels are interleaved. - - import numpy # type: ignore - - assert self.buffer is not None - assert self.channels is not None - - # The following code assumes that the bytes in the buffer - # represent 8-bit or 16-bit signed ints. Ensure the number of - # bytes per sample matches that assumption. - assert self.bytes_per_sample == 1 or self.bytes_per_sample == 2 - - # Create a dictionary mapping bytes per sample to numpy data - # types - dtype = { - 1: numpy.int8, - 2: numpy.int16 - } - - # Convert the ctypes buffer to a NumPy array - array = numpy.frombuffer( - self.buffer, - dtype=dtype[self.bytes_per_sample] - ) - - # Reshape the array - return array.reshape( - (len(self.buffer) - // self.bytes_per_sample - // self.channels, - self.channels) - ) diff --git a/sbapp/pyogg/flac.py b/sbapp/pyogg/flac.py deleted file mode 100644 index d44509e..0000000 --- a/sbapp/pyogg/flac.py +++ /dev/null @@ -1,2061 +0,0 @@ -############################################################ -# Flac license: # -############################################################ -""" -Copyright (C) 2000-2009 Josh Coalson -Copyright (C) 2011-2016 Xiph.Org Foundation - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -- Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -- Neither the name of the Xiph.org Foundation nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - -import ctypes -from ctypes import c_int, c_int8, c_int16, c_int32, c_int64, c_uint, c_uint8, c_uint16, c_uint32, c_uint64, c_float, c_long, c_ulong, c_char, c_bool, c_char_p, c_ubyte, c_longlong, c_ulonglong, c_size_t, c_void_p, c_double, POINTER, pointer, cast, CFUNCTYPE, Structure, Union -import ctypes.util -import sys -from traceback import print_exc as _print_exc -import os - -from .ogg import * - -from .library_loader import ExternalLibrary, ExternalLibraryError - -__here = os.getcwd() - -libflac = None - -try: - names = { - "Windows": "libFLAC.dll", - "Darwin": "libFLAC.8.dylib", - "external": "FLAC" - } - libflac = Library.load(names, tests = [lambda lib: hasattr(lib, "FLAC__EntropyCodingMethodTypeString")]) -except ExternalLibraryError: - pass -except: - _print_exc() - -if libflac: - PYOGG_FLAC_AVAIL = True -else: - PYOGG_FLAC_AVAIL = False - -# ctypes -c_ubyte_p = POINTER(c_ubyte) -c_uchar_p = c_ubyte_p -c_uint_p = POINTER(c_uint) -c_size_t_p = POINTER(c_size_t) -c_off_t = c_int32 -# /ctypes - -if PYOGG_FLAC_AVAIL: - # Sanity check also satisfies mypy type checking - assert libflac is not None - - # ordinals - - FLAC__int8 = c_int8 - FLAC__uint8 = c_uint8 - - FLAC__int16 = c_int16 - - FLAC__int32 = c_int32 - FLAC__int32_p = POINTER(FLAC__int32) - - FLAC__int64 = c_int64 - FLAC__uint16 = c_uint16 - FLAC__uint32 = c_uint32 - FLAC__uint64 = c_uint64 - - FLAC__uint64_p = POINTER(FLAC__uint64) - - FLAC__bool = c_bool - - FLAC__byte = c_uint8 - - FLAC__byte_p = POINTER(FLAC__byte) - - c_char_p_p = POINTER(c_char_p) - - # /ordinals - - # callback - - FLAC__IOHandle = CFUNCTYPE(c_void_p) - - FLAC__IOCallback_Read = CFUNCTYPE(c_size_t, - c_void_p, - c_size_t, - c_size_t, - FLAC__IOHandle) - - FLAC__IOCallback_Write = CFUNCTYPE(c_size_t, c_void_p, c_size_t, c_size_t, FLAC__IOHandle) - - FLAC__IOCallback_Seek = CFUNCTYPE(c_int, FLAC__IOHandle, FLAC__int64, c_int) - - FLAC__IOCallback_Tell = CFUNCTYPE(FLAC__int64, FLAC__IOHandle) - - FLAC__IOCallback_Eof = CFUNCTYPE(c_int, FLAC__IOHandle) - - FLAC__IOCallback_Close = CFUNCTYPE(c_int, FLAC__IOHandle) - - class FLAC__IOCallbacks(Structure): - _fields_ = [("read", FLAC__IOCallback_Read), - ("write", FLAC__IOCallback_Write), - ("seek", FLAC__IOCallback_Seek), - ("tell", FLAC__IOCallback_Tell), - ("eof", FLAC__IOCallback_Eof), - ("close", FLAC__IOCallback_Close)] - - # /callback - - # format - - FLAC__MAX_METADATA_TYPE_CODE =(126) - FLAC__MIN_BLOCK_SIZE =(16) - FLAC__MAX_BLOCK_SIZE =(65535) - FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ =(4608) - FLAC__MAX_CHANNELS =(8) - FLAC__MIN_BITS_PER_SAMPLE =(4) - FLAC__MAX_BITS_PER_SAMPLE =(32) - FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE =(24) - FLAC__MAX_SAMPLE_RATE =(655350) - FLAC__MAX_LPC_ORDER =(32) - FLAC__SUBSET_MAX_LPC_ORDER_48000HZ =(12) - FLAC__MIN_QLP_COEFF_PRECISION =(5) - FLAC__MAX_QLP_COEFF_PRECISION =(15) - FLAC__MAX_FIXED_ORDER =(4) - FLAC__MAX_RICE_PARTITION_ORDER =(15) - FLAC__SUBSET_MAX_RICE_PARTITION_ORDER =(8) - - FLAC__VERSION_STRING = c_char_p.in_dll(libflac, "FLAC__VERSION_STRING") - - FLAC__VENDOR_STRING = c_char_p.in_dll(libflac, "FLAC__VENDOR_STRING") - - FLAC__STREAM_SYNC_STRING = (FLAC__byte * 4).in_dll(libflac, "FLAC__STREAM_SYNC_STRING") - - FLAC__STREAM_SYNC = c_uint.in_dll(libflac, "FLAC__STREAM_SYNC") - - FLAC__STREAM_SYNC_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_SYNC_LEN") - - FLAC__STREAM_SYNC_LENGTH =(4) - - - - FLAC__EntropyCodingMethodType = c_int - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0 - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1 - - - - libflac.FLAC__EntropyCodingMethodTypeString.restype = c_char_p - libflac.FLAC__EntropyCodingMethodTypeString.argtypes = [] - - def FLAC__EntropyCodingMethodTypeString(): - return libflac.FLAC__EntropyCodingMethodTypeString() - - - - class FLAC__EntropyCodingMethod_PartitionedRiceContents(Structure): - _fields_ = [("parameters", c_uint_p), - ("raw_bits", c_uint_p), - ("capacity_by_order", c_uint)] - - class FLAC__EntropyCodingMethod_PartitionedRice(Structure): - _fields_ = [("order", c_uint), - ("contents", POINTER(FLAC__EntropyCodingMethod_PartitionedRiceContents))] - - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = c_uint.in_dll(libflac, "FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN") - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = c_uint.in_dll(libflac, "FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN") - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = c_uint.in_dll(libflac, "FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN") - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = c_uint.in_dll(libflac, "FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN") - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = c_uint.in_dll(libflac, "FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER") - - - class FLAC__EntropyCodingMethod_data(Union): - _fields_ = [("partitioned_rice", FLAC__EntropyCodingMethod_PartitionedRice)] - - class FLAC__EntropyCodingMethod(Structure): - _fields_ = [("type", POINTER(FLAC__EntropyCodingMethodType)), - ("data", FLAC__EntropyCodingMethod_data)] - - FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = c_uint.in_dll(libflac, "FLAC__ENTROPY_CODING_METHOD_TYPE_LEN") - - - - FLAC__SubframeType = c_int - FLAC__SUBFRAME_TYPE_CONSTANT = 0 - FLAC__SUBFRAME_TYPE_VERBATIM = 1 - FLAC__SUBFRAME_TYPE_FIXED = 2 - FLAC__SUBFRAME_TYPE_LPC = 3 - - - - libflac.FLAC__SubframeTypeString.restype = c_char_p - libflac.FLAC__SubframeTypeString.argtypes = [] - - def FLAC__SubframeTypeString(): - return libflac.FLAC__SubframeTypeString() - - - - class FLAC__Subframe_Constant(Structure): - _fields_ = [("value", FLAC__int32)] - - - class FLAC__Subframe_Verbatim(Structure): - _fields_ = [("data", FLAC__int32_p)] - - - class FLAC__Subframe_Fixed(Structure): - _fields_ = [("entropy_coding_method", FLAC__EntropyCodingMethod), - ("order", c_uint), - ("warmup", FLAC__int32 * FLAC__MAX_FIXED_ORDER), - ("residual", FLAC__int32_p)] - - - class FLAC__Subframe_LPC(Structure): - _fields_ = [("entropy_coding_method", FLAC__EntropyCodingMethod), - ("order", c_uint), - ("qlp_coeff_precision", c_uint), - ("quantization_level", c_int), - ("qlp_coeff", FLAC__int32 * FLAC__MAX_LPC_ORDER), - ("warmup", FLAC__int32 * FLAC__MAX_LPC_ORDER), - ("residual", FLAC__int32_p)] - - - FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = c_uint.in_dll(libflac, "FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN") - - FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = c_uint.in_dll(libflac, "FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN") - - - - class FLAC__Subframe_data(Union): - _fields_ = [("constant", FLAC__Subframe_Constant), - ("fixed", FLAC__Subframe_Fixed), - ("lpc", FLAC__Subframe_LPC), - ("verbatim", FLAC__Subframe_Verbatim)] - - class FLAC__Subframe(Structure): - _fields_ = [("type", FLAC__SubframeType), - ("data", FLAC__Subframe_data), - ("wasted_bits", c_uint)] - - - FLAC__SUBFRAME_ZERO_PAD_LEN = c_uint.in_dll(libflac, "FLAC__SUBFRAME_ZERO_PAD_LEN") - - FLAC__SUBFRAME_TYPE_LEN = c_uint.in_dll(libflac, "FLAC__SUBFRAME_TYPE_LEN") - - FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = c_uint.in_dll(libflac, "FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN") - - FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = c_uint.in_dll(libflac, "FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK") - - FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = c_uint.in_dll(libflac, "FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK") - - FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = c_uint.in_dll(libflac, "FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK") - - FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = c_uint.in_dll(libflac, "FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK") - - - FLAC__ChannelAssignment = c_int - - FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0 - FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1 - FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2 - FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 - - - - libflac.FLAC__ChannelAssignmentString.restype = c_char_p - libflac.FLAC__ChannelAssignmentString.argtypes = [] - - def FLAC__ChannelAssignmentString(): - return libflac.FLAC__ChannelAssignmentString() - - FLAC__FrameNumberType = c_int - - - libflac.FLAC__FrameNumberTypeString.restype = c_char_p - libflac.FLAC__FrameNumberTypeString.argtypes = [] - - def FLAC__FrameNumberTypeString(): - return libflac.FLAC__FrameNumberTypeString() - - - class FLAC__FrameHeader_number(Union): - _fields_ =[("frame_number", FLAC__uint32), - ("sample_number", FLAC__uint64)] - - class FLAC__FrameHeader(Structure): - _fields_ = [("blocksize", c_uint), - ("sample_rate", c_uint), - ("channels", c_uint), - ("channel_assignment", FLAC__ChannelAssignment), - ("bits_per_sample", c_uint), - ("number_type", FLAC__FrameNumberType), - ("number", FLAC__FrameHeader_number), - ("crc", FLAC__uint8)] - - - FLAC__FRAME_HEADER_SYNC = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_SYNC") - - FLAC__FRAME_HEADER_RESERVED_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_RESERVED_LEN") - - FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN") - - FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_BLOCK_SIZE_LEN") - - FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_SAMPLE_RATE_LEN") - - FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN") - - FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN") - - FLAC__FRAME_HEADER_ZERO_PAD_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_ZERO_PAD_LEN") - - FLAC__FRAME_HEADER_CRC_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_HEADER_CRC_LEN") - - - - class FLAC__FrameFooter(Structure): - _fields_ = [("crc", FLAC__uint16)] - - FLAC__FRAME_FOOTER_CRC_LEN = c_uint.in_dll(libflac, "FLAC__FRAME_FOOTER_CRC_LEN") - - - - class FLAC__Frame(Structure): - _fields_ = [("header", FLAC__FrameHeader), - ("subframes", FLAC__Subframe * FLAC__MAX_CHANNELS), - ("footer", FLAC__FrameFooter)] - - - FLAC__MetadataType = c_int - - FLAC__METADATA_TYPE_STREAMINFO = 0 - - FLAC__METADATA_TYPE_PADDING = 1 - - FLAC__METADATA_TYPE_APPLICATION = 2 - - FLAC__METADATA_TYPE_SEEKTABLE = 3 - - FLAC__METADATA_TYPE_VORBIS_COMMENT = 4 - - FLAC__METADATA_TYPE_CUESHEET = 5 - - FLAC__METADATA_TYPE_PICTURE = 6 - - FLAC__METADATA_TYPE_UNDEFINED = 7 - - FLAC__MAX_METADATA_TYPE = FLAC__MAX_METADATA_TYPE_CODE - - - - libflac.FLAC__MetadataTypeString.restype = c_char_p - libflac.FLAC__MetadataTypeString.argtypes = [] - - def FLAC__MetadataTypeString(): - return libflac.FLAC__MetadataTypeString() - - - - class FLAC__StreamMetadata_StreamInfo(Structure): - _fields_ = [("min_blocksize", c_uint), - ("max_framesize", c_uint), - ("min_framesize", c_uint), - ("max_framesize", c_uint), - ("sample_rate", c_uint), - ("channels", c_uint), - ("bits_per_sample", c_uint), - ("total_samples", FLAC__uint64), - ("md5sum", FLAC__byte*16)] - - FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN") - - - FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN") - - FLAC__STREAM_METADATA_STREAMINFO_LENGTH =(34) - - - class FLAC__StreamMetadata_Padding(Structure): - _fields_ = [("dummy", c_int)] - - - - class FLAC__StreamMetadata_Application(Structure): - _fields_ = [("id", FLAC__byte*4), - ("data", FLAC__byte_p)] - - FLAC__STREAM_METADATA_APPLICATION_ID_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_APPLICATION_ID_LEN") - - - class FLAC__StreamMetadata_SeekPoint(Structure): - _fields_ = [("sample_number", FLAC__uint64), - ("stream_offset", FLAC__uint64), - ("frame_samples", c_uint)] - - FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN") - - FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN") - - FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN") - - FLAC__STREAM_METADATA_SEEKPOINT_LENGTH =(18) - - - FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__uint64.in_dll(libflac, "FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER") - - class FLAC__StreamMetadata_SeekTable(Structure): - _fields_ = [("num_points", c_uint), - ("points", POINTER(FLAC__StreamMetadata_SeekPoint))] - - class FLAC__StreamMetadata_VorbisComment_Entry(Structure): - _fields_ = [("length", FLAC__uint32), - ("entry", FLAC__byte_p)] - - FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN") - - - class FLAC__StreamMetadata_VorbisComment(Structure): - _fields_ = [("vendor_string", FLAC__StreamMetadata_VorbisComment_Entry), - ("num_comments", FLAC__uint32), - ("comments", POINTER(FLAC__StreamMetadata_VorbisComment_Entry))] - - FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN") - - - class FLAC__StreamMetadata_CueSheet_Index(Structure): - _fields_ = [("offset", FLAC__uint64), - ("number", FLAC__byte)] - - - FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN") - - FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN") - - FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN") - - - class FLAC__StreamMetadata_CueSheet_Track(Structure): - _fields_ = [("offset", FLAC__uint64), - ("number", FLAC__byte), - ("isrc", c_char*13), - ("type", c_uint), - ("pre_emphasis", c_uint), - ("num_indices", FLAC__byte), - ("indices", POINTER(FLAC__StreamMetadata_CueSheet_Index))] - - FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN") - - FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN") - - FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN") - - FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN") - - FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN") - - FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN") - - FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN") - - - class FLAC__StreamMetadata_CueSheet(Structure): - _fields_ = [("media_catalog_number", c_char*129), - ("lead_in", FLAC__uint64), - ("is_cd", FLAC__bool), - ("num_tracks", c_uint), - ("tracks", POINTER(FLAC__StreamMetadata_CueSheet_Track))] - - FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN") - - - FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN") - - FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN") - - FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN") - - FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN") - - - FLAC__StreamMetadata_Picture_Type = c_int - FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0 - FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1 - FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2 - FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3 - FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4 - FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5 - FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6 - FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7 - FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8 - FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9 - FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10 - FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11 - FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12 - FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13 - FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14 - FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15 - FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16 - FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17 - FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18 - FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19 - FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20 - - - libflac.FLAC__StreamMetadata_Picture_TypeString.restype = c_char_p - libflac.FLAC__StreamMetadata_Picture_TypeString.argtypes = [] - - def FLAC__StreamMetadata_Picture_TypeString(): - return libflac.FLAC__StreamMetadata_Picture_TypeString() - - - class FLAC__StreamMetadata_Picture(Structure): - _fields_ = [("type", FLAC__StreamMetadata_Picture_Type), - ("mime_type", c_char_p), - ("description", FLAC__byte_p), - ("width", FLAC__uint32), - ("height", FLAC__uint32), - ("depth", FLAC__uint32), - ("colors", FLAC__uint32), - ("data_length", FLAC__uint32), - ("data", FLAC__byte)] - - FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_TYPE_LEN") - - FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN") - - FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN") - - FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN") - - FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN") - - - FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN") - - FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_COLORS_LEN") - - FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN") - - - class FLAC__StreamMetadata_Unknown(Structure): - _fields_ = [("data", FLAC__byte_p)] - - - class FLAC__StreamMetadata_data(Union): - _fields_ = [("stream_info", FLAC__StreamMetadata_StreamInfo), - ("padding", FLAC__StreamMetadata_Padding), - ("application", FLAC__StreamMetadata_Application), - ("seek_table", FLAC__StreamMetadata_SeekTable), - ("vorbis_comment", FLAC__StreamMetadata_VorbisComment), - ("cue_sheet", FLAC__StreamMetadata_CueSheet), - ("picture", FLAC__StreamMetadata_Picture), - ("unknown", FLAC__StreamMetadata_Unknown)] - - class FLAC__StreamMetadata(Structure): - _fields_ = [("type", FLAC__MetadataType), - ("is_last", FLAC__bool), - ("length", c_uint), - ("data", FLAC__StreamMetadata_data)] - - FLAC__STREAM_METADATA_IS_LAST_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_IS_LAST_LEN") - - FLAC__STREAM_METADATA_TYPE_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_TYPE_LEN") - - FLAC__STREAM_METADATA_LENGTH_LEN = c_uint.in_dll(libflac, "FLAC__STREAM_METADATA_LENGTH_LEN") - - FLAC__STREAM_METADATA_HEADER_LENGTH =(4) - - - - libflac.FLAC__format_sample_rate_is_valid.restype = FLAC__bool - libflac.FLAC__format_sample_rate_is_valid.argtypes = [c_uint] - - def FLAC__format_sample_rate_is_valid(sample_rate): - return libflac.FLAC__format_sample_rate_is_valid(sample_rate) - - - libflac.FLAC__format_blocksize_is_subset.restype = FLAC__bool - libflac.FLAC__format_blocksize_is_subset.argtypes = [c_uint, c_uint] - - def FLAC__format_blocksize_is_subset(blocksize, sample_rate): - return libflac.FLAC__format_blocksize_is_subset(blocksize, sample_rate) - - - libflac.FLAC__format_sample_rate_is_subset.restype = FLAC__bool - libflac.FLAC__format_sample_rate_is_subset.argtypes = [c_uint] - - def FLAC__format_sample_rate_is_subset(sample_rate): - return libflac.FLAC__format_sample_rate_is_subset(sample_rate) - - - libflac.FLAC__format_vorbiscomment_entry_name_is_legal.restype = FLAC__bool - libflac.FLAC__format_vorbiscomment_entry_name_is_legal.argtypes = [c_char_p] - - def FLAC__format_vorbiscomment_entry_name_is_legal(name): - return libflac.FLAC__format_vorbiscomment_entry_name_is_legal(name) - - libflac.FLAC__format_vorbiscomment_entry_value_is_legal.restype = FLAC__bool - libflac.FLAC__format_vorbiscomment_entry_value_is_legal.argtypes = [FLAC__byte_p, c_uint] - - def FLAC__format_vorbiscomment_entry_value_is_legal(value, length): - return libflac.FLAC__format_vorbiscomment_entry_value_is_legal(value, length) - - libflac.FLAC__format_vorbiscomment_entry_is_legal.restype = FLAC__bool - libflac.FLAC__format_vorbiscomment_entry_is_legal.argtypes = [FLAC__byte_p, c_uint] - - def FLAC__format_vorbiscomment_entry_is_legal(entry, length): - return libflac.FLAC__format_vorbiscomment_entry_is_legal(entry, length) - - libflac.FLAC__format_seektable_is_legal.restype = FLAC__bool - libflac.FLAC__format_seektable_is_legal.argtypes = [POINTER(FLAC__StreamMetadata_SeekTable)] - - def FLAC__format_seektable_is_legal(seek_table): - return libflac.FLAC__format_seektable_is_legal(seek_table) - - - libflac.FLAC__format_seektable_sort.restype = FLAC__bool - libflac.FLAC__format_seektable_sort.argtypes = [POINTER(FLAC__StreamMetadata_SeekTable)] - - def FLAC__format_seektable_sort(seek_table): - return libflac.FLAC__format_seektable_sort(seek_table) - - libflac.FLAC__format_cuesheet_is_legal.restype = FLAC__bool - libflac.FLAC__format_cuesheet_is_legal.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet), FLAC__bool, c_char_p_p] - - def FLAC__format_cuesheet_is_legal(cue_sheet, check_cd_da_subset, violation): - return libflac.FLAC__format_cuesheet_is_legal(cue_sheet, check_cd_da_subset, violation) - - # /format - - # metadata - - libflac.FLAC__metadata_get_streaminfo.restype = FLAC__bool - libflac.FLAC__metadata_get_streaminfo.argtypes = [c_char_p, POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_get_streaminfo(filename, streaminfo): - return libflac.FLAC__metadata_get_streaminfo(filename, streaminfo) - - libflac.FLAC__metadata_get_tags.restype = FLAC__bool - libflac.FLAC__metadata_get_tags.argtypes = [c_char_p, POINTER(POINTER(FLAC__StreamMetadata))] - - def FLAC__metadata_get_tags(filename, tags): - return libflac.FLAC__metadata_get_tags(filename, tags) - - libflac.FLAC__metadata_get_cuesheet.restype = FLAC__bool - libflac.FLAC__metadata_get_cuesheet.argtypes = [c_char_p, POINTER(POINTER(FLAC__StreamMetadata))] - - def FLAC__metadata_get_cuesheet(filename, cuesheet): - return libflac.FLAC__metadata_get_cuesheet(filename, cuesheet) - - libflac.FLAC__metadata_get_picture.restype = FLAC__bool - libflac.FLAC__metadata_get_picture.argtypes = [c_char_p, POINTER(POINTER(FLAC__StreamMetadata)), FLAC__StreamMetadata_Picture_Type, c_char_p, FLAC__byte_p, c_uint, c_uint, c_uint, c_uint] - - def FLAC__metadata_get_picture(filename, picture, type, mime_type, description, max_width, max_height, max_depth, max_colors): - return libflac.FLAC__metadata_get_picture(filename, picture, type, mime_type, description, max_width, max_height, max_depth, max_colors) - - - class FLAC__Metadata_SimpleIterator(Structure): - _fields_ = [("dummy", c_int)] - - FLAC__Metadata_SimpleIteratorStatus = c_int - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0 - - - libflac.FLAC__Metadata_SimpleIteratorStatusString.restype = c_char_p - libflac.FLAC__Metadata_SimpleIteratorStatusString.argtypes = [] - - def FLAC__Metadata_SimpleIteratorStatusString(): - return libflac.FLAC__Metadata_SimpleIteratorStatusString() - - - libflac.FLAC__metadata_simple_iterator_new.restype = POINTER(FLAC__Metadata_SimpleIterator) - libflac.FLAC__metadata_simple_iterator_new.argtypes = [] - - def FLAC__metadata_simple_iterator_new(): - return libflac.FLAC__metadata_simple_iterator_new() - - - libflac.FLAC__metadata_simple_iterator_delete.restype = None - libflac.FLAC__metadata_simple_iterator_delete.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_delete(iterator): - return libflac.FLAC__metadata_simple_iterator_delete(iterator) - - - libflac.FLAC__metadata_simple_iterator_status.restype = FLAC__Metadata_SimpleIteratorStatus - libflac.FLAC__metadata_simple_iterator_status.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_status(iterator): - return libflac.FLAC__metadata_simple_iterator_status(iterator) - - libflac.FLAC__metadata_simple_iterator_init.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_init.argtypes = [POINTER(FLAC__Metadata_SimpleIterator), c_char_p, FLAC__bool, FLAC__bool] - - def FLAC__metadata_simple_iterator_init(iterator, filename, read_only, preserve_file_stats): - return libflac.FLAC__metadata_simple_iterator_init(iterator, filename, read_only, preserve_file_stats) - - libflac.FLAC__metadata_simple_iterator_is_writable.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_is_writable.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_is_writable(iterator): - return libflac.FLAC__metadata_simple_iterator_is_writable(iterator) - - libflac.FLAC__metadata_simple_iterator_next.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_next.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_next(iterator): - return libflac.FLAC__metadata_simple_iterator_next(iterator) - - libflac.FLAC__metadata_simple_iterator_prev.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_prev.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_prev(iterator): - return libflac.FLAC__metadata_simple_iterator_prev(iterator) - - libflac.FLAC__metadata_simple_iterator_is_last.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_is_last.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_is_last(iterator): - return libflac.FLAC__metadata_simple_iterator_is_last(iterator) - - libflac.FLAC__metadata_simple_iterator_get_block_offset.restype = c_off_t - libflac.FLAC__metadata_simple_iterator_get_block_offset.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_get_block_offset(iterator): - return libflac.FLAC__metadata_simple_iterator_get_block_offset(iterator) - - libflac.FLAC__metadata_simple_iterator_get_block_type.restype = FLAC__MetadataType - libflac.FLAC__metadata_simple_iterator_get_block_type.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_get_block_type(iterator): - return libflac.FLAC__metadata_simple_iterator_get_block_type(iterator) - - libflac.FLAC__metadata_simple_iterator_get_block_length.restype = c_uint - libflac.FLAC__metadata_simple_iterator_get_block_length.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_get_block_length(iterator): - return libflac.FLAC__metadata_simple_iterator_get_block_length(iterator) - - libflac.FLAC__metadata_simple_iterator_get_application_id.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_get_application_id.argtypes = [POINTER(FLAC__Metadata_SimpleIterator), FLAC__byte_p] - - def FLAC__metadata_simple_iterator_get_application_id(iterator, id): - return libflac.FLAC__metadata_simple_iterator_get_application_id(iterator, id) - - libflac.FLAC__metadata_simple_iterator_get_block.restype = POINTER(FLAC__StreamMetadata) - libflac.FLAC__metadata_simple_iterator_get_block.argtypes = [POINTER(FLAC__Metadata_SimpleIterator)] - - def FLAC__metadata_simple_iterator_get_block(iterator): - return libflac.FLAC__metadata_simple_iterator_get_block(iterator) - - libflac.FLAC__metadata_simple_iterator_set_block.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_set_block.argtypes = [POINTER(FLAC__Metadata_SimpleIterator), POINTER(FLAC__StreamMetadata), FLAC__bool] - - def FLAC__metadata_simple_iterator_set_block(iterator, block, use_padding): - return libflac.FLAC__metadata_simple_iterator_set_block(iterator, block, use_padding) - - libflac.FLAC__metadata_simple_iterator_insert_block_after.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_insert_block_after.argtypes = [POINTER(FLAC__Metadata_SimpleIterator), POINTER(FLAC__StreamMetadata), FLAC__bool] - - def FLAC__metadata_simple_iterator_insert_block_after(iterator, block, use_padding): - return libflac.FLAC__metadata_simple_iterator_insert_block_after(iterator, block, use_padding) - - libflac.FLAC__metadata_simple_iterator_delete_block.restype = FLAC__bool - libflac.FLAC__metadata_simple_iterator_delete_block.argtypes = [POINTER(FLAC__Metadata_SimpleIterator), FLAC__bool] - - def FLAC__metadata_simple_iterator_delete_block(iterator, use_padding): - return libflac.FLAC__metadata_simple_iterator_delete_block(iterator, use_padding) - - class FLAC__Metadata_Chain(Structure): - _fields_ = [("dummy", c_int)] - - class FLAC__Metadata_Iterator(Structure): - _fields_ = [("dummy", c_int)] - - FLAC__Metadata_ChainStatus = c_int - - FLAC__METADATA_CHAIN_STATUS_OK = 0 - - libflac.FLAC__Metadata_ChainStatusString.restype = c_char_p - libflac.FLAC__Metadata_ChainStatusString.argtypes = [] - - def FLAC__Metadata_ChainStatusString(): - return libflac.FLAC__Metadata_ChainStatusString() - - libflac.FLAC__metadata_chain_new.restype = POINTER(FLAC__Metadata_Chain) - libflac.FLAC__metadata_chain_new.argtypes = [] - - def FLAC__metadata_chain_new(): - return libflac.FLAC__metadata_chain_new() - - libflac.FLAC__metadata_chain_delete.restype = None - libflac.FLAC__metadata_chain_delete.argtypes = [POINTER(FLAC__Metadata_Chain)] - - def FLAC__metadata_chain_delete(chain): - return libflac.FLAC__metadata_chain_delete(chain) - - libflac.FLAC__metadata_chain_status.restype = FLAC__Metadata_ChainStatus - libflac.FLAC__metadata_chain_status.argtypes = [POINTER(FLAC__Metadata_Chain)] - - def FLAC__metadata_chain_status(chain): - return libflac.FLAC__metadata_chain_status(chain) - - libflac.FLAC__metadata_chain_read.restype = FLAC__bool - libflac.FLAC__metadata_chain_read.argtypes = [POINTER(FLAC__Metadata_Chain), c_char_p] - - def FLAC__metadata_chain_read(chain, filename): - return libflac.FLAC__metadata_chain_read(chain, filename) - - libflac.FLAC__metadata_chain_read_ogg.restype = FLAC__bool - libflac.FLAC__metadata_chain_read_ogg.argtypes = [POINTER(FLAC__Metadata_Chain), c_char_p] - - def FLAC__metadata_chain_read_ogg(chain, filename): - return libflac.FLAC__metadata_chain_read_ogg(chain, filename) - - libflac.FLAC__metadata_chain_read_with_callbacks.restype = FLAC__bool - libflac.FLAC__metadata_chain_read_with_callbacks.argtypes = [POINTER(FLAC__Metadata_Chain), FLAC__IOHandle, FLAC__IOCallbacks] - - def FLAC__metadata_chain_read_with_callbacks(chain, handle, callbacks): - return libflac.FLAC__metadata_chain_read_with_callbacks(chain, handle, callbacks) - - libflac.FLAC__metadata_chain_read_ogg_with_callbacks.restype = FLAC__bool - libflac.FLAC__metadata_chain_read_ogg_with_callbacks.argtypes = [POINTER(FLAC__Metadata_Chain), FLAC__IOHandle, FLAC__IOCallbacks] - - def FLAC__metadata_chain_read_ogg_with_callbacks(chain, handle, callbacks): - return libflac.FLAC__metadata_chain_read_ogg_with_callbacks(chain, handle, callbacks) - - libflac.FLAC__metadata_chain_check_if_tempfile_needed.restype = FLAC__bool - libflac.FLAC__metadata_chain_check_if_tempfile_needed.argtypes = [POINTER(FLAC__Metadata_Chain), FLAC__bool] - - def FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding): - return libflac.FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding) - - libflac.FLAC__metadata_chain_write.restype = FLAC__bool - libflac.FLAC__metadata_chain_write.argtypes = [POINTER(FLAC__Metadata_Chain), FLAC__bool, FLAC__bool] - - def FLAC__metadata_chain_write(chain, use_padding, preserve_file_stats): - return libflac.FLAC__metadata_chain_write(chain, use_padding, preserve_file_stats) - - libflac.FLAC__metadata_chain_write_with_callbacks.restype = FLAC__bool - libflac.FLAC__metadata_chain_write_with_callbacks.argtypes = [POINTER(FLAC__Metadata_Chain), FLAC__bool, FLAC__IOHandle, FLAC__IOCallbacks] - - def FLAC__metadata_chain_write_with_callbacks(chain, use_padding, handle, callbacks): - return libflac.FLAC__metadata_chain_write_with_callbacks(chain, use_padding, handle, callbacks) - - libflac.FLAC__metadata_chain_write_with_callbacks_and_tempfile.restype = FLAC__bool - libflac.FLAC__metadata_chain_write_with_callbacks_and_tempfile.argtypes = [POINTER(FLAC__Metadata_Chain), FLAC__bool, FLAC__IOHandle, FLAC__IOCallbacks, FLAC__IOHandle, FLAC__IOCallbacks] - - def FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain, use_padding, handle, callbacks, temp_handle, temp_callbacks): - return libflac.FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain, use_padding, handle, callbacks, temp_handle, temp_callbacks) - - libflac.FLAC__metadata_chain_merge_padding.restype = None - libflac.FLAC__metadata_chain_merge_padding.argtypes = [POINTER(FLAC__Metadata_Chain)] - - def FLAC__metadata_chain_merge_padding(chain): - return libflac.FLAC__metadata_chain_merge_padding(chain) - - libflac.FLAC__metadata_chain_sort_padding.restype = None - libflac.FLAC__metadata_chain_sort_padding.argtypes = [POINTER(FLAC__Metadata_Chain)] - - def FLAC__metadata_chain_sort_padding(chain): - return libflac.FLAC__metadata_chain_sort_padding(chain) - - libflac.FLAC__metadata_iterator_new.restype = POINTER(FLAC__Metadata_Iterator) - libflac.FLAC__metadata_iterator_new.argtypes = [] - - def FLAC__metadata_iterator_new(): - return libflac.FLAC__metadata_iterator_new() - - libflac.FLAC__metadata_iterator_delete.restype = None - libflac.FLAC__metadata_iterator_delete.argtypes = [POINTER(FLAC__Metadata_Iterator)] - - def FLAC__metadata_iterator_delete(iterator): - return libflac.FLAC__metadata_iterator_delete(iterator) - - libflac.FLAC__metadata_iterator_init.restype = None - libflac.FLAC__metadata_iterator_init.argtypes = [POINTER(FLAC__Metadata_Iterator), POINTER(FLAC__Metadata_Chain)] - - def FLAC__metadata_iterator_init(iterator, chain): - return libflac.FLAC__metadata_iterator_init(iterator, chain) - - libflac.FLAC__metadata_iterator_next.restype = FLAC__bool - libflac.FLAC__metadata_iterator_next.argtypes = [POINTER(FLAC__Metadata_Iterator)] - - def FLAC__metadata_iterator_next(iterator): - return libflac.FLAC__metadata_iterator_next(iterator) - - libflac.FLAC__metadata_iterator_prev.restype = FLAC__bool - libflac.FLAC__metadata_iterator_prev.argtypes = [POINTER(FLAC__Metadata_Iterator)] - - def FLAC__metadata_iterator_prev(iterator): - return libflac.FLAC__metadata_iterator_prev(iterator) - - libflac.FLAC__metadata_iterator_get_block_type.restype = FLAC__MetadataType - libflac.FLAC__metadata_iterator_get_block_type.argtypes = [POINTER(FLAC__Metadata_Iterator)] - - def FLAC__metadata_iterator_get_block_type(iterator): - return libflac.FLAC__metadata_iterator_get_block_type(iterator) - - libflac.FLAC__metadata_iterator_get_block_type.restype = POINTER(FLAC__StreamMetadata) - libflac.FLAC__metadata_iterator_get_block_type.argtypes = [POINTER(FLAC__Metadata_Iterator)] - - def FLAC__metadata_iterator_get_block_type(iterator): - return libflac.FLAC__metadata_iterator_get_block_type(iterator) - - libflac.FLAC__metadata_iterator_set_block.restype = FLAC__bool - libflac.FLAC__metadata_iterator_set_block.argtypes = [POINTER(FLAC__Metadata_Iterator), POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_iterator_set_block(iterator, block): - return libflac.FLAC__metadata_iterator_set_block(iterator, block) - - libflac.FLAC__metadata_iterator_delete_block.restype = FLAC__bool - libflac.FLAC__metadata_iterator_delete_block.argtypes = [POINTER(FLAC__Metadata_Iterator), FLAC__bool] - - def FLAC__metadata_iterator_delete_block(iterator, replace_with_padding): - return libflac.FLAC__metadata_iterator_delete_block(iterator, replace_with_padding) - - libflac.FLAC__metadata_iterator_insert_block_before.restype = FLAC__bool - libflac.FLAC__metadata_iterator_insert_block_before.argtypes = [POINTER(FLAC__Metadata_Iterator), POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_iterator_insert_block_before(iterator, block): - return libflac.FLAC__metadata_iterator_insert_block_before(iterator, block) - - libflac.FLAC__metadata_iterator_insert_block_after.restype = FLAC__bool - libflac.FLAC__metadata_iterator_insert_block_after.argtypes = [POINTER(FLAC__Metadata_Iterator), POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_iterator_insert_block_after(iterator, block): - return libflac.FLAC__metadata_iterator_insert_block_after(iterator, block) - - libflac.FLAC__metadata_object_new.restype = POINTER(FLAC__StreamMetadata) - libflac.FLAC__metadata_object_new.argtypes = [POINTER(FLAC__MetadataType)] - - def FLAC__metadata_object_new(type): - return libflac.FLAC__metadata_object_new(type) - - libflac.FLAC__metadata_object_clone.restype = POINTER(FLAC__StreamMetadata) - libflac.FLAC__metadata_object_clone.argtypes = [POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_object_clone(object): - return libflac.FLAC__metadata_object_clone(object) - - libflac.FLAC__metadata_object_delete.restype = None - libflac.FLAC__metadata_object_delete.argtypes = [POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_object_delete(object): - return libflac.FLAC__metadata_object_delete(object) - - libflac.FLAC__metadata_object_is_equal.restype = FLAC__bool - libflac.FLAC__metadata_object_is_equal.argtypes = [POINTER(FLAC__StreamMetadata), POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_object_is_equal(block1, block2): - return libflac.FLAC__metadata_object_is_equal(block1, block2) - - libflac.FLAC__metadata_object_application_set_data.restype = FLAC__bool - libflac.FLAC__metadata_object_application_set_data.argtypes = [POINTER(FLAC__StreamMetadata), FLAC__byte_p, c_uint, FLAC__bool] - - def FLAC__metadata_object_application_set_data(object, data, length, copy): - return libflac.FLAC__metadata_object_application_set_data(object, data, length, copy) - - libflac.FLAC__metadata_object_seektable_resize_points.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_resize_points.argtypes = [POINTER(FLAC__StreamMetadata),c_uint] - - def FLAC__metadata_object_seektable_resize_points(object, new_num_points): - return libflac.FLAC__metadata_object_seektable_resize_points(object, new_num_points) - - libflac.FLAC__metadata_object_seektable_set_point.restype = None - libflac.FLAC__metadata_object_seektable_set_point.argtypes = [POINTER(FLAC__StreamMetadata),c_uint, FLAC__StreamMetadata_SeekPoint] - - def FLAC__metadata_object_seektable_set_point(object, point_num, point): - return libflac.FLAC__metadata_object_seektable_set_point(object, point_num, point) - - libflac.FLAC__metadata_object_seektable_insert_point.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_insert_point.argtypes = [POINTER(FLAC__StreamMetadata),c_uint, FLAC__StreamMetadata_SeekPoint] - - def FLAC__metadata_object_seektable_insert_point(object, point_num, point): - return libflac.FLAC__metadata_object_seektable_insert_point(object, point_num, point) - - libflac.FLAC__metadata_object_seektable_delete_point.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_delete_point.argtypes = [POINTER(FLAC__StreamMetadata),c_uint] - - def FLAC__metadata_object_seektable_delete_point(object, point_num): - return libflac.FLAC__metadata_object_seektable_delete_point(object, point_num) - - libflac.FLAC__metadata_object_seektable_is_legal.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_is_legal.argtypes = [POINTER(FLAC__StreamMetadata)] - - def FLAC__metadata_object_seektable_is_legal(object): - return libflac.FLAC__metadata_object_seektable_is_legal(object) - - libflac.FLAC__metadata_object_seektable_template_append_placeholders.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_template_append_placeholders.argtypes = [POINTER(FLAC__StreamMetadata), c_uint] - - def FLAC__metadata_object_seektable_template_append_placeholders(object, num): - return libflac.FLAC__metadata_object_seektable_template_append_placeholders(object, num) - - libflac.FLAC__metadata_object_seektable_template_append_point.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_template_append_point.argtypes = [POINTER(FLAC__StreamMetadata), FLAC__uint64] - - def FLAC__metadata_object_seektable_template_append_point(object, sample_number): - return libflac.FLAC__metadata_object_seektable_template_append_point(object, sample_number) - - libflac.FLAC__metadata_object_seektable_template_append_points.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_template_append_points.argtypes = [POINTER(FLAC__StreamMetadata), POINTER(FLAC__uint64*0), c_uint] - - def FLAC__metadata_object_seektable_template_append_points(object, sample_numbers, num): - return libflac.FLAC__metadata_object_seektable_template_append_points(object, sample_numbers, num) - - libflac.FLAC__metadata_object_seektable_template_append_spaced_points.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_template_append_spaced_points.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, FLAC__uint64] - - def FLAC__metadata_object_seektable_template_append_spaced_points(object, num, total_samples): - return libflac.FLAC__metadata_object_seektable_template_append_spaced_points(object, num, total_samples) - - libflac.FLAC__metadata_object_seektable_template_append_spaced_points_by_samples.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_template_append_spaced_points_by_samples.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, FLAC__uint64] - - def FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(object, samples, total_samples): - return libflac.FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(object, samples, total_samples) - - libflac.FLAC__metadata_object_seektable_template_sort.restype = FLAC__bool - libflac.FLAC__metadata_object_seektable_template_sort.argtypes = [POINTER(FLAC__StreamMetadata), FLAC__bool] - - def FLAC__metadata_object_seektable_template_sort(object, compact): - return libflac.FLAC__metadata_object_seektable_template_sort(object, compact) - - libflac.FLAC__metadata_object_vorbiscomment_set_vendor_string.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_set_vendor_string.argtypes = [POINTER(FLAC__StreamMetadata), FLAC__StreamMetadata_VorbisComment_Entry, FLAC__bool] - - def FLAC__metadata_object_vorbiscomment_set_vendor_string(object, entry, copy): - return libflac.FLAC__metadata_object_vorbiscomment_set_vendor_string(object, entry, copy) - - libflac.FLAC__metadata_object_vorbiscomment_resize_comments.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_resize_comments.argtypes = [POINTER(FLAC__StreamMetadata), c_uint] - - def FLAC__metadata_object_vorbiscomment_resize_comments(object, new_num_comments): - return libflac.FLAC__metadata_object_vorbiscomment_resize_comments(object, new_num_comments) - - libflac.FLAC__metadata_object_vorbiscomment_set_comment.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_set_comment.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, FLAC__StreamMetadata_VorbisComment_Entry, FLAC__bool] - - def FLAC__metadata_object_vorbiscomment_set_comment(object, comment_num, entry, copy): - return libflac.FLAC__metadata_object_vorbiscomment_set_comment(object, comment_num, entry, copy) - - libflac.FLAC__metadata_object_vorbiscomment_insert_comment.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_insert_comment.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, FLAC__StreamMetadata_VorbisComment_Entry, FLAC__bool] - - def FLAC__metadata_object_vorbiscomment_insert_comment(object, comment_num, entry, copy): - return libflac.FLAC__metadata_object_vorbiscomment_insert_comment(object, comment_num, entry, copy) - - libflac.FLAC__metadata_object_vorbiscomment_append_comment.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_append_comment.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, FLAC__StreamMetadata_VorbisComment_Entry, FLAC__bool] - - def FLAC__metadata_object_vorbiscomment_append_comment(object, entry, copy): - return libflac.FLAC__metadata_object_vorbiscomment_append_comment(object,entry, copy) - - libflac.FLAC__metadata_object_vorbiscomment_replace_comment.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_replace_comment.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, FLAC__StreamMetadata_VorbisComment_Entry, FLAC__bool, FLAC__bool] - - def FLAC__metadata_object_vorbiscomment_replace_comment(object, entry, all, copy): - return libflac.FLAC__metadata_object_vorbiscomment_replace_comment(object,entry, all, copy) - - libflac.FLAC__metadata_object_vorbiscomment_delete_comment.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_delete_comment.argtypes = [POINTER(FLAC__StreamMetadata), c_uint] - - def FLAC__metadata_object_vorbiscomment_delete_comment(object, comment_num): - return libflac.FLAC__metadata_object_vorbiscomment_delete_comment(object,comment_num) - - libflac.FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair.argtypes = [POINTER(FLAC__StreamMetadata_VorbisComment_Entry), c_char_p, c_char_p] - - def FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(entry, field_name, field_value): - return libflac.FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(entry, field_name, field_value) - - libflac.FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair.argtypes = [POINTER(FLAC__StreamMetadata_VorbisComment_Entry), c_char_p_p, c_char_p_p] - - def FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(entry, field_name, field_value): - return libflac.FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(entry, field_name, field_value) - - libflac.FLAC__metadata_object_vorbiscomment_entry_matches.restype = FLAC__bool - libflac.FLAC__metadata_object_vorbiscomment_entry_matches.argtypes = [POINTER(FLAC__StreamMetadata_VorbisComment_Entry), c_char_p, c_uint] - - def FLAC__metadata_object_vorbiscomment_entry_matches(entry, field_name, field_value): - return libflac.FLAC__metadata_object_vorbiscomment_entry_matches(entry, field_name, field_value) - - libflac.FLAC__metadata_object_vorbiscomment_find_entry_from.restype = c_int - libflac.FLAC__metadata_object_vorbiscomment_find_entry_from.argtypes = [POINTER(FLAC__StreamMetadata), c_uint, c_char_p] - - def FLAC__metadata_object_vorbiscomment_find_entry_from(object, offset, field_name): - return libflac.FLAC__metadata_object_vorbiscomment_find_entry_from(object, offset, field_name) - - libflac.FLAC__metadata_object_vorbiscomment_remove_entry_matching.restype = c_int - libflac.FLAC__metadata_object_vorbiscomment_remove_entry_matching.argtypes = [POINTER(FLAC__StreamMetadata), c_char_p] - - def FLAC__metadata_object_vorbiscomment_remove_entry_matching(object, field_name): - return libflac.FLAC__metadata_object_vorbiscomment_remove_entry_matching(object, field_name) - - libflac.FLAC__metadata_object_vorbiscomment_remove_entries_matching.restype = c_int - libflac.FLAC__metadata_object_vorbiscomment_remove_entries_matching.argtypes = [POINTER(FLAC__StreamMetadata), c_char_p] - - def FLAC__metadata_object_vorbiscomment_remove_entries_matching(object, field_name): - return libflac.FLAC__metadata_object_vorbiscomment_remove_entries_matching(object, field_name) - - libflac.FLAC__metadata_object_cuesheet_track_new.restype = POINTER(FLAC__StreamMetadata_CueSheet_Track) - libflac.FLAC__metadata_object_cuesheet_track_new.argtypes = [] - - def FLAC__metadata_object_cuesheet_track_new(): - return libflac.FLAC__metadata_object_cuesheet_track_new() - - libflac.FLAC__metadata_object_cuesheet_track_delete.restype = None - libflac.FLAC__metadata_object_cuesheet_track_delete.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track)] - - def FLAC__metadata_object_cuesheet_track_delete(object): - return libflac.FLAC__metadata_object_cuesheet_track_delete(object) - - libflac.FLAC__metadata_object_cuesheet_track_resize_indices.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_track_resize_indices.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint, c_uint] - - def FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, new_num_indices): - return libflac.FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, new_num_indices) - - libflac.FLAC__metadata_object_cuesheet_track_insert_index.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_track_insert_index.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint, c_uint, FLAC__StreamMetadata_CueSheet_Index] - - def FLAC__metadata_object_cuesheet_track_insert_index(object, track_num, index_num, index): - return libflac.FLAC__metadata_object_cuesheet_track_insert_index(object, track_num, index_num, index) - - libflac.FLAC__metadata_object_cuesheet_track_insert_blank_index.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_track_insert_blank_index.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint, c_uint] - - def FLAC__metadata_object_cuesheet_track_insert_blank_index(object, track_num, index_num): - return libflac.FLAC__metadata_object_cuesheet_track_insert_blank_index(object, track_num, index_num) - - libflac.FLAC__metadata_object_cuesheet_track_delete_index.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_track_delete_index.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint, c_uint] - - def FLAC__metadata_object_cuesheet_track_delete_index(object, track_num, index_num): - return libflac.FLAC__metadata_object_cuesheet_track_delete_index(object, track_num, index_num) - - libflac.FLAC__metadata_object_cuesheet_resize_tracks.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_resize_tracks.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint] - - def FLAC__metadata_object_cuesheet_resize_tracks(object, new_num_tracks): - return libflac.FLAC__metadata_object_cuesheet_resize_tracks(object, new_num_tracks) - - libflac.FLAC__metadata_object_cuesheet_set_track.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_set_track.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint, POINTER(FLAC__StreamMetadata_CueSheet_Track), FLAC__bool] - - def FLAC__metadata_object_cuesheet_set_track(object, new_num_tracks, track, copy): - return libflac.FLAC__metadata_object_cuesheet_set_track(object, new_num_tracks, track, copy) - - libflac.FLAC__metadata_object_cuesheet_insert_track.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_insert_track.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint, POINTER(FLAC__StreamMetadata_CueSheet_Track), FLAC__bool] - - def FLAC__metadata_object_cuesheet_insert_track(object, track_num, track, copy): - return libflac.FLAC__metadata_object_cuesheet_insert_track(object, track_num, track, copy) - - libflac.FLAC__metadata_object_cuesheet_insert_blank_track.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_insert_blank_track.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint] - - def FLAC__metadata_object_cuesheet_insert_blank_track(object, track_num): - return libflac.FLAC__metadata_object_cuesheet_insert_blank_track(object, track_num) - - libflac.FLAC__metadata_object_cuesheet_delete_track.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_delete_track.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_uint] - - def FLAC__metadata_object_cuesheet_delete_track(object, track_num): - return libflac.FLAC__metadata_object_cuesheet_delete_track(object, track_num) - - libflac.FLAC__metadata_object_cuesheet_is_legal.restype = FLAC__bool - libflac.FLAC__metadata_object_cuesheet_is_legal.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), FLAC__bool, c_char_p_p] - - def FLAC__metadata_object_cuesheet_is_legal(object, check_cd_da_subset, violation): - return libflac.FLAC__metadata_object_cuesheet_is_legal(object, check_cd_da_subset, violation) - - libflac.FLAC__metadata_object_cuesheet_calculate_cddb_id.restype = FLAC__uint32 - libflac.FLAC__metadata_object_cuesheet_calculate_cddb_id.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track)] - - def FLAC__metadata_object_cuesheet_calculate_cddb_id(object): - return libflac.FLAC__metadata_object_cuesheet_calculate_cddb_id(object) - - libflac.FLAC__metadata_object_picture_set_mime_type.restype = FLAC__bool - libflac.FLAC__metadata_object_picture_set_mime_type.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_char_p, FLAC__bool] - - def FLAC__metadata_object_picture_set_mime_type(object, mime_type, copy): - return libflac.FLAC__metadata_object_picture_set_mime_type(object, mime_type, copy) - - libflac.FLAC__metadata_object_picture_set_description.restype = FLAC__bool - libflac.FLAC__metadata_object_picture_set_description.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), FLAC__byte_p, FLAC__bool] - - def FLAC__metadata_object_picture_set_description(object, description, copy): - return libflac.FLAC__metadata_object_picture_set_description(object, mime_type, copy) - - libflac.FLAC__metadata_object_picture_set_data.restype = FLAC__bool - libflac.FLAC__metadata_object_picture_set_data.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), FLAC__byte_p,FLAC__uint32, FLAC__bool] - - def FLAC__metadata_object_picture_set_data(object, data, length, copy): - return libflac.FLAC__metadata_object_picture_set_data(object, mime_type, copy) - - libflac.FLAC__metadata_object_picture_is_legal.restype = FLAC__bool - libflac.FLAC__metadata_object_picture_is_legal.argtypes = [POINTER(FLAC__StreamMetadata_CueSheet_Track), c_char_p] - - def FLAC__metadata_object_picture_is_legal(object, violation): - return libflac.FLAC__metadata_object_picture_is_legal(object, violation) - - # /metadata - - # stream_decoder - - FLAC__StreamDecoderState = c_int - FLAC__StreamDecoderStateEnum = ["FLAC__STREAM_DECODER_SEARCH_FOR_METADATA", - "FLAC__STREAM_DECODER_READ_METADATA", - "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC", - "FLAC__STREAM_DECODER_READ_FRAME", - "FLAC__STREAM_DECODER_END_OF_STREAM", - "FLAC__STREAM_DECODER_OGG_ERROR", - "FLAC__STREAM_DECODER_SEEK_ERROR", - "FLAC__STREAM_DECODER_ABORTED", - "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR", - "FLAC__STREAM_DECODER_UNINITIALIZED"] - - libflac.FLAC__StreamDecoderStateString.restype = c_char_p - libflac.FLAC__StreamDecoderStateString.argtypes = [] - - def FLAC__StreamDecoderStateString(): - return libflac.FLAC__StreamDecoderStateString() - - - FLAC__StreamDecoderInitStatus = c_int - FLAC__StreamDecoderInitStatusEnum = ["FLAC__STREAM_DECODER_INIT_STATUS_OK", - "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER", - "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS", - "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR", - "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE", - "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"] - - libflac.FLAC__StreamDecoderInitStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderInitStatusString.argtypes = [] - - def FLAC__StreamDecoderInitStatusString(): - return libflac.FLAC__StreamDecoderInitStatusString() - - - FLAC__StreamDecoderReadStatus = c_int - FLAC__StreamDecoderReadStatusEnum = ["FLAC__STREAM_DECODER_READ_STATUS_CONTINUE", - "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM", - "FLAC__STREAM_DECODER_READ_STATUS_ABORT"] - - libflac.FLAC__StreamDecoderReadStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderReadStatusString.argtypes = [] - - def FLAC__StreamDecoderReadStatusString(): - return libflac.FLAC__StreamDecoderReadStatusString() - - - FLAC__StreamDecoderSeekStatus = c_int - FLAC__StreamDecoderSeekStatusEnum = ["FLAC__STREAM_DECODER_SEEK_STATUS_OK", - "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR", - "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"] - - libflac.FLAC__StreamDecoderSeekStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderSeekStatusString.argtypes = [] - - def FLAC__StreamDecoderSeekStatusString(): - return libflac.FLAC__StreamDecoderSeekStatusString() - - - FLAC__StreamDecoderTellStatus = c_int - FLAC__StreamDecoderTellStatusEnum = ["FLAC__STREAM_DECODER_TELL_STATUS_OK", - "FLAC__STREAM_DECODER_TELL_STATUS_ERROR", - "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"] - - libflac.FLAC__StreamDecoderTellStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderTellStatusString.argtypes = [] - - def FLAC__StreamDecoderTellStatusString(): - return libflac.FLAC__StreamDecoderTellStatusString() - - - FLAC__StreamDecoderLengthStatus = c_int - FLAC__StreamDecoderLengthStatusEnum = ["FLAC__STREAM_DECODER_LENGTH_STATUS_OK", - "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR", - "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"] - - libflac.FLAC__StreamDecoderLengthStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderLengthStatusString.argtypes = [] - - def FLAC__StreamDecoderLengthStatusString(): - return libflac.FLAC__StreamDecoderLengthStatusString() - - - FLAC__StreamDecoderWriteStatus = c_int - FLAC__StreamDecoderWriteStatusEnum = ["FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE", "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"] - - libflac.FLAC__StreamDecoderWriteStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderWriteStatusString.argtypes = [] - - def FLAC__StreamDecoderWriteStatusString(): - return libflac.FLAC__StreamDecoderWriteStatusString() - - FLAC__StreamDecoderErrorStatus = c_int - FLAC__StreamDecoderErrorStatusEnum = ["FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC", - "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER", - "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH", - "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"] - - libflac.FLAC__StreamDecoderErrorStatusString.restype = c_char_p - libflac.FLAC__StreamDecoderErrorStatusString.argtypes = [] - - def FLAC__StreamDecoderErrorStatusString(): - return libflac.FLAC__StreamDecoderErrorStatusString() - - - - class FLAC__StreamDecoderProtected(Structure): - _fields_ = [("dummy", c_int)] - - class FLAC__StreamDecoderPrivate(Structure): - _fields_ = [("dummy", c_int)] - - class FLAC__StreamDecoder(Structure): - _fields_ = [("protected_", POINTER(FLAC__StreamDecoderProtected)), - ("private_", POINTER(FLAC__StreamDecoderPrivate))] - - FLAC__StreamDecoderReadCallback = CFUNCTYPE( - FLAC__StreamDecoderReadStatus, - POINTER(FLAC__StreamDecoder), - POINTER(FLAC__byte*0), - c_size_t_p, - c_void_p - ) - - FLAC__StreamDecoderSeekCallback = CFUNCTYPE( - FLAC__StreamDecoderSeekStatus, - POINTER(FLAC__StreamDecoder), - FLAC__uint64, - c_void_p - ) - - FLAC__StreamDecoderTellCallback = CFUNCTYPE( - FLAC__StreamDecoderTellStatus, - POINTER(FLAC__StreamDecoder), - FLAC__uint64_p, - c_void_p - ) - - FLAC__StreamDecoderLengthCallback = CFUNCTYPE( - FLAC__StreamDecoderLengthStatus, - POINTER(FLAC__StreamDecoder), - FLAC__uint64_p, - c_void_p - ) - - FLAC__StreamDecoderEofCallback = CFUNCTYPE( - FLAC__bool, - POINTER(FLAC__StreamDecoder), - c_void_p - ) - - FLAC__StreamDecoderWriteCallback = CFUNCTYPE( - FLAC__StreamDecoderWriteStatus, - POINTER(FLAC__StreamDecoder), - POINTER(FLAC__Frame), - POINTER(FLAC__int32_p*0), - c_void_p - ) - - FLAC__StreamDecoderMetadataCallback = CFUNCTYPE( - None, - POINTER(FLAC__StreamDecoder), - POINTER(FLAC__StreamMetadata), - c_void_p - ) - - FLAC__StreamDecoderErrorCallback = CFUNCTYPE( - None, - POINTER(FLAC__StreamDecoder), - FLAC__StreamDecoderErrorStatus, - c_void_p - ) - - - libflac.FLAC__stream_decoder_new.restype = POINTER(FLAC__StreamDecoder) - libflac.FLAC__stream_decoder_new.argtypes = [] - - def FLAC__stream_decoder_new(): - return libflac.FLAC__stream_decoder_new() - - libflac.FLAC__stream_decoder_delete.restype = None - libflac.FLAC__stream_decoder_delete.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_delete(decoder): - return libflac.FLAC__stream_decoder_delete(decoder) - - - libflac.FLAC__stream_decoder_set_ogg_serial_number.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_ogg_serial_number.argtypes = [POINTER(FLAC__StreamDecoder), c_long] - - def FLAC__stream_decoder_set_ogg_serial_number(decoder, serial_number): - return libflac.FLAC__stream_decoder_set_ogg_serial_number(decoder, serial_number) - - libflac.FLAC__stream_decoder_set_md5_checking.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_md5_checking.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__bool] - - def FLAC__stream_decoder_set_md5_checking(decoder, value): - return libflac.FLAC__stream_decoder_set_md5_checking(decoder, value) - - libflac.FLAC__stream_decoder_set_metadata_respond.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_metadata_respond.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__MetadataType] - - def FLAC__stream_decoder_set_metadata_respond(decoder, type): - return libflac.FLAC__stream_decoder_set_metadata_respond(decoder, type) - - libflac.FLAC__stream_decoder_set_metadata_respond_application.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_metadata_respond_application.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__byte*4] - - def FLAC__stream_decoder_set_metadata_respond_application(decoder, id): - return libflac.FLAC__stream_decoder_set_metadata_respond_application(decoder, id) - - libflac.FLAC__stream_decoder_set_metadata_respond_all.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_metadata_respond_all.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_set_metadata_respond_all(decoder): - return libflac.FLAC__stream_decoder_set_metadata_respond_all(decoder) - - libflac.FLAC__stream_decoder_set_metadata_ignore.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_metadata_ignore.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__MetadataType] - - def FLAC__stream_decoder_set_metadata_ignore(decoder, type): - return libflac.FLAC__stream_decoder_set_metadata_ignore(decoder, type) - - libflac.FLAC__stream_decoder_set_metadata_ignore_application.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_metadata_ignore_application.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__byte*4] - - def FLAC__stream_decoder_set_metadata_ignore_application(decoder, id): - return libflac.FLAC__stream_decoder_set_metadata_ignore_application(decoder, id) - - libflac.FLAC__stream_decoder_set_metadata_ignore_all.restype = FLAC__bool - libflac.FLAC__stream_decoder_set_metadata_ignore_all.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_set_metadata_ignore_all(decoder): - return libflac.FLAC__stream_decoder_set_metadata_ignore_all(decoder) - - libflac.FLAC__stream_decoder_get_state.restype = FLAC__StreamDecoderState - libflac.FLAC__stream_decoder_get_state.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_state(decoder): - return libflac.FLAC__stream_decoder_get_state(decoder) - - libflac.FLAC__stream_decoder_get_resolved_state_string.restype = c_char_p - libflac.FLAC__stream_decoder_get_resolved_state_string.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_resolved_state_string(decoder): - return libflac.FLAC__stream_decoder_get_resolved_state_string(decoder) - - libflac.FLAC__stream_decoder_get_md5_checking.restype = FLAC__bool - libflac.FLAC__stream_decoder_get_md5_checking.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_md5_checking(decoder): - return libflac.FLAC__stream_decoder_get_md5_checking(decoder) - - libflac.FLAC__stream_decoder_get_total_samples.restype = FLAC__uint64 - libflac.FLAC__stream_decoder_get_total_samples.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_total_samples(decoder): - return libflac.FLAC__stream_decoder_get_total_samples(decoder) - - libflac.FLAC__stream_decoder_get_channels.restype = c_uint - libflac.FLAC__stream_decoder_get_channels.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_channels(decoder): - return libflac.FLAC__stream_decoder_get_channels(decoder) - - libflac.FLAC__stream_decoder_get_channel_assignment.restype = FLAC__ChannelAssignment - libflac.FLAC__stream_decoder_get_channel_assignment.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_channel_assignment(decoder): - return libflac.FLAC__stream_decoder_get_channel_assignment(decoder) - - libflac.FLAC__stream_decoder_get_bits_per_sample.restype = c_uint - libflac.FLAC__stream_decoder_get_bits_per_sample.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_bits_per_sample(decoder): - return libflac.FLAC__stream_decoder_get_bits_per_sample(decoder) - - libflac.FLAC__stream_decoder_get_sample_rate.restype = c_uint - libflac.FLAC__stream_decoder_get_sample_rate.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_sample_rate(decoder): - return libflac.FLAC__stream_decoder_get_sample_rate(decoder) - - libflac.FLAC__stream_decoder_get_blocksize.restype = c_uint - libflac.FLAC__stream_decoder_get_blocksize.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_get_blocksize(decoder): - return libflac.FLAC__stream_decoder_get_blocksize(decoder) - - libflac.FLAC__stream_decoder_get_decode_position.restype = FLAC__bool - libflac.FLAC__stream_decoder_get_decode_position.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__uint64_p] - - def FLAC__stream_decoder_get_decode_position(decoder, position): - return libflac.FLAC__stream_decoder_get_decode_position(decoder, position) - - libflac.FLAC__stream_decoder_init_stream.restype = FLAC__StreamDecoderInitStatus - libflac.FLAC__stream_decoder_init_stream.argtypes = [POINTER(FLAC__StreamDecoder), - FLAC__StreamDecoderReadCallback, - FLAC__StreamDecoderSeekCallback, - FLAC__StreamDecoderTellCallback, - FLAC__StreamDecoderLengthCallback, - FLAC__StreamDecoderEofCallback, - FLAC__StreamDecoderWriteCallback, - FLAC__StreamDecoderMetadataCallback, - FLAC__StreamDecoderErrorCallback, - c_void_p] - - def FLAC__stream_decoder_init_stream(decoder, read_callback, seek_callback, tell_callback, length_callback, eof_callback, write_callback, metadata_callback, error_callback, client_data): - return libflac.FLAC__stream_decoder_init_stream(decoder, read_callback, seek_callback, tell_callback, length_callback, eof_callback, write_callback, metadata_callback, error_callback, client_data) - - - libflac.FLAC__stream_decoder_init_ogg_stream.restype = FLAC__StreamDecoderInitStatus - libflac.FLAC__stream_decoder_init_ogg_stream.argtypes = [POINTER(FLAC__StreamDecoder), - FLAC__StreamDecoderReadCallback, - FLAC__StreamDecoderSeekCallback, - FLAC__StreamDecoderTellCallback, - FLAC__StreamDecoderLengthCallback, - FLAC__StreamDecoderEofCallback, - FLAC__StreamDecoderWriteCallback, - FLAC__StreamDecoderMetadataCallback, - FLAC__StreamDecoderErrorCallback, - c_void_p] - - def FLAC__stream_decoder_init_ogg_stream(decoder, read_callback, seek_callback, tell_callback, length_callback, eof_callback, write_callback, metadata_callback, error_callback, client_data): - return libflac.FLAC__stream_decoder_init_ogg_stream(decoder, read_callback, seek_callback, tell_callback, length_callback, eof_callback, write_callback, metadata_callback, error_callback, client_data) - - libflac.FLAC__stream_decoder_init_file.restype = FLAC__StreamDecoderInitStatus - libflac.FLAC__stream_decoder_init_file.argtypes = [POINTER(FLAC__StreamDecoder), - c_char_p, - FLAC__StreamDecoderWriteCallback, - FLAC__StreamDecoderMetadataCallback, - FLAC__StreamDecoderErrorCallback, - c_void_p] - - def FLAC__stream_decoder_init_file(decoder, filename, write_callback, metadata_callback, error_callback, client_data): - return libflac.FLAC__stream_decoder_init_file(decoder, filename, write_callback, metadata_callback, error_callback, client_data) - - libflac.FLAC__stream_decoder_init_ogg_file.restype = FLAC__StreamDecoderInitStatus - libflac.FLAC__stream_decoder_init_ogg_file.argtypes = [POINTER(FLAC__StreamDecoder), - c_char_p, - FLAC__StreamDecoderWriteCallback, - FLAC__StreamDecoderMetadataCallback, - FLAC__StreamDecoderErrorCallback, - c_void_p] - - def FLAC__stream_decoder_init_ogg_file(decoder, filename, write_callback, metadata_callback, error_callback, client_data): - return libflac.FLAC__stream_decoder_init_ogg_file(decoder, filename, write_callback, metadata_callback, error_callback, client_data) - - libflac.FLAC__stream_decoder_finish.restype = FLAC__bool - libflac.FLAC__stream_decoder_finish.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_finish(decoder): - return libflac.FLAC__stream_decoder_finish(decoder) - - libflac.FLAC__stream_decoder_flush.restype = FLAC__bool - libflac.FLAC__stream_decoder_flush.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_flush(decoder): - return libflac.FLAC__stream_decoder_flush(decoder) - - libflac.FLAC__stream_decoder_reset.restype = FLAC__bool - libflac.FLAC__stream_decoder_reset.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_reset(decoder): - return libflac.FLAC__stream_decoder_reset(decoder) - - libflac.FLAC__stream_decoder_process_single.restype = FLAC__bool - libflac.FLAC__stream_decoder_process_single.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_process_single(decoder): - return libflac.FLAC__stream_decoder_process_single(decoder) - - libflac.FLAC__stream_decoder_process_until_end_of_metadata.restype = FLAC__bool - libflac.FLAC__stream_decoder_process_until_end_of_metadata.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_process_until_end_of_metadata(decoder): - return libflac.FLAC__stream_decoder_process_until_end_of_metadata(decoder) - - libflac.FLAC__stream_decoder_process_until_end_of_stream.restype = FLAC__bool - libflac.FLAC__stream_decoder_process_until_end_of_stream.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_process_until_end_of_stream(decoder): - return libflac.FLAC__stream_decoder_process_until_end_of_stream(decoder) - - libflac.FLAC__stream_decoder_skip_single_frame.restype = FLAC__bool - libflac.FLAC__stream_decoder_skip_single_frame.argtypes = [POINTER(FLAC__StreamDecoder)] - - def FLAC__stream_decoder_skip_single_frame(decoder): - return libflac.FLAC__stream_decoder_skip_single_frame(decoder) - - libflac.FLAC__stream_decoder_seek_absolute.restype = FLAC__bool - libflac.FLAC__stream_decoder_seek_absolute.argtypes = [POINTER(FLAC__StreamDecoder), FLAC__uint64] - - def FLAC__stream_decoder_seek_absolute(decoder, sample): - return libflac.FLAC__stream_decoder_seek_absolute(decoder, sample) - - # /stream_decoder - - # stream_encoder - - FLAC__StreamEncoderState = c_int - - libflac.FLAC__StreamEncoderStateString.restype = c_char_p - libflac.FLAC__StreamEncoderStateString.argtypes = [] - - def FLAC__StreamEncoderStateString(): - return libflac.FLAC__StreamEncoderStateString() - - - FLAC__StreamEncoderInitStatus = c_int - - libflac.FLAC__StreamEncoderInitStatusString.restype = c_char_p - libflac.FLAC__StreamEncoderInitStatusString.argtypes = [] - - def FLAC__StreamEncoderInitStatusString(): - return libflac.FLAC__StreamEncoderInitStatusString() - - - FLAC__StreamEncoderReadStatus = c_int - - libflac.FLAC__StreamEncoderReadStatusString.restype = c_char_p - libflac.FLAC__StreamEncoderReadStatusString.argtypes = [] - - def FLAC__StreamEncoderReadStatusString(): - return libflac.FLAC__StreamEncoderReadStatusString() - - - FLAC__StreamEncoderWriteStatus = c_int - - libflac.FLAC__StreamEncoderWriteStatusString.restype = c_char_p - libflac.FLAC__StreamEncoderWriteStatusString.argtypes = [] - - def FLAC__StreamEncoderWriteStatusString(): - return libflac.FLAC__StreamEncoderWriteStatusString() - - - FLAC__StreamEncoderSeekStatus = c_int - - libflac.FLAC__StreamEncoderSeekStatusString.restype = c_char_p - libflac.FLAC__StreamEncoderSeekStatusString.argtypes = [] - - def FLAC__StreamEncoderSeekStatusString(): - return libflac.FLAC__StreamEncoderSeekStatusString() - - - FLAC__StreamEncoderTellStatus = c_int - - libflac.FLAC__StreamEncoderTellStatusString.restype = c_char_p - libflac.FLAC__StreamEncoderTellStatusString.argtypes = [] - - def FLAC__StreamEncoderTellStatusString(): - return libflac.FLAC__StreamEncoderTellStatusString() - - - class FLAC__StreamEncoderProtected(Structure): - _fields_ = [("dummy", c_int)] - - class FLAC__StreamEncoderPrivate(Structure): - _fields_ = [("dummy", c_int)] - - class FLAC__StreamEncoder(Structure): - _fields_ = [("protected_", POINTER(FLAC__StreamEncoderProtected)), - ("private_", POINTER(FLAC__StreamEncoderPrivate))] - - FLAC__StreamEncoderReadCallback = CFUNCTYPE(FLAC__StreamEncoderReadStatus, POINTER(FLAC__StreamEncoder), POINTER(FLAC__byte*0), c_size_t_p, c_void_p) - - FLAC__StreamEncoderWriteCallback = CFUNCTYPE(FLAC__StreamEncoderWriteStatus, POINTER(FLAC__StreamEncoder), POINTER(FLAC__byte*0), c_size_t, c_uint, c_uint, c_void_p) - - FLAC__StreamEncoderSeekCallback = CFUNCTYPE(FLAC__StreamEncoderSeekStatus, POINTER(FLAC__StreamEncoder), FLAC__uint64, c_void_p) - - FLAC__StreamEncoderTellCallback = CFUNCTYPE(FLAC__StreamEncoderTellStatus, POINTER(FLAC__StreamEncoder), FLAC__uint64_p, c_void_p) - - FLAC__StreamEncoderMetadataCallback = CFUNCTYPE(None, POINTER(FLAC__StreamEncoder), POINTER(FLAC__StreamMetadata), c_void_p) - - FLAC__StreamEncoderProgressCallback = CFUNCTYPE(None, POINTER(FLAC__StreamEncoder), FLAC__uint64,FLAC__uint64, c_uint, c_uint, c_void_p) - - - libflac.FLAC__stream_encoder_new.restype = POINTER(FLAC__StreamEncoder) - libflac.FLAC__stream_encoder_new.argtypes = [] - - def FLAC__stream_encoder_new(): - return libflac.FLAC__stream_encoder_new() - - libflac.FLAC__stream_encoder_delete.restype = None - libflac.FLAC__stream_encoder_delete.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_delete(encoder): - return libflac.FLAC__stream_encoder_delete(encoder) - - - libflac.FLAC__stream_encoder_set_ogg_serial_number.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_ogg_serial_number.argtypes = [POINTER(FLAC__StreamEncoder), c_long] - - def FLAC__stream_encoder_set_ogg_serial_number(encoder, serial_number): - return libflac.FLAC__stream_encoder_set_ogg_serial_number(encoder, serial_number) - - libflac.FLAC__stream_encoder_set_verify.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_verify.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_verify(encoder, value): - return libflac.FLAC__stream_encoder_set_verify(encoder, value) - - libflac.FLAC__stream_encoder_set_streamable_subset.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_streamable_subset.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_streamable_subset(encoder, value): - return libflac.FLAC__stream_encoder_set_streamable_subset(encoder, value) - - libflac.FLAC__stream_encoder_set_channels.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_channels.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_channels(encoder, value): - return libflac.FLAC__stream_encoder_set_channels(encoder, value) - - libflac.FLAC__stream_encoder_set_bits_per_sample.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_bits_per_sample.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_bits_per_sample(encoder, value): - return libflac.FLAC__stream_encoder_set_bits_per_sample(encoder, value) - - libflac.FLAC__stream_encoder_set_sample_rate.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_sample_rate.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_sample_rate(encoder, value): - return libflac.FLAC__stream_encoder_set_sample_rate(encoder, value) - - libflac.FLAC__stream_encoder_set_compression_level.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_compression_level.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_compression_level(encoder, value): - return libflac.FLAC__stream_encoder_set_compression_level(encoder, value) - - libflac.FLAC__stream_encoder_set_blocksize.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_blocksize.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_blocksize(encoder, value): - return libflac.FLAC__stream_encoder_set_blocksize(encoder, value) - - libflac.FLAC__stream_encoder_set_do_mid_side_stereo.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_do_mid_side_stereo.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_do_mid_side_stereo(encoder, value): - return libflac.FLAC__stream_encoder_set_do_mid_side_stereo(encoder, value) - - libflac.FLAC__stream_encoder_set_loose_mid_side_stereo.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_loose_mid_side_stereo.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_loose_mid_side_stereo(encoder, value): - return libflac.FLAC__stream_encoder_set_loose_mid_side_stereo(encoder, value) - - libflac.FLAC__stream_encoder_set_apodization.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_apodization.argtypes = [POINTER(FLAC__StreamEncoder), c_char_p] - - def FLAC__stream_encoder_set_apodization(encoder, specification): - return libflac.FLAC__stream_encoder_set_apodization(encoder, specification) - - libflac.FLAC__stream_encoder_set_max_lpc_order.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_max_lpc_order.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_max_lpc_order(encoder, value): - return libflac.FLAC__stream_encoder_set_max_lpc_order(encoder, value) - - libflac.FLAC__stream_encoder_set_qlp_coeff_precision.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_qlp_coeff_precision.argtypes = [POINTER(FLAC__StreamEncoder), c_uint] - - def FLAC__stream_encoder_set_qlp_coeff_precision(encoder, value): - return libflac.FLAC__stream_encoder_set_qlp_coeff_precision(encoder, value) - - libflac.FLAC__stream_encoder_set_do_qlp_coeff_prec_search.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_do_qlp_coeff_prec_search.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder, value): - return libflac.FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder, value) - - libflac.FLAC__stream_encoder_set_do_escape_coding.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_do_escape_coding.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_do_escape_coding(encoder, value): - return libflac.FLAC__stream_encoder_set_do_escape_coding(encoder, value) - - libflac.FLAC__stream_encoder_set_do_exhaustive_model_search.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_do_exhaustive_model_search.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_do_exhaustive_model_search(encoder, value): - return libflac.FLAC__stream_encoder_set_do_exhaustive_model_search(encoder, value) - - libflac.FLAC__stream_encoder_set_min_residual_partition_order.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_min_residual_partition_order.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_min_residual_partition_order(encoder, value): - return libflac.FLAC__stream_encoder_set_min_residual_partition_order(encoder, value) - - libflac.FLAC__stream_encoder_set_max_residual_partition_order.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_max_residual_partition_order.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_max_residual_partition_order(encoder, value): - return libflac.FLAC__stream_encoder_set_max_residual_partition_order(encoder, value) - - libflac.FLAC__stream_encoder_set_rice_parameter_search_dist.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_rice_parameter_search_dist.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__bool] - - def FLAC__stream_encoder_set_rice_parameter_search_dist(encoder, value): - return libflac.FLAC__stream_encoder_set_rice_parameter_search_dist(encoder, value) - - libflac.FLAC__stream_encoder_set_total_samples_estimate.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_total_samples_estimate.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__uint64] - - def FLAC__stream_encoder_set_total_samples_estimate(encoder, value): - return libflac.FLAC__stream_encoder_set_total_samples_estimate(encoder, value) - - libflac.FLAC__stream_encoder_set_metadata.restype = FLAC__bool - libflac.FLAC__stream_encoder_set_metadata.argtypes = [POINTER(FLAC__StreamEncoder), POINTER(POINTER(FLAC__StreamMetadata)), c_uint] - - def FLAC__stream_encoder_set_metadata(encoder, metadata, num_blocks): - return libflac.FLAC__stream_encoder_set_metadata(encoder, metadata, num_blocks) - - libflac.FLAC__stream_encoder_get_state.restype = FLAC__StreamEncoderState - libflac.FLAC__stream_encoder_get_state.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_state(encoder): - return libflac.FLAC__stream_encoder_get_state(encoder) - - libflac.FLAC__stream_encoder_get_verify_decoder_state.restype = FLAC__StreamEncoderState - libflac.FLAC__stream_encoder_get_verify_decoder_state.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_verify_decoder_state(encoder): - return libflac.FLAC__stream_encoder_get_verify_decoder_state(encoder) - - libflac.FLAC__stream_encoder_get_resolved_state_string.restype = c_char_p - libflac.FLAC__stream_encoder_get_resolved_state_string.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_resolved_state_string(encoder): - return libflac.FLAC__stream_encoder_get_resolved_state_string(encoder) - - libflac.FLAC__stream_encoder_get_verify_decoder_error_stats.restype = None - libflac.FLAC__stream_encoder_get_verify_decoder_error_stats.argtypes = [POINTER(FLAC__StreamEncoder), FLAC__uint64_p, c_uint_p, c_uint_p, c_uint_p, FLAC__int32_p, FLAC__int32_p] - - def FLAC__stream_encoder_get_verify_decoder_error_stats(encoder, absolute_sample, frame_number, channel, sample, expected, got): - return libflac.FLAC__stream_encoder_get_verify_decoder_error_stats(encoder, absolute_sample, frame_number, channel, sample, expected, got) - - libflac.FLAC__stream_encoder_get_verify.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_verify.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_verify(encoder): - return libflac.FLAC__stream_encoder_get_verify(encoder) - - libflac.FLAC__stream_encoder_get_streamable_subset.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_streamable_subset.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_streamable_subset(encoder): - return libflac.FLAC__stream_encoder_get_streamable_subset(encoder) - - libflac.FLAC__stream_encoder_get_channels.restype = c_uint - libflac.FLAC__stream_encoder_get_channels.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_channels(encoder): - return libflac.FLAC__stream_encoder_get_channels(encoder) - - libflac.FLAC__stream_encoder_get_bits_per_sample.restype = c_uint - libflac.FLAC__stream_encoder_get_bits_per_sample.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_bits_per_sample(encoder): - return libflac.FLAC__stream_encoder_get_bits_per_sample(encoder) - - libflac.FLAC__stream_encoder_get_sample_rate.restype = c_uint - libflac.FLAC__stream_encoder_get_sample_rate.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_sample_rate(encoder): - return libflac.FLAC__stream_encoder_get_sample_rate(encoder) - - libflac.FLAC__stream_encoder_get_blocksize.restype = c_uint - libflac.FLAC__stream_encoder_get_blocksize.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_blocksize(encoder): - return libflac.FLAC__stream_encoder_get_blocksize(encoder) - - libflac.FLAC__stream_encoder_get_do_mid_side_stereo.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_do_mid_side_stereo.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_do_mid_side_stereo(encoder): - return libflac.FLAC__stream_encoder_get_do_mid_side_stereo(encoder) - - libflac.FLAC__stream_encoder_get_loose_mid_side_stereo.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_loose_mid_side_stereo.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_loose_mid_side_stereo(encoder): - return libflac.FLAC__stream_encoder_get_loose_mid_side_stereo(encoder) - - libflac.FLAC__stream_encoder_get_max_lpc_order.restype = c_uint - libflac.FLAC__stream_encoder_get_max_lpc_order.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_max_lpc_order(encoder): - return libflac.FLAC__stream_encoder_get_max_lpc_order(encoder) - - libflac.FLAC__stream_encoder_get_qlp_coeff_precision.restype = c_uint - libflac.FLAC__stream_encoder_get_qlp_coeff_precision.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_qlp_coeff_precision(encoder): - return libflac.FLAC__stream_encoder_get_qlp_coeff_precision(encoder) - - libflac.FLAC__stream_encoder_get_do_qlp_coeff_prec_search.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_do_qlp_coeff_prec_search.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder): - return libflac.FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder) - - libflac.FLAC__stream_encoder_get_do_escape_coding.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_do_escape_coding.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_do_escape_coding(encoder): - return libflac.FLAC__stream_encoder_get_do_escape_coding(encoder) - - libflac.FLAC__stream_encoder_get_do_exhaustive_model_search.restype = FLAC__bool - libflac.FLAC__stream_encoder_get_do_exhaustive_model_search.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_do_exhaustive_model_search(encoder): - return libflac.FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) - - libflac.FLAC__stream_encoder_get_min_residual_partition_order.restype = c_uint - libflac.FLAC__stream_encoder_get_min_residual_partition_order.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_min_residual_partition_order(encoder): - return libflac.FLAC__stream_encoder_get_min_residual_partition_order(encoder) - - libflac.FLAC__stream_encoder_get_max_residual_partition_order.restype = c_uint - libflac.FLAC__stream_encoder_get_max_residual_partition_order.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_max_residual_partition_order(encoder): - return libflac.FLAC__stream_encoder_get_max_residual_partition_order(encoder) - - libflac.FLAC__stream_encoder_get_rice_parameter_search_dist.restype = c_uint - libflac.FLAC__stream_encoder_get_rice_parameter_search_dist.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_rice_parameter_search_dist(encoder): - return libflac.FLAC__stream_encoder_get_rice_parameter_search_dist(encoder) - - libflac.FLAC__stream_encoder_get_total_samples_estimate.restype = FLAC__uint64 - libflac.FLAC__stream_encoder_get_total_samples_estimate.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_get_total_samples_estimate(encoder): - return libflac.FLAC__stream_encoder_get_total_samples_estimate(encoder) - - libflac.FLAC__stream_encoder_init_stream.restype = FLAC__StreamEncoderInitStatus - libflac.FLAC__stream_encoder_init_stream.argtypes = [POINTER(FLAC__StreamEncoder), - FLAC__StreamEncoderWriteCallback, - FLAC__StreamEncoderSeekCallback, - FLAC__StreamEncoderTellCallback, - FLAC__StreamEncoderMetadataCallback, - c_void_p] - - def FLAC__stream_encoder_init_stream(encoder, write_callback, seek_callback, tell_callback, metadata_callback,client_data): - return libflac.FLAC__stream_encoder_init_stream(encoder, write_callback, seek_callback, tell_callback, metadata_callback,client_data) - - libflac.FLAC__stream_encoder_init_ogg_stream.restype = FLAC__StreamEncoderInitStatus - libflac.FLAC__stream_encoder_init_ogg_stream.argtypes = [POINTER(FLAC__StreamEncoder), - FLAC__StreamEncoderReadCallback, - FLAC__StreamEncoderWriteCallback, - FLAC__StreamEncoderSeekCallback, - FLAC__StreamEncoderTellCallback, - FLAC__StreamEncoderMetadataCallback, - c_void_p] - - def FLAC__stream_encoder_init_ogg_stream(encoder, read_callback, write_callback, seek_callback, tell_callback, metadata_callback,client_data): - return libflac.FLAC__stream_encoder_init_ogg_stream(encoder, read_callback, write_callback, seek_callback, tell_callback, metadata_callback,client_data) - - libflac.FLAC__stream_encoder_init_file.restype = FLAC__StreamEncoderInitStatus - libflac.FLAC__stream_encoder_init_file.argtypes = [POINTER(FLAC__StreamEncoder), - c_char_p, - FLAC__StreamEncoderProgressCallback, - c_void_p] - - def FLAC__stream_encoder_init_file(encoder, filename, progress_callback,client_data): - return libflac.FLAC__stream_encoder_init_file(encoder, filename, progress_callback,client_data) - - - libflac.FLAC__stream_encoder_init_ogg_file.restype = FLAC__StreamEncoderInitStatus - libflac.FLAC__stream_encoder_init_ogg_file.argtypes = [POINTER(FLAC__StreamEncoder), - c_char_p, - FLAC__StreamEncoderProgressCallback, - c_void_p] - - def FLAC__stream_encoder_init_ogg_file(encoder, filename, progress_callback,client_data): - return libflac.FLAC__stream_encoder_init_ogg_file(encoder, filename, progress_callback,client_data) - - libflac.FLAC__stream_encoder_finish.restype = FLAC__bool - libflac.FLAC__stream_encoder_finish.argtypes = [POINTER(FLAC__StreamEncoder)] - - def FLAC__stream_encoder_finish(encoder): - return libflac.FLAC__stream_encoder_finish(encoder) - - libflac.FLAC__stream_encoder_process.restype = FLAC__bool - libflac.FLAC__stream_encoder_process.argtypes = [POINTER(FLAC__StreamEncoder), POINTER(FLAC__int32_p*0), c_uint] - - def FLAC__stream_encoder_process(encoder, buffer, samples): - return libflac.FLAC__stream_encoder_process(encoder, buffer, samples) - - libflac.FLAC__stream_encoder_process_interleaved.restype = FLAC__bool - libflac.FLAC__stream_encoder_process_interleaved.argtypes = [POINTER(FLAC__StreamEncoder), POINTER(FLAC__int32*0), c_uint] - - def FLAC__stream_encoder_process_interleaved(encoder, buffer, samples): - return libflac.FLAC__stream_encoder_process_interleaved(encoder, buffer, samples) - - # /stream_encoder diff --git a/sbapp/pyogg/flac_file.py b/sbapp/pyogg/flac_file.py deleted file mode 100644 index 7e97ca7..0000000 --- a/sbapp/pyogg/flac_file.py +++ /dev/null @@ -1,114 +0,0 @@ -import ctypes -from itertools import chain - -from . import flac -from .audio_file import AudioFile -from .pyogg_error import PyOggError - -def _to_char_p(string): - try: - return ctypes.c_char_p(string.encode("utf-8")) - except: - return ctypes.c_char_p(string) - -def _resize_array(array, new_size): - return (array._type_*new_size).from_address(ctypes.addressof(array)) - - -class FlacFile(AudioFile): - def write_callback(self, decoder, frame, buffer, client_data): - multi_channel_buf = _resize_array(buffer.contents, self.channels) - arr_size = frame.contents.header.blocksize - if frame.contents.header.channels >= 2: - arrays = [] - for i in range(frame.contents.header.channels): - arr = ctypes.cast(multi_channel_buf[i], ctypes.POINTER(flac.FLAC__int32*arr_size)).contents - arrays.append(arr[:]) - - arr = list(chain.from_iterable(zip(*arrays))) - - self.buffer[self.buffer_pos : self.buffer_pos + len(arr)] = arr[:] - self.buffer_pos += len(arr) - - else: - arr = ctypes.cast(multi_channel_buf[0], ctypes.POINTER(flac.FLAC__int32*arr_size)).contents - self.buffer[self.buffer_pos : self.buffer_pos + arr_size] = arr[:] - self.buffer_pos += arr_size - return 0 - - def metadata_callback(self,decoder, metadata, client_data): - if not self.buffer: - self.total_samples = metadata.contents.data.stream_info.total_samples - self.channels = metadata.contents.data.stream_info.channels - Buffer = flac.FLAC__int16*(self.total_samples * self.channels) - self.buffer = Buffer() - self.frequency = metadata.contents.data.stream_info.sample_rate - - def error_callback(self,decoder, status, client_data): - raise PyOggError("An error occured during the process of decoding. Status enum: {}".format(flac.FLAC__StreamDecoderErrorStatusEnum[status])) - - def __init__(self, path): - self.decoder = flac.FLAC__stream_decoder_new() - - self.client_data = ctypes.c_void_p() - - #: Number of channels in audio file. - self.channels = None - - #: Number of samples per second (per channel). For - # example, 44100. - self.frequency = None - - self.total_samples = None - - #: Raw PCM data from audio file. - self.buffer = None - - self.buffer_pos = 0 - - write_callback_ = flac.FLAC__StreamDecoderWriteCallback(self.write_callback) - - metadata_callback_ = flac.FLAC__StreamDecoderMetadataCallback(self.metadata_callback) - - error_callback_ = flac.FLAC__StreamDecoderErrorCallback(self.error_callback) - - init_status = flac.FLAC__stream_decoder_init_file( - self.decoder, - _to_char_p(path), # This will have an issue with Unicode filenames - write_callback_, - metadata_callback_, - error_callback_, - self.client_data - ) - - if init_status: # error - error = flac.FLAC__StreamDecoderInitStatusEnum[init_status] - raise PyOggError( - "An error occured when trying to open '{}': {}".format(path, error) - ) - - metadata_status = (flac.FLAC__stream_decoder_process_until_end_of_metadata(self.decoder)) - if not metadata_status: # error - raise PyOggError("An error occured when trying to decode the metadata of {}".format(path)) - - stream_status = (flac.FLAC__stream_decoder_process_until_end_of_stream(self.decoder)) - if not stream_status: # error - raise PyOggError("An error occured when trying to decode the audio stream of {}".format(path)) - - flac.FLAC__stream_decoder_finish(self.decoder) - - #: Length of buffer - self.buffer_length = len(self.buffer) - - self.bytes_per_sample = ctypes.sizeof(flac.FLAC__int16) # See definition of Buffer in metadata_callback() - - # Cast buffer to one-dimensional array of chars - CharBuffer = ( - ctypes.c_byte * - (self.bytes_per_sample * len(self.buffer)) - ) - self.buffer = CharBuffer.from_buffer(self.buffer) - - # FLAC audio is always signed. See - # https://xiph.org/flac/api/group__flac__stream__decoder.html#gaf98a4f9e2cac5747da6018c3dfc8dde1 - self.signed = True diff --git a/sbapp/pyogg/flac_file_stream.py b/sbapp/pyogg/flac_file_stream.py deleted file mode 100644 index f832c31..0000000 --- a/sbapp/pyogg/flac_file_stream.py +++ /dev/null @@ -1,141 +0,0 @@ -import ctypes -from itertools import chain - -from . import flac -from .pyogg_error import PyOggError - -def _to_char_p(string): - try: - return ctypes.c_char_p(string.encode("utf-8")) - except: - return ctypes.c_char_p(string) - -def _resize_array(array, new_size): - return (array._type_*new_size).from_address(ctypes.addressof(array)) - - -class FlacFileStream: - def write_callback(self,decoder, frame, buffer, client_data): - multi_channel_buf = _resize_array(buffer.contents, self.channels) - arr_size = frame.contents.header.blocksize - if frame.contents.header.channels >= 2: - arrays = [] - for i in range(frame.contents.header.channels): - arr = ctypes.cast(multi_channel_buf[i], ctypes.POINTER(flac.FLAC__int32*arr_size)).contents - arrays.append(arr[:]) - - arr = list(chain.from_iterable(zip(*arrays))) - - self.buffer = (flac.FLAC__int16*len(arr))(*arr) - self.bytes_written = len(arr) * 2 - - else: - arr = ctypes.cast(multi_channel_buf[0], ctypes.POINTER(flac.FLAC__int32*arr_size)).contents - self.buffer = (flac.FLAC__int16*len(arr))(*arr[:]) - self.bytes_written = arr_size * 2 - return 0 - - def metadata_callback(self,decoder, metadata, client_data): - self.total_samples = metadata.contents.data.stream_info.total_samples - self.channels = metadata.contents.data.stream_info.channels - self.frequency = metadata.contents.data.stream_info.sample_rate - - def error_callback(self,decoder, status, client_data): - raise PyOggError("An error occured during the process of decoding. Status enum: {}".format(flac.FLAC__StreamDecoderErrorStatusEnum[status])) - - def __init__(self, path): - self.decoder = flac.FLAC__stream_decoder_new() - - self.client_data = ctypes.c_void_p() - - #: Number of channels in audio file. - self.channels = None - - #: Number of samples per second (per channel). For - # example, 44100. - self.frequency = None - - self.total_samples = None - - self.buffer = None - - self.bytes_written = None - - self.write_callback_ = flac.FLAC__StreamDecoderWriteCallback(self.write_callback) - - self.metadata_callback_ = flac.FLAC__StreamDecoderMetadataCallback(self.metadata_callback) - - self.error_callback_ = flac.FLAC__StreamDecoderErrorCallback(self.error_callback) - - init_status = flac.FLAC__stream_decoder_init_file(self.decoder, - _to_char_p(path), - self.write_callback_, - self.metadata_callback_, - self.error_callback_, - self.client_data) - - if init_status: # error - raise PyOggError("An error occured when trying to open '{}': {}".format(path, flac.FLAC__StreamDecoderInitStatusEnum[init_status])) - - metadata_status = (flac.FLAC__stream_decoder_process_until_end_of_metadata(self.decoder)) - if not metadata_status: # error - raise PyOggError("An error occured when trying to decode the metadata of {}".format(path)) - - #: Bytes per sample - self.bytes_per_sample = 2 - - def get_buffer(self): - """Returns the buffer. - - Returns buffer (a bytes object) or None if all data has - been read from the file. - - """ - # Attempt to read a single frame of audio - stream_status = (flac.FLAC__stream_decoder_process_single(self.decoder)) - if not stream_status: # error - raise PyOggError("An error occured when trying to decode the audio stream of {}".format(path)) - - # Check if we encountered the end of the stream - if (flac.FLAC__stream_decoder_get_state(self.decoder) == 4): # end of stream - return None - - buffer_as_bytes = bytes(self.buffer) - return buffer_as_bytes - - def clean_up(self): - flac.FLAC__stream_decoder_finish(self.decoder) - - def get_buffer_as_array(self): - """Provides the buffer as a NumPy array. - - Note that the underlying data type is 16-bit signed - integers. - - Does not copy the underlying data, so the returned array - should either be processed or copied before the next call - to get_buffer() or get_buffer_as_array(). - - """ - import numpy # type: ignore - - # Read the next samples from the stream - buf = self.get_buffer() - - # Check if we've come to the end of the stream - if buf is None: - return None - - # Convert the bytes buffer to a NumPy array - array = numpy.frombuffer( - buf, - dtype=numpy.int16 - ) - - # Reshape the array - return array.reshape( - (len(buf) - // self.bytes_per_sample - // self.channels, - self.channels) - ) diff --git a/sbapp/pyogg/library_loader.py b/sbapp/pyogg/library_loader.py deleted file mode 100644 index 711b1ba..0000000 --- a/sbapp/pyogg/library_loader.py +++ /dev/null @@ -1,147 +0,0 @@ -import ctypes -import ctypes.util -import os -import sys -import platform -from typing import ( - Optional, - Dict, - List -) - -_here = os.path.dirname(__file__) - -class ExternalLibraryError(Exception): - pass - -architecture = platform.architecture()[0] - -_windows_styles = ["{}", "lib{}", "lib{}_dynamic", "{}_dynamic"] - -_other_styles = ["{}", "lib{}"] - -if architecture == "32bit": - for arch_style in ["32bit", "32" "86", "win32", "x86", "_x86", "_32", "_win32", "_32bit"]: - for style in ["{}", "lib{}"]: - _windows_styles.append(style.format("{}"+arch_style)) - -elif architecture == "64bit": - for arch_style in ["64bit", "64" "86_64", "amd64", "win_amd64", "x86_64", "_x86_64", "_64", "_amd64", "_64bit"]: - for style in ["{}", "lib{}"]: - _windows_styles.append(style.format("{}"+arch_style)) - - -run_tests = lambda lib, tests: [f(lib) for f in tests] - -# Get the appropriate directory for the shared libraries depending -# on the current platform and architecture -platform_ = platform.system() -lib_dir = None -if platform_ == "Darwin": - lib_dir = "libs/macos" -elif platform_ == "Windows": - if architecture == "32bit": - lib_dir = "libs/win32" - elif architecture == "64bit": - lib_dir = "libs/win_amd64" - - -class Library: - @staticmethod - def load(names: Dict[str, str], paths: Optional[List[str]] = None, tests = []) -> Optional[ctypes.CDLL]: - lib = InternalLibrary.load(names, tests) - if lib is None: - lib = ExternalLibrary.load(names["external"], paths, tests) - return lib - - -class InternalLibrary: - @staticmethod - def load(names: Dict[str, str], tests) -> Optional[ctypes.CDLL]: - # If we do not have a library directory, give up immediately - if lib_dir is None: - return None - - # Get the appropriate library filename given the platform - try: - name = names[platform_] - except KeyError: - return None - - # Attempt to load the library from here - path = _here + "/" + lib_dir + "/" + name - try: - lib = ctypes.CDLL(path) - except OSError as e: - return None - - # Check that the library passes the tests - if tests and all(run_tests(lib, tests)): - return lib - - # Library failed tests - return None - -# Cache of libraries that have already been loaded -_loaded_libraries: Dict[str, ctypes.CDLL] = {} - -class ExternalLibrary: - @staticmethod - def load(name, paths = None, tests = []): - if name in _loaded_libraries: - return _loaded_libraries[name] - if sys.platform == "win32": - lib = ExternalLibrary.load_windows(name, paths, tests) - _loaded_libraries[name] = lib - return lib - else: - lib = ExternalLibrary.load_other(name, paths, tests) - _loaded_libraries[name] = lib - return lib - - @staticmethod - def load_other(name, paths = None, tests = []): - os.environ["PATH"] += ";" + ";".join((os.getcwd(), _here)) - if paths: os.environ["PATH"] += ";" + ";".join(paths) - - for style in _other_styles: - candidate = style.format(name) - library = ctypes.util.find_library(candidate) - if library: - try: - lib = ctypes.CDLL(library) - if tests and all(run_tests(lib, tests)): - return lib - except: - pass - - @staticmethod - def load_windows(name, paths = None, tests = []): - os.environ["PATH"] += ";" + ";".join((os.getcwd(), _here)) - if paths: os.environ["PATH"] += ";" + ";".join(paths) - - not_supported = [] # libraries that were found, but are not supported - for style in _windows_styles: - candidate = style.format(name) - library = ctypes.util.find_library(candidate) - if library: - try: - lib = ctypes.CDLL(library) - if tests and all(run_tests(lib, tests)): - return lib - not_supported.append(library) - except WindowsError: - pass - except OSError: - not_supported.append(library) - - - if not_supported: - raise ExternalLibraryError("library '{}' couldn't be loaded, because the following candidates were not supported:".format(name) - + ("\n{}" * len(not_supported)).format(*not_supported)) - - raise ExternalLibraryError("library '{}' couldn't be loaded".format(name)) - - - - diff --git a/sbapp/pyogg/ogg.py b/sbapp/pyogg/ogg.py deleted file mode 100644 index 08a944b..0000000 --- a/sbapp/pyogg/ogg.py +++ /dev/null @@ -1,672 +0,0 @@ -############################################################ -# Ogg license: # -############################################################ -""" -Copyright (c) 2002, Xiph.org Foundation - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -- Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -- Neither the name of the Xiph.org Foundation nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - -import ctypes -from ctypes import c_int, c_int8, c_int16, c_int32, c_int64, c_uint, c_uint8, c_uint16, c_uint32, c_uint64, c_float, c_long, c_ulong, c_char, c_char_p, c_ubyte, c_longlong, c_ulonglong, c_size_t, c_void_p, c_double, POINTER, pointer, cast -import ctypes.util -import sys -from traceback import print_exc as _print_exc -import os - -from .library_loader import Library, ExternalLibrary, ExternalLibraryError - - -def get_raw_libname(name): - name = os.path.splitext(name)[0].lower() - for x in "0123456789._- ":name=name.replace(x,"") - return name - -# Define a function to convert strings to char-pointers. In Python 3 -# all strings are Unicode, while in Python 2 they were ASCII-encoded. -# FIXME: Does PyOgg even support Python 2? -if sys.version_info.major > 2: - to_char_p = lambda s: s.encode('utf-8') -else: - to_char_p = lambda s: s - -__here = os.getcwd() - -libogg = None - -try: - names = { - "Windows": "ogg.dll", - "Darwin": "libogg.0.dylib", - "external": "ogg" - } - libogg = Library.load(names, tests = [lambda lib: hasattr(lib, "oggpack_writeinit")]) -except ExternalLibraryError: - pass -except: - _print_exc() - -if libogg is not None: - PYOGG_OGG_AVAIL = True -else: - PYOGG_OGG_AVAIL = False - -if PYOGG_OGG_AVAIL: - # Sanity check also satisfies mypy type checking - assert libogg is not None - - # ctypes - c_ubyte_p = POINTER(c_ubyte) - c_uchar = c_ubyte - c_uchar_p = c_ubyte_p - c_float_p = POINTER(c_float) - c_float_p_p = POINTER(c_float_p) - c_float_p_p_p = POINTER(c_float_p_p) - c_char_p_p = POINTER(c_char_p) - c_int_p = POINTER(c_int) - c_long_p = POINTER(c_long) - - # os_types - ogg_int16_t = c_int16 - ogg_uint16_t = c_uint16 - ogg_int32_t = c_int32 - ogg_uint32_t = c_uint32 - ogg_int64_t = c_int64 - ogg_uint64_t = c_uint64 - ogg_int64_t_p = POINTER(ogg_int64_t) - - # ogg - class ogg_iovec_t(ctypes.Structure): - """ - Wrapper for: - typedef struct ogg_iovec_t; - """ - _fields_ = [("iov_base", c_void_p), - ("iov_len", c_size_t)] - - class oggpack_buffer(ctypes.Structure): - """ - Wrapper for: - typedef struct oggpack_buffer; - """ - _fields_ = [("endbyte", c_long), - ("endbit", c_int), - ("buffer", c_uchar_p), - ("ptr", c_uchar_p), - ("storage", c_long)] - - class ogg_page(ctypes.Structure): - """ - Wrapper for: - typedef struct ogg_page; - """ - _fields_ = [("header", c_uchar_p), - ("header_len", c_long), - ("body", c_uchar_p), - ("body_len", c_long)] - - class ogg_stream_state(ctypes.Structure): - """ - Wrapper for: - typedef struct ogg_stream_state; - """ - _fields_ = [("body_data", c_uchar_p), - ("body_storage", c_long), - ("body_fill", c_long), - ("body_returned", c_long), - - ("lacing_vals", c_int), - ("granule_vals", ogg_int64_t), - - ("lacing_storage", c_long), - ("lacing_fill", c_long), - ("lacing_packet", c_long), - ("lacing_returned", c_long), - - ("header", c_uchar*282), - ("header_fill", c_int), - - ("e_o_s", c_int), - ("b_o_s", c_int), - - ("serialno", c_long), - ("pageno", c_long), - ("packetno", ogg_int64_t), - ("granulepos", ogg_int64_t)] - - class ogg_packet(ctypes.Structure): - """ - Wrapper for: - typedef struct ogg_packet; - """ - _fields_ = [("packet", c_uchar_p), - ("bytes", c_long), - ("b_o_s", c_long), - ("e_o_s", c_long), - - ("granulepos", ogg_int64_t), - - ("packetno", ogg_int64_t)] - - def __str__(self): - bos = "" - if self.b_o_s: - bos = "beginning of stream, " - eos = "" - if self.e_o_s: - eos = "end of stream, " - - # Converting the data will cause a seg-fault if the memory isn't valid - data = bytes(self.packet[0:self.bytes]) - value = ( - f"Ogg Packet <{hex(id(self))}>: " + - f"number {self.packetno}, " + - f"granule position {self.granulepos}, " + - bos + eos + - f"{self.bytes} bytes" - ) - return value - - class ogg_sync_state(ctypes.Structure): - """ - Wrapper for: - typedef struct ogg_sync_state; - """ - _fields_ = [("data", c_uchar_p), - ("storage", c_int), - ("fill", c_int), - ("returned", c_int), - - ("unsynched", c_int), - ("headerbytes", c_int), - ("bodybytes", c_int)] - - b_p = POINTER(oggpack_buffer) - oy_p = POINTER(ogg_sync_state) - op_p = POINTER(ogg_packet) - og_p = POINTER(ogg_page) - os_p = POINTER(ogg_stream_state) - iov_p = POINTER(ogg_iovec_t) - - libogg.oggpack_writeinit.restype = None - libogg.oggpack_writeinit.argtypes = [b_p] - - def oggpack_writeinit(b): - libogg.oggpack_writeinit(b) - - try: - libogg.oggpack_writecheck.restype = c_int - libogg.oggpack_writecheck.argtypes = [b_p] - def oggpack_writecheck(b): - libogg.oggpack_writecheck(b) - except: - pass - - libogg.oggpack_writetrunc.restype = None - libogg.oggpack_writetrunc.argtypes = [b_p, c_long] - - def oggpack_writetrunc(b, bits): - libogg.oggpack_writetrunc(b, bits) - - libogg.oggpack_writealign.restype = None - libogg.oggpack_writealign.argtypes = [b_p] - - def oggpack_writealign(b): - libogg.oggpack_writealign(b) - - libogg.oggpack_writecopy.restype = None - libogg.oggpack_writecopy.argtypes = [b_p, c_void_p, c_long] - - def oggpack_writecopy(b, source, bits): - libogg.oggpack_writecopy(b, source, bits) - - libogg.oggpack_reset.restype = None - libogg.oggpack_reset.argtypes = [b_p] - - def oggpack_reset(b): - libogg.oggpack_reset(b) - - libogg.oggpack_writeclear.restype = None - libogg.oggpack_writeclear.argtypes = [b_p] - - def oggpack_writeclear(b): - libogg.oggpack_writeclear(b) - - libogg.oggpack_readinit.restype = None - libogg.oggpack_readinit.argtypes = [b_p, c_uchar_p, c_int] - - def oggpack_readinit(b, buf, bytes): - libogg.oggpack_readinit(b, buf, bytes) - - libogg.oggpack_write.restype = None - libogg.oggpack_write.argtypes = [b_p, c_ulong, c_int] - - def oggpack_write(b, value, bits): - libogg.oggpack_write(b, value, bits) - - libogg.oggpack_look.restype = c_long - libogg.oggpack_look.argtypes = [b_p, c_int] - - def oggpack_look(b, bits): - return libogg.oggpack_look(b, bits) - - libogg.oggpack_look1.restype = c_long - libogg.oggpack_look1.argtypes = [b_p] - - def oggpack_look1(b): - return libogg.oggpack_look1(b) - - libogg.oggpack_adv.restype = None - libogg.oggpack_adv.argtypes = [b_p, c_int] - - def oggpack_adv(b, bits): - libogg.oggpack_adv(b, bits) - - libogg.oggpack_adv1.restype = None - libogg.oggpack_adv1.argtypes = [b_p] - - def oggpack_adv1(b): - libogg.oggpack_adv1(b) - - libogg.oggpack_read.restype = c_long - libogg.oggpack_read.argtypes = [b_p, c_int] - - def oggpack_read(b, bits): - return libogg.oggpack_read(b, bits) - - libogg.oggpack_read1.restype = c_long - libogg.oggpack_read1.argtypes = [b_p] - - def oggpack_read1(b): - return libogg.oggpack_read1(b) - - libogg.oggpack_bytes.restype = c_long - libogg.oggpack_bytes.argtypes = [b_p] - - def oggpack_bytes(b): - return libogg.oggpack_bytes(b) - - libogg.oggpack_bits.restype = c_long - libogg.oggpack_bits.argtypes = [b_p] - - def oggpack_bits(b): - return libogg.oggpack_bits(b) - - libogg.oggpack_get_buffer.restype = c_uchar_p - libogg.oggpack_get_buffer.argtypes = [b_p] - - def oggpack_get_buffer(b): - return libogg.oggpack_get_buffer(b) - - - - libogg.oggpackB_writeinit.restype = None - libogg.oggpackB_writeinit.argtypes = [b_p] - - def oggpackB_writeinit(b): - libogg.oggpackB_writeinit(b) - - try: - libogg.oggpackB_writecheck.restype = c_int - libogg.oggpackB_writecheck.argtypes = [b_p] - - def oggpackB_writecheck(b): - return libogg.oggpackB_writecheck(b) - except: - pass - - libogg.oggpackB_writetrunc.restype = None - libogg.oggpackB_writetrunc.argtypes = [b_p, c_long] - - def oggpackB_writetrunc(b, bits): - libogg.oggpackB_writetrunc(b, bits) - - libogg.oggpackB_writealign.restype = None - libogg.oggpackB_writealign.argtypes = [b_p] - - def oggpackB_writealign(b): - libogg.oggpackB_writealign(b) - - libogg.oggpackB_writecopy.restype = None - libogg.oggpackB_writecopy.argtypes = [b_p, c_void_p, c_long] - - def oggpackB_writecopy(b, source, bits): - libogg.oggpackB_writecopy(b, source, bits) - - libogg.oggpackB_reset.restype = None - libogg.oggpackB_reset.argtypes = [b_p] - - def oggpackB_reset(b): - libogg.oggpackB_reset(b) - - libogg.oggpackB_reset.restype = None - libogg.oggpackB_writeclear.argtypes = [b_p] - - def oggpackB_reset(b): - libogg.oggpackB_reset(b) - - libogg.oggpackB_readinit.restype = None - libogg.oggpackB_readinit.argtypes = [b_p, c_uchar_p, c_int] - - def oggpackB_readinit(b, buf, bytes): - libogg.oggpackB_readinit(b, buf, bytes) - - libogg.oggpackB_write.restype = None - libogg.oggpackB_write.argtypes = [b_p, c_ulong, c_int] - - def oggpackB_write(b, value, bits): - libogg.oggpackB_write(b, value, bits) - - libogg.oggpackB_look.restype = c_long - libogg.oggpackB_look.argtypes = [b_p, c_int] - - def oggpackB_look(b, bits): - return libogg.oggpackB_look(b, bits) - - libogg.oggpackB_look1.restype = c_long - libogg.oggpackB_look1.argtypes = [b_p] - - def oggpackB_look1(b): - return libogg.oggpackB_look1(b) - - libogg.oggpackB_adv.restype = None - libogg.oggpackB_adv.argtypes = [b_p, c_int] - - def oggpackB_adv(b, bits): - libogg.oggpackB_adv(b, bits) - - libogg.oggpackB_adv1.restype = None - libogg.oggpackB_adv1.argtypes = [b_p] - - def oggpackB_adv1(b): - libogg.oggpackB_adv1(b) - - libogg.oggpackB_read.restype = c_long - libogg.oggpackB_read.argtypes = [b_p, c_int] - - def oggpackB_read(b, bits): - return libogg.oggpackB_read(b, bits) - - libogg.oggpackB_read1.restype = c_long - libogg.oggpackB_read1.argtypes = [b_p] - - def oggpackB_read1(b): - return libogg.oggpackB_read1(b) - - libogg.oggpackB_bytes.restype = c_long - libogg.oggpackB_bytes.argtypes = [b_p] - - def oggpackB_bytes(b): - return libogg.oggpackB_bytes(b) - - libogg.oggpackB_bits.restype = c_long - libogg.oggpackB_bits.argtypes = [b_p] - - def oggpackB_bits(b): - return libogg.oggpackB_bits(b) - - libogg.oggpackB_get_buffer.restype = c_uchar_p - libogg.oggpackB_get_buffer.argtypes = [b_p] - - def oggpackB_get_buffer(b): - return libogg.oggpackB_get_buffer(b) - - - - libogg.ogg_stream_packetin.restype = c_int - libogg.ogg_stream_packetin.argtypes = [os_p, op_p] - - def ogg_stream_packetin(os, op): - return libogg.ogg_stream_packetin(os, op) - - try: - libogg.ogg_stream_iovecin.restype = c_int - libogg.ogg_stream_iovecin.argtypes = [os_p, iov_p, c_int, c_long, ogg_int64_t] - - def ogg_stream_iovecin(os, iov, count, e_o_s, granulepos): - return libogg.ogg_stream_iovecin(os, iov, count, e_o_s, granulepos) - except: - pass - - libogg.ogg_stream_pageout.restype = c_int - libogg.ogg_stream_pageout.argtypes = [os_p, og_p] - - def ogg_stream_pageout(os, og): - return libogg.ogg_stream_pageout(os, og) - - try: - libogg.ogg_stream_pageout_fill.restype = c_int - libogg.ogg_stream_pageout_fill.argtypes = [os_p, og_p, c_int] - def ogg_stream_pageout_fill(os, og, nfill): - return libogg.ogg_stream_pageout_fill(os, og, nfill) - except: - pass - - libogg.ogg_stream_flush.restype = c_int - libogg.ogg_stream_flush.argtypes = [os_p, og_p] - - def ogg_stream_flush(os, og): - return libogg.ogg_stream_flush(os, og) - - try: - libogg.ogg_stream_flush_fill.restype = c_int - libogg.ogg_stream_flush_fill.argtypes = [os_p, og_p, c_int] - def ogg_stream_flush_fill(os, og, nfill): - return libogg.ogg_stream_flush_fill(os, og, nfill) - except: - pass - - - - libogg.ogg_sync_init.restype = c_int - libogg.ogg_sync_init.argtypes = [oy_p] - - def ogg_sync_init(oy): - return libogg.ogg_sync_init(oy) - - libogg.ogg_sync_clear.restype = c_int - libogg.ogg_sync_clear.argtypes = [oy_p] - - def ogg_sync_clear(oy): - return libogg.ogg_sync_clear(oy) - - libogg.ogg_sync_reset.restype = c_int - libogg.ogg_sync_reset.argtypes = [oy_p] - - def ogg_sync_reset(oy): - return libogg.ogg_sync_reset(oy) - - libogg.ogg_sync_destroy.restype = c_int - libogg.ogg_sync_destroy.argtypes = [oy_p] - - def ogg_sync_destroy(oy): - return libogg.ogg_sync_destroy(oy) - - try: - libogg.ogg_sync_check.restype = c_int - libogg.ogg_sync_check.argtypes = [oy_p] - def ogg_sync_check(oy): - return libogg.ogg_sync_check(oy) - except: - pass - - - - libogg.ogg_sync_buffer.restype = c_char_p - libogg.ogg_sync_buffer.argtypes = [oy_p, c_long] - - def ogg_sync_buffer(oy, size): - return libogg.ogg_sync_buffer(oy, size) - - libogg.ogg_sync_wrote.restype = c_int - libogg.ogg_sync_wrote.argtypes = [oy_p, c_long] - - def ogg_sync_wrote(oy, bytes): - return libogg.ogg_sync_wrote(oy, bytes) - - libogg.ogg_sync_pageseek.restype = c_int - libogg.ogg_sync_pageseek.argtypes = [oy_p, og_p] - - def ogg_sync_pageseek(oy, og): - return libogg.ogg_sync_pageseek(oy, og) - - libogg.ogg_sync_pageout.restype = c_long - libogg.ogg_sync_pageout.argtypes = [oy_p, og_p] - - def ogg_sync_pageout(oy, og): - return libogg.ogg_sync_pageout(oy, og) - - libogg.ogg_stream_pagein.restype = c_int - libogg.ogg_stream_pagein.argtypes = [os_p, og_p] - - def ogg_stream_pagein(os, og): - return libogg.ogg_stream_pagein(oy, og) - - libogg.ogg_stream_packetout.restype = c_int - libogg.ogg_stream_packetout.argtypes = [os_p, op_p] - - def ogg_stream_packetout(os, op): - return libogg.ogg_stream_packetout(oy, op) - - libogg.ogg_stream_packetpeek.restype = c_int - libogg.ogg_stream_packetpeek.argtypes = [os_p, op_p] - - def ogg_stream_packetpeek(os, op): - return libogg.ogg_stream_packetpeek(os, op) - - - - libogg.ogg_stream_init.restype = c_int - libogg.ogg_stream_init.argtypes = [os_p, c_int] - - def ogg_stream_init(os, serialno): - return libogg.ogg_stream_init(os, serialno) - - libogg.ogg_stream_clear.restype = c_int - libogg.ogg_stream_clear.argtypes = [os_p] - - def ogg_stream_clear(os): - return libogg.ogg_stream_clear(os) - - libogg.ogg_stream_reset.restype = c_int - libogg.ogg_stream_reset.argtypes = [os_p] - - def ogg_stream_reset(os): - return libogg.ogg_stream_reset(os) - - libogg.ogg_stream_reset_serialno.restype = c_int - libogg.ogg_stream_reset_serialno.argtypes = [os_p, c_int] - - def ogg_stream_reset_serialno(os, serialno): - return libogg.ogg_stream_reset_serialno(os, serialno) - - libogg.ogg_stream_destroy.restype = c_int - libogg.ogg_stream_destroy.argtypes = [os_p] - - def ogg_stream_destroy(os): - return libogg.ogg_stream_destroy(os) - - try: - libogg.ogg_stream_check.restype = c_int - libogg.ogg_stream_check.argtypes = [os_p] - def ogg_stream_check(os): - return libogg.ogg_stream_check(os) - except: - pass - - libogg.ogg_stream_eos.restype = c_int - libogg.ogg_stream_eos.argtypes = [os_p] - - def ogg_stream_eos(os): - return libogg.ogg_stream_eos(os) - - - - libogg.ogg_page_checksum_set.restype = None - libogg.ogg_page_checksum_set.argtypes = [og_p] - - def ogg_page_checksum_set(og): - libogg.ogg_page_checksum_set(og) - - - - libogg.ogg_page_version.restype = c_int - libogg.ogg_page_version.argtypes = [og_p] - - def ogg_page_version(og): - return libogg.ogg_page_version(og) - - libogg.ogg_page_continued.restype = c_int - libogg.ogg_page_continued.argtypes = [og_p] - - def ogg_page_continued(og): - return libogg.ogg_page_continued(og) - - libogg.ogg_page_bos.restype = c_int - libogg.ogg_page_bos.argtypes = [og_p] - - def ogg_page_bos(og): - return libogg.ogg_page_bos(og) - - libogg.ogg_page_eos.restype = c_int - libogg.ogg_page_eos.argtypes = [og_p] - - def ogg_page_eos(og): - return libogg.ogg_page_eos(og) - - libogg.ogg_page_granulepos.restype = ogg_int64_t - libogg.ogg_page_granulepos.argtypes = [og_p] - - def ogg_page_granulepos(og): - return libogg.ogg_page_granulepos(og) - - libogg.ogg_page_serialno.restype = c_int - libogg.ogg_page_serialno.argtypes = [og_p] - - def ogg_page_serialno(og): - return libogg.ogg_page_serialno(og) - - libogg.ogg_page_pageno.restype = c_long - libogg.ogg_page_pageno.argtypes = [og_p] - - def ogg_page_pageno(og): - return libogg.ogg_page_pageno(og) - - libogg.ogg_page_packets.restype = c_int - libogg.ogg_page_packets.argtypes = [og_p] - - def ogg_page_packets(og): - return libogg.ogg_page_packets(og) - - - - libogg.ogg_packet_clear.restype = None - libogg.ogg_packet_clear.argtypes = [op_p] - - def ogg_packet_clear(op): - libogg.ogg_packet_clear(op) diff --git a/sbapp/pyogg/ogg_opus_writer.py b/sbapp/pyogg/ogg_opus_writer.py deleted file mode 100644 index 547d0f5..0000000 --- a/sbapp/pyogg/ogg_opus_writer.py +++ /dev/null @@ -1,421 +0,0 @@ -import builtins -import copy -import ctypes -import random -import struct -from typing import ( - Optional, - Union, - BinaryIO -) - -from . import ogg -from . import opus -from .opus_buffered_encoder import OpusBufferedEncoder -#from .opus_encoder import OpusEncoder -from .pyogg_error import PyOggError - -class OggOpusWriter(): - """Encodes PCM data into an OggOpus file.""" - - def __init__(self, - f: Union[BinaryIO, str], - encoder: OpusBufferedEncoder, - custom_pre_skip: Optional[int] = None) -> None: - """Construct an OggOpusWriter. - - f may be either a string giving the path to the file, or - an already-opened file handle. - - If f is an already-opened file handle, then it is the - user's responsibility to close the file when they are - finished with it. The file should be opened for writing - in binary (not text) mode. - - The encoder should be a - OpusBufferedEncoder and should be fully configured before the - first call to the `write()` method. - - The Opus encoder requires an amount of "warm up" and when - stored in an Ogg container that warm up can be skipped. When - `custom_pre_skip` is None, the required amount of warm up - silence is automatically calculated and inserted. If a custom - (non-silent) pre-skip is desired, then `custom_pre_skip` - should be specified as the number of samples (per channel). - It is then the user's responsibility to pass the non-silent - pre-skip samples to `encode()`. - - """ - # Store the Opus encoder - self._encoder = encoder - - # Store the custom pre skip - self._custom_pre_skip = custom_pre_skip - - # Create a new stream state with a random serial number - self._stream_state = self._create_stream_state() - - # Create a packet (reused for each pass) - self._ogg_packet = ogg.ogg_packet() - self._packet_valid = False - - # Create a page (reused for each pass) - self._ogg_page = ogg.ogg_page() - - # Counter for the number of packets written into Ogg stream - self._count_packets = 0 - - # Counter for the number of samples encoded into Opus - # packets - self._count_samples = 0 - - # Flag to indicate if the headers have been written - self._headers_written = False - - # Flag to indicate that the stream has been finished (the - # EOS bit was set in a final packet) - self._finished = False - - # Reference to the current encoded packet (written only - # when we know if it the last) - self._current_encoded_packet: Optional[bytes] = None - - # Open file if required. Given this may raise an exception, - # it should be the last step of initialisation. - self._i_opened_the_file = False - if isinstance(f, str): - self._file = builtins.open(f, 'wb') - self._i_opened_the_file = True - else: - # Assume it's already opened file - self._file = f - - def __del__(self) -> None: - if not self._finished: - self.close() - - # - # User visible methods - # - - def write(self, pcm: memoryview) -> None: - """Encode the PCM and write out the Ogg Opus stream. - - Encoders the PCM using the provided encoder. - - """ - # Check that the stream hasn't already been finished - if self._finished: - raise PyOggError( - "Stream has already ended. Perhaps close() was "+ - "called too early?") - - # If we haven't already written out the headers, do so - # now. Then, write a frame of silence to warm up the - # encoder. - if not self._headers_written: - pre_skip = self._write_headers(self._custom_pre_skip) - if self._custom_pre_skip is None: - self._write_silence(pre_skip) - - # Call the internal method to encode the bytes - self._write_to_oggopus(pcm) - - - def _write_to_oggopus(self, pcm: memoryview, flush: bool = False) -> None: - assert self._encoder is not None - - def handle_encoded_packet(encoded_packet: memoryview, - samples: int, - end_of_stream: bool) -> None: - # Cast memoryview to ctypes Array - Buffer = ctypes.c_ubyte * len(encoded_packet) - encoded_packet_ctypes = Buffer.from_buffer(encoded_packet) - - # Obtain a pointer to the encoded packet - encoded_packet_ptr = ctypes.cast( - encoded_packet_ctypes, - ctypes.POINTER(ctypes.c_ubyte) - ) - - # Increase the count of the number of samples written - self._count_samples += samples - - # Place data into the packet - self._ogg_packet.packet = encoded_packet_ptr - self._ogg_packet.bytes = len(encoded_packet) - self._ogg_packet.b_o_s = 0 - self._ogg_packet.e_o_s = end_of_stream - self._ogg_packet.granulepos = self._count_samples - self._ogg_packet.packetno = self._count_packets - - # Increase the counter of the number of packets - # in the stream - self._count_packets += 1 - - # Write the packet into the stream - self._write_packet() - - - # Encode the PCM data into an Opus packet - self._encoder.buffered_encode( - pcm, - flush=flush, - callback=handle_encoded_packet - ) - - def close(self) -> None: - # Check we haven't already closed this stream - if self._finished: - # We're attempting to close an already closed stream, - # do nothing more. - return - - # Flush the underlying buffered encoder - self._write_to_oggopus(memoryview(bytearray(b"")), flush=True) - - # The current packet must be the end of the stream, update - # the packet's details - self._ogg_packet.e_o_s = 1 - - # Write the packet to the stream - if self._packet_valid: - self._write_packet() - - # Flush the stream of any unwritten pages - self._flush() - - # Mark the stream as finished - self._finished = True - - # Close the file if we opened it - if self._i_opened_the_file: - self._file.close() - self._i_opened_the_file = False - - # Clean up the Ogg-related memory - ogg.ogg_stream_clear(self._stream_state) - - # Clean up the reference to the encoded packet (as it must - # now have been written) - del self._current_encoded_packet - - # - # Internal methods - # - - def _create_random_serial_no(self) -> ctypes.c_int: - sizeof_c_int = ctypes.sizeof(ctypes.c_int) - min_int = -2**(sizeof_c_int*8-1) - max_int = 2**(sizeof_c_int*8-1)-1 - serial_no = ctypes.c_int(random.randint(min_int, max_int)) - - return serial_no - - def _create_stream_state(self) -> ogg.ogg_stream_state: - # Create a random serial number - serial_no = self._create_random_serial_no() - - # Create an ogg_stream_state - ogg_stream_state = ogg.ogg_stream_state() - - # Initialise the stream state - ogg.ogg_stream_init( - ctypes.pointer(ogg_stream_state), - serial_no - ) - - return ogg_stream_state - - def _make_identification_header(self, pre_skip: int, input_sampling_rate: int = 0) -> bytes: - """Make the OggOpus identification header. - - An input_sampling rate may be set to zero to mean 'unspecified'. - - Only channel mapping family 0 is currently supported. - This allows mono and stereo signals. - - See https://tools.ietf.org/html/rfc7845#page-12 for more - details. - - """ - signature = b"OpusHead" - version = 1 - output_channels = self._encoder._channels - output_gain = 0 - channel_mapping_family = 0 - data = struct.pack( - " int: - """ Returns pre-skip. """ - if custom_pre_skip is not None: - # Use the user-specified amount of pre-skip - pre_skip = custom_pre_skip - else: - # Obtain the algorithmic delay of the Opus encoder. See - # https://tools.ietf.org/html/rfc7845#page-27 - delay_samples = self._encoder.get_algorithmic_delay() - - # Extra samples are recommended. See - # https://tools.ietf.org/html/rfc7845#page-27 - extra_samples = 120 - - # We will just fill a whole frame with silence. Calculate - # the minimum frame length, which we'll use as the - # pre-skip. - frame_durations = [2.5, 5, 10, 20, 40, 60] # milliseconds - frame_lengths = [ - x * self._encoder._samples_per_second // 1000 - for x in frame_durations - ] - for frame_length in frame_lengths: - if frame_length > delay_samples + extra_samples: - pre_skip = frame_length - break - - # Create the identification header - id_header = self._make_identification_header( - pre_skip = pre_skip - ) - - # Specify the packet containing the identification header - self._ogg_packet.packet = ctypes.cast(id_header, ogg.c_uchar_p) # type: ignore - self._ogg_packet.bytes = len(id_header) - self._ogg_packet.b_o_s = 1 - self._ogg_packet.e_o_s = 0 - self._ogg_packet.granulepos = 0 - self._ogg_packet.packetno = self._count_packets - self._count_packets += 1 - - # Write the identification header - result = ogg.ogg_stream_packetin( - self._stream_state, - self._ogg_packet - ) - - if result != 0: - raise PyOggError( - "Failed to write Opus identification header" - ) - - return pre_skip - - def _make_comment_header(self): - """Make the OggOpus comment header. - - See https://tools.ietf.org/html/rfc7845#page-22 for more - details. - - """ - signature = b"OpusTags" - vendor_string = b"ENCODER=PyOgg" - vendor_string_length = struct.pack(" None: - super().__init__() - - self._frame_size_ms: Optional[float] = None - self._frame_size_bytes: Optional[int] = None - - # Buffer contains the bytes required for the next - # frame. - self._buffer: Optional[ctypes.Array] = None - - # Location of the next free byte in the buffer - self._buffer_index = 0 - - - def set_frame_size(self, frame_size: float) -> None: - """ Set the desired frame duration (in milliseconds). - - Valid options are 2.5, 5, 10, 20, 40, or 60ms. - - """ - - # Ensure the frame size is valid. Compare frame size in - # units of 0.1ms to avoid floating point comparison - if int(frame_size*10) not in [25, 50, 100, 200, 400, 600]: - raise PyOggError( - "Frame size ({:f}) not one of ".format(frame_size)+ - "the acceptable values" - ) - - self._frame_size_ms = frame_size - - self._calc_frame_size() - - - def set_sampling_frequency(self, samples_per_second: int) -> None: - super().set_sampling_frequency(samples_per_second) - self._calc_frame_size() - - - def buffered_encode(self, - pcm_bytes: memoryview, - flush: bool = False, - callback: Callable[[memoryview,int,bool],None] = None - ) -> List[Tuple[memoryview, int, bool]]: - """Gets encoded packets and their number of samples. - - This method returns a list, where each item in the list is - a tuple. The first item in the tuple is an Opus-encoded - frame stored as a bytes-object. The second item in the - tuple is the number of samples encoded (excluding - silence). - - If `callback` is supplied then this method will instead - return an empty list but call the callback for every - Opus-encoded frame that would have been returned as a - list. This option has the desireable property of - eliminating the copying of the encoded packets, which is - required in order to form a list. The callback should - take two arguments, the encoded frame (a Python bytes - object) and the number of samples encoded per channel (an - int). The user must either process or copy the data as - the data may be overwritten once the callback terminates. - - """ - # If there's no work to do return immediately - if len(pcm_bytes) == 0 and flush == False: - return [] # no work to do - - # Sanity checks - if self._frame_size_ms is None: - raise PyOggError("Frame size must be set before encoding") - assert self._frame_size_bytes is not None - assert self._channels is not None - assert self._buffer is not None - assert self._buffer_index is not None - - # Local variable initialisation - results = [] - pcm_index = 0 - pcm_len = len(pcm_bytes) - - # 'Cast' memoryview of PCM to ctypes Array - Buffer = ctypes.c_ubyte * len(pcm_bytes) - try: - pcm_ctypes = Buffer.from_buffer(pcm_bytes) - except TypeError: - warnings.warn( - "Because PCM was read-only, an extra memory "+ - "copy was required; consider storing PCM in "+ - "writable memory (for example, bytearray "+ - "rather than bytes)." - ) - pcm_ctypes = Buffer.from_buffer(pcm_bytes) - - # Either store the encoded packet to return at the end of the - # method or immediately call the callback with the encoded - # packet. - def store_or_callback(encoded_packet: memoryview, - samples: int, - end_of_stream: bool = False) -> None: - if callback is None: - # Store the result - results.append(( - encoded_packet, - samples, - end_of_stream - )) - else: - # Call the callback - callback( - encoded_packet, - samples, - end_of_stream - ) - - # Fill the remainder of the buffer with silence and encode it. - # The associated number of samples are only that of actual - # data, not the added silence. - def flush_buffer() -> None: - # Sanity checks to satisfy mypy - assert self._buffer_index is not None - assert self._channels is not None - assert self._buffer is not None - - # If the buffer is already empty, we have no work to do - if self._buffer_index == 0: - return - - # Store the number of samples currently in the buffer - samples = ( - self._buffer_index - // self._channels - // ctypes.sizeof(opus.opus_int16) - ) - - # Fill the buffer with silence - ctypes.memset( - # destination - ctypes.byref(self._buffer, self._buffer_index), - # value - 0, - # count - len(self._buffer) - self._buffer_index - ) - - # Encode the PCM - # As at 2020-11-05, mypy is unaware that ctype Arrays - # support the buffer protocol. - encoded_packet = self.encode(memoryview(self._buffer)) # type: ignore - - # Either store the encoded packet or call the - # callback - store_or_callback(encoded_packet, samples, True) - - - # Copy the data remaining from the provided PCM into the - # buffer. Flush if required. - def copy_insufficient_data() -> None: - # Sanity checks to satisfy mypy - assert self._buffer is not None - - # Calculate remaining data - remaining_data = len(pcm_bytes) - pcm_index - - # Copy the data into the buffer. - ctypes.memmove( - # destination - ctypes.byref(self._buffer, self._buffer_index), - # source - ctypes.byref(pcm_ctypes, pcm_index), - # count - remaining_data - ) - - self._buffer_index += remaining_data - - # If we've been asked to flush the buffer then do so - if flush: - flush_buffer() - - # Loop through the provided PCM and the current buffer, - # encoding as we have full packets. - while True: - # There are two possibilities at this point: either we - # have previously unencoded data still in the buffer or we - # do not - if self._buffer_index == 0: - # We do not have unencoded data - - # We are free to progress through the PCM that has - # been provided encoding frames without copying any - # bytes. Once there is insufficient data remaining - # for a complete frame, that data should be copied - # into the buffer and we have finished. - if pcm_len - pcm_index > self._frame_size_bytes: - # We have enough data remaining in the provided - # PCM to encode more than an entire frame without - # copying any data. Unfortunately, splicing a - # ctypes array copies the array. To avoid the - # copy we use memoryview see - # https://mattgwwalker.wordpress.com/2020/12/12/python-ctypes-slicing/ - frame_data = memoryview(pcm_bytes)[ - pcm_index:pcm_index+self._frame_size_bytes - ] - - # Update the PCM index - pcm_index += self._frame_size_bytes - - # Store number of samples (per channel) of actual - # data - samples = ( - len(frame_data) - // self._channels - // ctypes.sizeof(opus.opus_int16) - ) - - # Encode the PCM - encoded_packet = super().encode(frame_data) - - # Either store the encoded packet or call the - # callback - store_or_callback(encoded_packet, samples) - - else: - # We do not have enough data to fill a frame while - # still having data left over. Copy the data into - # the buffer. - copy_insufficient_data() - return results - - else: - # We have unencoded data. - - # Copy the provided PCM into the buffer (up until the - # buffer is full). If we can fill it, then we can - # encode the filled buffer and continue. If we can't - # fill it then we've finished. - data_required = len(self._buffer) - self._buffer_index - if pcm_len > data_required: - # We have sufficient data to fill the buffer and - # have data left over. Copy data into the buffer. - assert pcm_index == 0 - remaining = len(self._buffer) - self._buffer_index - ctypes.memmove( - # destination - ctypes.byref(self._buffer, self._buffer_index), - # source - pcm_ctypes, - # count - remaining - ) - pcm_index += remaining - self._buffer_index += remaining - assert self._buffer_index == len(self._buffer) - - # Encode the PCM - encoded_packet = super().encode( - # Memoryviews of ctypes do work, even though - # mypy complains. - memoryview(self._buffer) # type: ignore - ) - - # Store number of samples (per channel) of actual - # data - samples = ( - self._buffer_index - // self._channels - // ctypes.sizeof(opus.opus_int16) - ) - - # We've now processed the buffer - self._buffer_index = 0 - - # Either store the encoded packet or call the - # callback - store_or_callback(encoded_packet, samples) - else: - # We have insufficient data to fill the buffer - # while still having data left over. Copy the - # data into the buffer. - copy_insufficient_data() - return results - - - def _calc_frame_size(self): - """Calculates the number of bytes in a frame. - - If the frame size (in milliseconds) and the number of - samples per seconds have already been specified, then the - frame size in bytes is set. Otherwise, this method does - nothing. - - The frame size is measured in bytes required to store the - sample. - - """ - if (self._frame_size_ms is None - or self._samples_per_second is None): - return - - self._frame_size_bytes = ( - self._frame_size_ms - * self._samples_per_second - // 1000 - * ctypes.sizeof(opus.opus_int16) - * self._channels - ) - - # Allocate space for the buffer - Buffer = ctypes.c_ubyte * self._frame_size_bytes - self._buffer = Buffer() - - - def _get_next_frame(self, add_silence=False): - """Gets the next Opus-encoded frame. - - Returns a tuple where the first item is the Opus-encoded - frame and the second item is the number of encoded samples - (per channel). - - Returns None if insufficient data is available. - - """ - next_frame = bytes() - samples = 0 - - # Ensure frame size has been specified - if self._frame_size_bytes is None: - raise PyOggError( - "Desired frame size hasn't been set. Perhaps "+ - "encode() was called before set_frame_size() "+ - "and set_sampling_frequency()?" - ) - - # Check if there's insufficient data in the buffer to fill - # a frame. - if self._frame_size_bytes > self._buffer_size: - if len(self._buffer) == 0: - # No data at all in buffer - return None - if add_silence: - # Get all remaining data - while len(self._buffer) != 0: - next_frame += self._buffer.popleft() - self._buffer_size = 0 - # Store number of samples (per channel) of actual - # data - samples = ( - len(next_frame) - // self._channels - // ctypes.sizeof(opus.opus_int16) - ) - # Fill remainder of frame with silence - bytes_remaining = self._frame_size_bytes - len(next_frame) - next_frame += b'\x00' * bytes_remaining - return (next_frame, samples) - else: - # Insufficient data to fill a frame and we're not - # adding silence - return None - - bytes_remaining = self._frame_size_bytes - while bytes_remaining > 0: - if len(self._buffer[0]) <= bytes_remaining: - # Take the whole first item - buffer_ = self._buffer.popleft() - next_frame += buffer_ - bytes_remaining -= len(buffer_) - self._buffer_size -= len(buffer_) - else: - # Take only part of the buffer - - # TODO: This could be more efficiently - # implemented. Rather than appending back the - # remaining data, we could just update an index - # saying where we were up to in regards to the - # first entry of the buffer. - buffer_ = self._buffer.popleft() - next_frame += buffer_[:bytes_remaining] - self._buffer_size -= bytes_remaining - # And put the unused part back into the buffer - self._buffer.appendleft(buffer_[bytes_remaining:]) - bytes_remaining = 0 - - # Calculate number of samples (per channel) - samples = ( - len(next_frame) - // self._channels - // ctypes.sizeof(opus.opus_int16) - ) - - return (next_frame, samples) diff --git a/sbapp/pyogg/opus_decoder.py b/sbapp/pyogg/opus_decoder.py deleted file mode 100644 index 8a1f4dd..0000000 --- a/sbapp/pyogg/opus_decoder.py +++ /dev/null @@ -1,273 +0,0 @@ -import ctypes - -from . import opus -from .pyogg_error import PyOggError - -class OpusDecoder: - def __init__(self): - self._decoder = None - self._channels = None - self._samples_per_second = None - self._pcm_buffer = None - self._pcm_buffer_ptr = None - self._pcm_buffer_size_int = None - - # TODO: Check if there is clean up that we need to do when - # closing a decoder. - - # - # User visible methods - # - - def set_channels(self, n): - - """Set the number of channels. - - n must be either 1 or 2. - - The decoder is capable of filling in either mono or - interleaved stereo pcm buffers. - - """ - if self._decoder is None: - if n < 0 or n > 2: - raise PyOggError( - "Invalid number of channels in call to "+ - "set_channels()" - ) - self._channels = n - else: - raise PyOggError( - "Cannot change the number of channels after "+ - "the decoder was created. Perhaps "+ - "set_channels() was called after decode()?" - ) - self._create_pcm_buffer() - - def set_sampling_frequency(self, samples_per_second): - """Set the number of samples (per channel) per second. - - samples_per_second must be one of 8000, 12000, 16000, - 24000, or 48000. - - Internally Opus stores data at 48000 Hz, so that should be - the default value for Fs. However, the decoder can - efficiently decode to buffers at 8, 12, 16, and 24 kHz so - if for some reason the caller cannot use data at the full - sample rate, or knows the compressed data doesn't use the - full frequency range, it can request decoding at a reduced - rate. - - """ - if self._decoder is None: - if samples_per_second in [8000, 12000, 16000, 24000, 48000]: - self._samples_per_second = samples_per_second - else: - raise PyOggError( - "Specified sampling frequency "+ - "({:d}) ".format(samples_per_second)+ - "was not one of the accepted values" - ) - else: - raise PyOggError( - "Cannot change the sampling frequency after "+ - "the decoder was created. Perhaps "+ - "set_sampling_frequency() was called after decode()?" - ) - self._create_pcm_buffer() - - def decode(self, encoded_bytes: memoryview): - """Decodes an Opus-encoded packet into PCM. - - """ - # If we haven't already created a decoder, do so now - if self._decoder is None: - self._decoder = self._create_decoder() - - # Create a ctypes array from the memoryview (without copying - # data) - Buffer = ctypes.c_char * len(encoded_bytes) - encoded_bytes_ctypes = Buffer.from_buffer(encoded_bytes) - - # Create pointer to encoded bytes - encoded_bytes_ptr = ctypes.cast( - encoded_bytes_ctypes, - ctypes.POINTER(ctypes.c_ubyte) - ) - - # Store length of encoded bytes into int32 - len_int32 = opus.opus_int32( - len(encoded_bytes) - ) - - # Check that we have a PCM buffer - if self._pcm_buffer is None: - raise PyOggError("PCM buffer was not configured.") - - # Decode the encoded frame - result = opus.opus_decode( - self._decoder, - encoded_bytes_ptr, - len_int32, - self._pcm_buffer_ptr, - self._pcm_buffer_size_int, - 0 # TODO: What's Forward Error Correction about? - ) - - # Check for any errors - if result < 0: - raise PyOggError( - "An error occurred while decoding an Opus-encoded "+ - "packet: "+ - opus.opus_strerror(result).decode("utf") - ) - - # Extract just the valid data as bytes - end_valid_data = ( - result - * ctypes.sizeof(opus.opus_int16) - * self._channels - ) - - # Create memoryview of PCM buffer to avoid copying data during slice. - mv = memoryview(self._pcm_buffer) - - # Cast memoryview to chars - mv = mv.cast('c') - - # Slice memoryview to extract only valid data - mv = mv[:end_valid_data] - - return mv - - - def decode_missing_packet(self, frame_duration): - """ Obtain PCM data despite missing a frame. - - frame_duration is in milliseconds. - - """ - - # Consider frame duration in units of 0.1ms in order to - # avoid floating-point comparisons. - if int(frame_duration*10) not in [25, 50, 100, 200, 400, 600]: - raise PyOggError( - "Frame duration ({:f}) is not one of the accepted values".format(frame_duration) - ) - - # Calculate frame size - frame_size = int( - frame_duration - * self._samples_per_second - // 1000 - ) - - # Store frame size as int - frame_size_int = ctypes.c_int(frame_size) - - # Decode missing packet - result = opus.opus_decode( - self._decoder, - None, - 0, - self._pcm_buffer_ptr, - frame_size_int, - 0 # TODO: What is this Forward Error Correction about? - ) - - # Check for any errors - if result < 0: - raise PyOggError( - "An error occurred while decoding an Opus-encoded "+ - "packet: "+ - opus.opus_strerror(result).decode("utf") - ) - - # Extract just the valid data as bytes - end_valid_data = ( - result - * ctypes.sizeof(opus.opus_int16) - * self._channels - ) - return bytes(self._pcm_buffer)[:end_valid_data] - - # - # Internal methods - # - - def _create_pcm_buffer(self): - if (self._samples_per_second is None - or self._channels is None): - # We cannot define the buffer yet - return - - # Create buffer to hold 120ms of samples. See "opus_decode()" at - # https://opus-codec.org/docs/opus_api-1.3.1/group__opus__decoder.html - max_duration = 120 # milliseconds - max_samples = max_duration * self._samples_per_second // 1000 - PCMBuffer = opus.opus_int16 * (max_samples * self._channels) - self._pcm_buffer = PCMBuffer() - self._pcm_buffer_ptr = ( - ctypes.cast(ctypes.pointer(self._pcm_buffer), - ctypes.POINTER(opus.opus_int16)) - ) - - # Store samples per channel in an int - self._pcm_buffer_size_int = ctypes.c_int(max_samples) - - def _create_decoder(self): - # To create a decoder, we must first allocate resources for it. - # We want Python to be responsible for the memory deallocation, - # and thus Python must be responsible for the initial memory - # allocation. - - # Check that the sampling frequency has been defined - if self._samples_per_second is None: - raise PyOggError( - "The sampling frequency was not specified before "+ - "attempting to create an Opus decoder. Perhaps "+ - "decode() was called before set_sampling_frequency()?" - ) - - # The sampling frequency must be passed in as a 32-bit int - samples_per_second = opus.opus_int32(self._samples_per_second) - - # Check that the number of channels has been defined - if self._channels is None: - raise PyOggError( - "The number of channels were not specified before "+ - "attempting to create an Opus decoder. Perhaps "+ - "decode() was called before set_channels()?" - ) - - # The number of channels must also be passed in as a 32-bit int - channels = opus.opus_int32(self._channels) - - # Obtain the number of bytes of memory required for the decoder - size = opus.opus_decoder_get_size(channels); - - # Allocate the required memory for the decoder - memory = ctypes.create_string_buffer(size) - - # Cast the newly-allocated memory as a pointer to a decoder. We - # could also have used opus.od_p as the pointer type, but writing - # it out in full may be clearer. - decoder = ctypes.cast(memory, ctypes.POINTER(opus.OpusDecoder)) - - # Initialise the decoder - error = opus.opus_decoder_init( - decoder, - samples_per_second, - channels - ); - - # Check that there hasn't been an error when initialising the - # decoder - if error != opus.OPUS_OK: - raise PyOggError( - "An error occurred while creating the decoder: "+ - opus.opus_strerror(error).decode("utf") - ) - - # Return our newly-created decoder - return decoder diff --git a/sbapp/pyogg/opus_encoder.py b/sbapp/pyogg/opus_encoder.py deleted file mode 100644 index 1da82da..0000000 --- a/sbapp/pyogg/opus_encoder.py +++ /dev/null @@ -1,358 +0,0 @@ -import ctypes -from typing import Optional, Union, ByteString - -from . import opus -from .pyogg_error import PyOggError - -class OpusEncoder: - """Encodes PCM data into Opus frames.""" - def __init__(self) -> None: - self._encoder: Optional[ctypes.pointer] = None - self._channels: Optional[int] = None - self._samples_per_second: Optional[int] = None - self._application: Optional[int] = None - self._max_bytes_per_frame: Optional[opus.opus_int32] = None - self._output_buffer: Optional[ctypes.Array] = None - self._output_buffer_ptr: Optional[ctypes.pointer] = None - - # An output buffer of 4,000 bytes is recommended in - # https://opus-codec.org/docs/opus_api-1.3.1/group__opus__encoder.html - self.set_max_bytes_per_frame(4000) - - # - # User visible methods - # - - def set_channels(self, n: int) -> None: - """Set the number of channels. - - n must be either 1 or 2. - - """ - if self._encoder is None: - if n < 0 or n > 2: - raise PyOggError( - "Invalid number of channels in call to "+ - "set_channels()" - ) - self._channels = n - else: - raise PyOggError( - "Cannot change the number of channels after "+ - "the encoder was created. Perhaps "+ - "set_channels() was called after encode()?" - ) - - def set_sampling_frequency(self, samples_per_second: int) -> None: - """Set the number of samples (per channel) per second. - - This must be one of 8000, 12000, 16000, 24000, or 48000. - - Regardless of the sampling rate and number of channels - selected, the Opus encoder can switch to a lower audio - bandwidth or number of channels if the bitrate selected is - too low. This also means that it is safe to always use 48 - kHz stereo input and let the encoder optimize the - encoding. - - """ - if self._encoder is None: - if samples_per_second in [8000, 12000, 16000, 24000, 48000]: - self._samples_per_second = samples_per_second - else: - raise PyOggError( - "Specified sampling frequency "+ - "({:d}) ".format(samples_per_second)+ - "was not one of the accepted values" - ) - else: - raise PyOggError( - "Cannot change the sampling frequency after "+ - "the encoder was created. Perhaps "+ - "set_sampling_frequency() was called after encode()?" - ) - - def set_application(self, application: str) -> None: - """Set the encoding mode. - - This must be one of 'voip', 'audio', or 'restricted_lowdelay'. - - 'voip': Gives best quality at a given bitrate for voice - signals. It enhances the input signal by high-pass - filtering and emphasizing formants and - harmonics. Optionally it includes in-band forward error - correction to protect against packet loss. Use this mode - for typical VoIP applications. Because of the enhancement, - even at high bitrates the output may sound different from - the input. - - 'audio': Gives best quality at a given bitrate for most - non-voice signals like music. Use this mode for music and - mixed (music/voice) content, broadcast, and applications - requiring less than 15 ms of coding delay. - - 'restricted_lowdelay': configures low-delay mode that - disables the speech-optimized mode in exchange for - slightly reduced delay. This mode can only be set on an - newly initialized encoder because it changes the codec - delay. - """ - if self._encoder is not None: - raise PyOggError( - "Cannot change the application after "+ - "the encoder was created. Perhaps "+ - "set_application() was called after encode()?" - ) - if application == "voip": - self._application = opus.OPUS_APPLICATION_VOIP - elif application == "audio": - self._application = opus.OPUS_APPLICATION_AUDIO - elif application == "restricted_lowdelay": - self._application = opus.OPUS_APPLICATION_RESTRICTED_LOWDELAY - else: - raise PyOggError( - "The application specification '{:s}' ".format(application)+ - "wasn't one of the accepted values." - ) - - def set_max_bytes_per_frame(self, max_bytes: int) -> None: - """Set the maximum number of bytes in an encoded frame. - - Size of the output payload. This may be used to impose an - upper limit on the instant bitrate, but should not be used - as the only bitrate control. - - TODO: Use OPUS_SET_BITRATE to control the bitrate. - - """ - self._max_bytes_per_frame = opus.opus_int32(max_bytes) - OutputBuffer = ctypes.c_ubyte * max_bytes - self._output_buffer = OutputBuffer() - self._output_buffer_ptr = ( - ctypes.cast(ctypes.pointer(self._output_buffer), - ctypes.POINTER(ctypes.c_ubyte)) - ) - - - def encode(self, pcm: Union[bytes, bytearray, memoryview]) -> memoryview: - """Encodes PCM data into an Opus frame. - - `pcm` must be formatted as bytes-like, with each sample taking - two bytes (signed 16-bit integers; interleaved left, then - right channels if in stereo). - - If `pcm` is not writeable, a copy of the array will be made. - - """ - # If we haven't already created an encoder, do so now - if self._encoder is None: - self._encoder = self._create_encoder() - - # Sanity checks also satisfy mypy type checking - assert self._channels is not None - assert self._samples_per_second is not None - assert self._output_buffer is not None - - # Calculate the effective frame duration of the given PCM - # data. Calculate it in units of 0.1ms in order to avoid - # floating point comparisons. - bytes_per_sample = 2 - frame_size = ( - len(pcm) # bytes - // bytes_per_sample - // self._channels - ) - frame_duration = ( - (10*frame_size) - // (self._samples_per_second//1000) - ) - - # Check that we have a valid frame size - if int(frame_duration) not in [25, 50, 100, 200, 400, 600]: - raise PyOggError( - "The effective frame duration ({:.1f} ms) " - .format(frame_duration/10)+ - "was not one of the acceptable values." - ) - - # Create a ctypes object sharing the memory of the PCM data - PcmCtypes = ctypes.c_ubyte * len(pcm) - try: - # Attempt to share the PCM memory - - # Unfortunately, as at 2020-09-27, the type hinting for - # read-only and writeable buffer protocols was a - # work-in-progress. The following only works for writable - # cases, but the method's parameters include a read-only - # possibility (bytes), thus we ignore mypy's error. - pcm_ctypes = PcmCtypes.from_buffer(pcm) # type: ignore[arg-type] - except TypeError: - # The data must be copied if it's not writeable - pcm_ctypes = PcmCtypes.from_buffer_copy(pcm) - - # Create a pointer to the PCM data - pcm_ptr = ctypes.cast( - pcm_ctypes, - ctypes.POINTER(opus.opus_int16) - ) - - # Create an int giving the frame size per channel - frame_size_int = ctypes.c_int(frame_size) - - # Encode PCM - result = opus.opus_encode( - self._encoder, - pcm_ptr, - frame_size_int, - self._output_buffer_ptr, - self._max_bytes_per_frame - ) - - # Check for any errors - if result < 0: - raise PyOggError( - "An error occurred while encoding to Opus format: "+ - opus.opus_strerror(result).decode("utf") - ) - - # Get memoryview of buffer so that the slice operation doesn't - # copy the data. - # - # Unfortunately, as at 2020-09-27, the type hints for - # memoryview do not include ctype arrays. This is because - # there is no currently accepted manner to label a class as - # supporting the buffer protocol. However, it's clearly a - # work in progress. For more information, see: - # * https://bugs.python.org/issue27501 - # * https://github.com/python/typing/issues/593 - # * https://github.com/python/typeshed/pull/4232 - mv = memoryview(self._output_buffer) # type: ignore - - # Cast the memoryview to char - mv = mv.cast('c') - - # Slice just the valid data from the memoryview - valid_data_as_bytes = mv[:result] - - # DEBUG - # Convert memoryview back to ctypes instance - Buffer = ctypes.c_ubyte * len(valid_data_as_bytes) - buf = Buffer.from_buffer( valid_data_as_bytes ) - - # Convert PCM back to pointer and dump 4,000-byte buffer - ptr = ctypes.cast( - buf, - ctypes.POINTER(ctypes.c_ubyte) - ) - - return valid_data_as_bytes - - - def get_algorithmic_delay(self): - """Gets the total samples of delay added by the entire codec. - - This can be queried by the encoder and then the provided - number of samples can be skipped on from the start of the - decoder's output to provide time aligned input and - output. From the perspective of a decoding application the - real data begins this many samples late. - - The decoder contribution to this delay is identical for all - decoders, but the encoder portion of the delay may vary from - implementation to implementation, version to version, or even - depend on the encoder's initial configuration. Applications - needing delay compensation should call this method rather than - hard-coding a value. - - """ - # If we haven't already created an encoder, do so now - if self._encoder is None: - self._encoder = self._create_encoder() - - # Obtain the algorithmic delay of the Opus encoder. See - # https://tools.ietf.org/html/rfc7845#page-27 - delay = opus.opus_int32() - - result = opus.opus_encoder_ctl( - self._encoder, - opus.OPUS_GET_LOOKAHEAD_REQUEST, - ctypes.pointer(delay) - ) - if result != opus.OPUS_OK: - raise PyOggError( - "Failed to obtain the algorithmic delay of "+ - "the Opus encoder: "+ - opus.opus_strerror(result).decode("utf") - ) - delay_samples = delay.value - return delay_samples - - - # - # Internal methods - # - - def _create_encoder(self) -> ctypes.pointer: - # To create an encoder, we must first allocate resources for it. - # We want Python to be responsible for the memory deallocation, - # and thus Python must be responsible for the initial memory - # allocation. - - # Check that the application has been defined - if self._application is None: - raise PyOggError( - "The application was not specified before "+ - "attempting to create an Opus encoder. Perhaps "+ - "encode() was called before set_application()?" - ) - application = self._application - - # Check that the sampling frequency has been defined - if self._samples_per_second is None: - raise PyOggError( - "The sampling frequency was not specified before "+ - "attempting to create an Opus encoder. Perhaps "+ - "encode() was called before set_sampling_frequency()?" - ) - - # The frequency must be passed in as a 32-bit int - samples_per_second = opus.opus_int32(self._samples_per_second) - - # Check that the number of channels has been defined - if self._channels is None: - raise PyOggError( - "The number of channels were not specified before "+ - "attempting to create an Opus encoder. Perhaps "+ - "encode() was called before set_channels()?" - ) - channels = self._channels - - # Obtain the number of bytes of memory required for the encoder - size = opus.opus_encoder_get_size(channels); - - # Allocate the required memory for the encoder - memory = ctypes.create_string_buffer(size) - - # Cast the newly-allocated memory as a pointer to an encoder. We - # could also have used opus.oe_p as the pointer type, but writing - # it out in full may be clearer. - encoder = ctypes.cast(memory, ctypes.POINTER(opus.OpusEncoder)) - - # Initialise the encoder - error = opus.opus_encoder_init( - encoder, - samples_per_second, - channels, - application - ) - - # Check that there hasn't been an error when initialising the - # encoder - if error != opus.OPUS_OK: - raise PyOggError( - "An error occurred while creating the encoder: "+ - opus.opus_strerror(error).decode("utf") - ) - - # Return our newly-created encoder - return encoder diff --git a/sbapp/pyogg/opus_file.py b/sbapp/pyogg/opus_file.py deleted file mode 100644 index f8519f4..0000000 --- a/sbapp/pyogg/opus_file.py +++ /dev/null @@ -1,106 +0,0 @@ -import ctypes - -from . import ogg -from . import opus -from .pyogg_error import PyOggError -from .audio_file import AudioFile - -class OpusFile(AudioFile): - def __init__(self, path: str) -> None: - # Open the file - error = ctypes.c_int() - of = opus.op_open_file( - ogg.to_char_p(path), - ctypes.pointer(error) - ) - - # Check for errors - if error.value != 0: - raise PyOggError( - ("File '{}' couldn't be opened or doesn't exist. "+ - "Error code: {}").format(path, error.value) - ) - - # Extract the number of channels in the newly opened file - #: Number of channels in audio file. - self.channels = opus.op_channel_count(of, -1) - - # Allocate sufficient memory to store the entire PCM - pcm_size = opus.op_pcm_total(of, -1) - Buf = opus.opus_int16*(pcm_size*self.channels) - buf = Buf() - - # Create a pointer to the newly allocated memory. It - # seems we can only do pointer arithmetic on void - # pointers. See - # https://mattgwwalker.wordpress.com/2020/05/30/pointer-manipulation-in-python/ - buf_ptr = ctypes.cast( - ctypes.pointer(buf), - ctypes.c_void_p - ) - assert buf_ptr.value is not None # for mypy - buf_ptr_zero = buf_ptr.value - - #: Bytes per sample - self.bytes_per_sample = ctypes.sizeof(opus.opus_int16) - - # Read through the entire file, copying the PCM into the - # buffer - samples = 0 - while True: - # Calculate remaining buffer size - remaining_buffer = ( - len(buf) # int - - (buf_ptr.value - - buf_ptr_zero) // self.bytes_per_sample - ) - - # Convert buffer pointer to the desired type - ptr = ctypes.cast( - buf_ptr, - ctypes.POINTER(opus.opus_int16) - ) - - # Read the next section of PCM - ns = opus.op_read( - of, - ptr, - remaining_buffer, - ogg.c_int_p() - ) - - # Check for errors - if ns<0: - raise PyOggError( - "Error while reading OggOpus file. "+ - "Error code: {}".format(ns) - ) - - # Increment the pointer - buf_ptr.value += ( - ns - * self.bytes_per_sample - * self.channels - ) - assert buf_ptr.value is not None # for mypy - - samples += ns - - # Check if we've finished - if ns==0: - break - - # Close the open file - opus.op_free(of) - - # Opus files are always stored at 48k samples per second - #: Number of samples per second (per channel). Always 48,000. - self.frequency = 48000 - - # Cast buffer to a one-dimensional array of chars - #: Raw PCM data from audio file. - CharBuffer = ( - ctypes.c_byte - * (self.bytes_per_sample * self.channels * pcm_size) - ) - self.buffer = CharBuffer.from_buffer(buf) diff --git a/sbapp/pyogg/opus_file_stream.py b/sbapp/pyogg/opus_file_stream.py deleted file mode 100644 index b3e1723..0000000 --- a/sbapp/pyogg/opus_file_stream.py +++ /dev/null @@ -1,127 +0,0 @@ -import ctypes - -from . import ogg -from . import opus -from .pyogg_error import PyOggError - -class OpusFileStream: - def __init__(self, path): - """Opens an OggOpus file as a stream. - - path should be a string giving the filename of the file to - open. Unicode file names may not work correctly. - - An exception will be raised if the file cannot be opened - correctly. - - """ - error = ctypes.c_int() - - self.of = opus.op_open_file(ogg.to_char_p(path), ctypes.pointer(error)) - - if error.value != 0: - self.of = None - raise PyOggError("file couldn't be opened or doesn't exist. Error code : {}".format(error.value)) - - #: Number of channels in audio file - self.channels = opus.op_channel_count(self.of, -1) - - #: Total PCM Length - self.pcm_size = opus.op_pcm_total(self.of, -1) - - #: Number of samples per second (per channel) - self.frequency = 48000 - - # The buffer size should be (per channel) large enough to - # hold 120ms (the largest possible Opus frame) at 48kHz. - # See https://opus-codec.org/docs/opusfile_api-0.7/group__stream__decoding.html#ga963c917749335e29bb2b698c1cb20a10 - self.buffer_size = self.frequency // 1000 * 120 * self.channels - self.Buf = opus.opus_int16 * self.buffer_size - self._buf = self.Buf() - self.buffer_ptr = ctypes.cast( - ctypes.pointer(self._buf), - opus.opus_int16_p - ) - - #: Bytes per sample - self.bytes_per_sample = ctypes.sizeof(opus.opus_int16) - - def __del__(self): - if self.of is not None: - opus.op_free(self.of) - - def get_buffer(self): - """Obtains the next frame of PCM samples. - - Returns an array of signed 16-bit integers. If the file - is in stereo, the left and right channels are interleaved. - - Returns None when all data has been read. - - The array that is returned should be either processed or - copied before the next call to :meth:`~get_buffer` or - :meth:`~get_buffer_as_array` as the array's memory is reused for - each call. - - """ - # Read the next frame - samples_read = opus.op_read( - self.of, - self.buffer_ptr, - self.buffer_size, - None - ) - - # Check for errors - if samples_read < 0: - raise PyOggError( - "Failed to read OpusFileStream. Error {:d}".format(samples_read) - ) - - # Check if we've reached the end of the stream - if samples_read == 0: - return None - - # Cast the pointer to opus_int16 to an array of the - # correct size - result_ptr = ctypes.cast( - self.buffer_ptr, - ctypes.POINTER(opus.opus_int16 * (samples_read*self.channels)) - ) - - # Convert the array to Python bytes - return bytes(result_ptr.contents) - - def get_buffer_as_array(self): - """Provides the buffer as a NumPy array. - - Note that the underlying data type is 16-bit signed - integers. - - Does not copy the underlying data, so the returned array - should either be processed or copied before the next call - to :meth:`~get_buffer` or :meth:`~get_buffer_as_array`. - - """ - import numpy # type: ignore - - # Read the next samples from the stream - buf = self.get_buffer() - - # Check if we've come to the end of the stream - if buf is None: - return None - - # Convert the bytes buffer to a NumPy array - array = numpy.frombuffer( - buf, - dtype=numpy.int16 - ) - - # Reshape the array - return array.reshape( - (len(buf) - // self.bytes_per_sample - // self.channels, - self.channels) - ) diff --git a/sbapp/pyogg/py.typed b/sbapp/pyogg/py.typed deleted file mode 100644 index d4defd9..0000000 --- a/sbapp/pyogg/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. This package uses inline types. \ No newline at end of file diff --git a/sbapp/pyogg/pyogg_error.py b/sbapp/pyogg/pyogg_error.py deleted file mode 100644 index 35f28bf..0000000 --- a/sbapp/pyogg/pyogg_error.py +++ /dev/null @@ -1,2 +0,0 @@ -class PyOggError(Exception): - pass diff --git a/sbapp/pyogg/vorbis.py b/sbapp/pyogg/vorbis.py deleted file mode 100644 index a8432ba..0000000 --- a/sbapp/pyogg/vorbis.py +++ /dev/null @@ -1,855 +0,0 @@ -############################################################ -# Vorbis license: # -############################################################ -""" -Copyright (c) 2002-2015 Xiph.org Foundation - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -- Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -- Neither the name of the Xiph.org Foundation nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - -import ctypes -import ctypes.util -from traceback import print_exc as _print_exc -import os - -OV_EXCLUDE_STATIC_CALLBACKS = False - -__MINGW32__ = False - -_WIN32 = False - -from .ogg import * - -from .library_loader import ExternalLibrary, ExternalLibraryError - -__here = os.getcwd() - -libvorbis = None - -try: - names = { - "Windows": "libvorbis.dll", - "Darwin": "libvorbis.0.dylib", - "external": "vorbis" - } - libvorbis = Library.load(names, tests = [lambda lib: hasattr(lib, "vorbis_info_init")]) -except ExternalLibraryError: - pass -except: - _print_exc() - -libvorbisfile = None - -try: - names = { - "Windows": "libvorbisfile.dll", - "Darwin": "libvorbisfile.3.dylib", - "external": "vorbisfile" - } - libvorbisfile = Library.load(names, tests = [lambda lib: hasattr(lib, "ov_clear")]) -except ExternalLibraryError: - pass -except: - _print_exc() - -libvorbisenc = None - -# In some cases, libvorbis may also have the libvorbisenc functionality. -libvorbis_is_also_libvorbisenc = True - -for f in ("vorbis_encode_ctl", - "vorbis_encode_init", - "vorbis_encode_init_vbr", - "vorbis_encode_setup_init", - "vorbis_encode_setup_managed", - "vorbis_encode_setup_vbr"): - if not hasattr(libvorbis, f): - libvorbis_is_also_libvorbisenc = False - break - -if libvorbis_is_also_libvorbisenc: - libvorbisenc = libvorbis -else: - try: - names = { - "Windows": "libvorbisenc.dll", - "Darwin": "libvorbisenc.2.dylib", - "external": "vorbisenc" - } - libvorbisenc = Library.load(names, tests = [lambda lib: hasattr(lib, "vorbis_encode_init")]) - except ExternalLibraryError: - pass - except: - _print_exc() - -if libvorbis is None: - PYOGG_VORBIS_AVAIL = False -else: - PYOGG_VORBIS_AVAIL = True - -if libvorbisfile is None: - PYOGG_VORBIS_FILE_AVAIL = False -else: - PYOGG_VORBIS_FILE_AVAIL = True - -if libvorbisenc is None: - PYOGG_VORBIS_ENC_AVAIL = False -else: - PYOGG_VORBIS_ENC_AVAIL = True - -# FIXME: What's the story with the lack of checking for PYOGG_VORBIS_ENC_AVAIL? -# We just seem to assume that it's available. - -if PYOGG_OGG_AVAIL and PYOGG_VORBIS_AVAIL and PYOGG_VORBIS_FILE_AVAIL: - # Sanity check also satisfies mypy type checking - assert libogg is not None - assert libvorbis is not None - assert libvorbisfile is not None - - - # codecs - class vorbis_info(ctypes.Structure): - """ - Wrapper for: - typedef struct vorbis_info vorbis_info; - """ - _fields_ = [("version", c_int), - ("channels", c_int), - ("rate", c_long), - - ("bitrate_upper", c_long), - ("bitrate_nominal", c_long), - ("bitrate_lower", c_long), - ("bitrate_window", c_long), - ("codec_setup", c_void_p)] - - - - class vorbis_dsp_state(ctypes.Structure): - """ - Wrapper for: - typedef struct vorbis_dsp_state vorbis_dsp_state; - """ - _fields_ = [("analysisp", c_int), - ("vi", POINTER(vorbis_info)), - ("pcm", c_float_p_p), - ("pcmret", c_float_p_p), - ("pcm_storage", c_int), - ("pcm_current", c_int), - ("pcm_returned", c_int), - - ("preextrapolate", c_int), - ("eofflag", c_int), - - ("lW", c_long), - ("W", c_long), - ("nW", c_long), - ("centerW", c_long), - - ("granulepos", ogg_int64_t), - ("sequence", ogg_int64_t), - - ("glue_bits", ogg_int64_t), - ("time_bits", ogg_int64_t), - ("floor_bits", ogg_int64_t), - ("res_bits", ogg_int64_t), - - ("backend_state", c_void_p)] - - class alloc_chain(ctypes.Structure): - """ - Wrapper for: - typedef struct alloc_chain; - """ - pass - - alloc_chain._fields_ = [("ptr", c_void_p), - ("next", POINTER(alloc_chain))] - - class vorbis_block(ctypes.Structure): - """ - Wrapper for: - typedef struct vorbis_block vorbis_block; - """ - _fields_ = [("pcm", c_float_p_p), - ("opb", oggpack_buffer), - ("lW", c_long), - ("W", c_long), - ("nW", c_long), - ("pcmend", c_int), - ("mode", c_int), - - ("eofflag", c_int), - ("granulepos", ogg_int64_t), - ("sequence", ogg_int64_t), - ("vd", POINTER(vorbis_dsp_state)), - - ("localstore", c_void_p), - ("localtop", c_long), - ("localalloc", c_long), - ("totaluse", c_long), - ("reap", POINTER(alloc_chain)), - - ("glue_bits", c_long), - ("time_bits", c_long), - ("floor_bits", c_long), - ("res_bits", c_long), - - ("internal", c_void_p)] - - class vorbis_comment(ctypes.Structure): - """ - Wrapper for: - typedef struct vorbis_comment vorbis_comment; - """ - _fields_ = [("user_comments", c_char_p_p), - ("comment_lengths", c_int_p), - ("comments", c_int), - ("vendor", c_char_p)] - - - - vi_p = POINTER(vorbis_info) - vc_p = POINTER(vorbis_comment) - vd_p = POINTER(vorbis_dsp_state) - vb_p = POINTER(vorbis_block) - - libvorbis.vorbis_info_init.restype = None - libvorbis.vorbis_info_init.argtypes = [vi_p] - def vorbis_info_init(vi): - libvorbis.vorbis_info_init(vi) - - libvorbis.vorbis_info_clear.restype = None - libvorbis.vorbis_info_clear.argtypes = [vi_p] - def vorbis_info_clear(vi): - libvorbis.vorbis_info_clear(vi) - - libvorbis.vorbis_info_blocksize.restype = c_int - libvorbis.vorbis_info_blocksize.argtypes = [vi_p, c_int] - def vorbis_info_blocksize(vi, zo): - return libvorbis.vorbis_info_blocksize(vi, zo) - - libvorbis.vorbis_comment_init.restype = None - libvorbis.vorbis_comment_init.argtypes = [vc_p] - def vorbis_comment_init(vc): - libvorbis.vorbis_comment_init(vc) - - libvorbis.vorbis_comment_add.restype = None - libvorbis.vorbis_comment_add.argtypes = [vc_p, c_char_p] - def vorbis_comment_add(vc, comment): - libvorbis.vorbis_comment_add(vc, comment) - - libvorbis.vorbis_comment_add_tag.restype = None - libvorbis.vorbis_comment_add_tag.argtypes = [vc_p, c_char_p, c_char_p] - def vorbis_comment_add_tag(vc, tag, comment): - libvorbis.vorbis_comment_add_tag(vc, tag, comment) - - libvorbis.vorbis_comment_query.restype = c_char_p - libvorbis.vorbis_comment_query.argtypes = [vc_p, c_char_p, c_int] - def vorbis_comment_query(vc, tag, count): - libvorbis.vorbis_comment_query(vc, tag, count) - - libvorbis.vorbis_comment_query_count.restype = c_int - libvorbis.vorbis_comment_query_count.argtypes = [vc_p, c_char_p] - def vorbis_comment_query_count(vc, tag): - libvorbis.vorbis_comment_query_count(vc, tag) - - libvorbis.vorbis_comment_clear.restype = None - libvorbis.vorbis_comment_clear.argtypes = [vc_p] - def vorbis_comment_clear(vc): - libvorbis.vorbis_comment_clear(vc) - - - - libvorbis.vorbis_block_init.restype = c_int - libvorbis.vorbis_block_init.argtypes = [vd_p, vb_p] - def vorbis_block_init(v,vb): - return libvorbis.vorbis_block_init(v,vb) - - libvorbis.vorbis_block_clear.restype = c_int - libvorbis.vorbis_block_clear.argtypes = [vb_p] - def vorbis_block_clear(vb): - return libvorbis.vorbis_block_clear(vb) - - libvorbis.vorbis_dsp_clear.restype = None - libvorbis.vorbis_dsp_clear.argtypes = [vd_p] - def vorbis_dsp_clear(v): - return libvorbis.vorbis_dsp_clear(v) - - libvorbis.vorbis_granule_time.restype = c_double - libvorbis.vorbis_granule_time.argtypes = [vd_p, ogg_int64_t] - def vorbis_granule_time(v, granulepos): - return libvorbis.vorbis_granule_time(v, granulepos) - - - - libvorbis.vorbis_version_string.restype = c_char_p - libvorbis.vorbis_version_string.argtypes = [] - def vorbis_version_string(): - return libvorbis.vorbis_version_string() - - - - - - libvorbis.vorbis_analysis_init.restype = c_int - libvorbis.vorbis_analysis_init.argtypes = [vd_p, vi_p] - def vorbis_analysis_init(v, vi): - return libvorbis.vorbis_analysis_init(v, vi) - - libvorbis.vorbis_commentheader_out.restype = c_int - libvorbis.vorbis_commentheader_out.argtypes = [vc_p, op_p] - def vorbis_commentheader_out(vc, op): - return libvorbis.vorbis_commentheader_out(vc, op) - - libvorbis.vorbis_analysis_headerout.restype = c_int - libvorbis.vorbis_analysis_headerout.argtypes = [vd_p, vc_p, op_p, op_p, op_p] - def vorbis_analysis_headerout(v,vc, op, op_comm, op_code): - return libvorbis.vorbis_analysis_headerout(v,vc, op, op_comm, op_code) - - libvorbis.vorbis_analysis_buffer.restype = c_float_p_p - libvorbis.vorbis_analysis_buffer.argtypes = [vd_p, c_int] - def vorbis_analysis_buffer(v, vals): - return libvorbis.vorbis_analysis_buffer(v, vals) - - libvorbis.vorbis_analysis_wrote.restype = c_int - libvorbis.vorbis_analysis_wrote.argtypes = [vd_p, c_int] - def vorbis_analysis_wrote(v, vals): - return libvorbis.vorbis_analysis_wrote(v, vals) - - libvorbis.vorbis_analysis_blockout.restype = c_int - libvorbis.vorbis_analysis_blockout.argtypes = [vd_p, vb_p] - def vorbis_analysis_blockout(v, vb): - return libvorbis.vorbis_analysis_blockout(v, vb) - - libvorbis.vorbis_analysis.restype = c_int - libvorbis.vorbis_analysis.argtypes = [vb_p, op_p] - def vorbis_analysis(vb, op): - return libvorbis.vorbis_analysis(vb, op) - - - - - libvorbis.vorbis_bitrate_addblock.restype = c_int - libvorbis.vorbis_bitrate_addblock.argtypes = [vb_p] - def vorbis_bitrate_addblock(vb): - return libvorbis.vorbis_bitrate_addblock(vb) - - libvorbis.vorbis_bitrate_flushpacket.restype = c_int - libvorbis.vorbis_bitrate_flushpacket.argtypes = [vd_p, op_p] - def vorbis_bitrate_flushpacket(vd, op): - return libvorbis.vorbis_bitrate_flushpacket(vd, op) - - - - - libvorbis.vorbis_synthesis_idheader.restype = c_int - libvorbis.vorbis_synthesis_idheader.argtypes = [op_p] - def vorbis_synthesis_idheader(op): - return libvorbis.vorbis_synthesis_idheader(op) - - libvorbis.vorbis_synthesis_headerin.restype = c_int - libvorbis.vorbis_synthesis_headerin.argtypes = [vi_p, vc_p, op_p] - def vorbis_synthesis_headerin(vi, vc, op): - return libvorbis.vorbis_synthesis_headerin(vi, vc, op) - - - - - libvorbis.vorbis_synthesis_init.restype = c_int - libvorbis.vorbis_synthesis_init.argtypes = [vd_p, vi_p] - def vorbis_synthesis_init(v,vi): - return libvorbis.vorbis_synthesis_init(v,vi) - - libvorbis.vorbis_synthesis_restart.restype = c_int - libvorbis.vorbis_synthesis_restart.argtypes = [vd_p] - def vorbis_synthesis_restart(v): - return libvorbis.vorbis_synthesis_restart(v) - - libvorbis.vorbis_synthesis.restype = c_int - libvorbis.vorbis_synthesis.argtypes = [vb_p, op_p] - def vorbis_synthesis(vb, op): - return libvorbis.vorbis_synthesis(vb, op) - - libvorbis.vorbis_synthesis_trackonly.restype = c_int - libvorbis.vorbis_synthesis_trackonly.argtypes = [vb_p, op_p] - def vorbis_synthesis_trackonly(vb, op): - return libvorbis.vorbis_synthesis_trackonly(vb, op) - - libvorbis.vorbis_synthesis_blockin.restype = c_int - libvorbis.vorbis_synthesis_blockin.argtypes = [vd_p, vb_p] - def vorbis_synthesis_blockin(v, vb): - return libvorbis.vorbis_synthesis_blockin(v, vb) - - libvorbis.vorbis_synthesis_pcmout.restype = c_int - libvorbis.vorbis_synthesis_pcmout.argtypes = [vd_p, c_float_p_p_p] - def vorbis_synthesis_pcmout(v, pcm): - return libvorbis.vorbis_synthesis_pcmout(v, pcm) - - libvorbis.vorbis_synthesis_lapout.restype = c_int - libvorbis.vorbis_synthesis_lapout.argtypes = [vd_p, c_float_p_p_p] - def vorbis_synthesis_lapout(v, pcm): - return libvorbis.vorbis_synthesis_lapout(v, pcm) - - libvorbis.vorbis_synthesis_read.restype = c_int - libvorbis.vorbis_synthesis_read.argtypes = [vd_p, c_int] - def vorbis_synthesis_read(v, samples): - return libvorbis.vorbis_synthesis_read(v, samples) - - libvorbis.vorbis_packet_blocksize.restype = c_long - libvorbis.vorbis_packet_blocksize.argtypes = [vi_p, op_p] - def vorbis_packet_blocksize(vi, op): - return libvorbis.vorbis_packet_blocksize(vi, op) - - - - libvorbis.vorbis_synthesis_halfrate.restype = c_int - libvorbis.vorbis_synthesis_halfrate.argtypes = [vi_p, c_int] - def vorbis_synthesis_halfrate(v, flag): - return libvorbis.vorbis_synthesis_halfrate(v, flag) - - libvorbis.vorbis_synthesis_halfrate_p.restype = c_int - libvorbis.vorbis_synthesis_halfrate_p.argtypes = [vi_p] - def vorbis_synthesis_halfrate_p(vi): - return libvorbis.vorbis_synthesis_halfrate_p(vi) - - OV_FALSE = -1 - OV_EOF = -2 - OV_HOLE = -3 - - OV_EREAD = -128 - OV_EFAULT = -129 - OV_EIMPL =-130 - OV_EINVAL =-131 - OV_ENOTVORBIS =-132 - OV_EBADHEADER =-133 - OV_EVERSION =-134 - OV_ENOTAUDIO =-135 - OV_EBADPACKET =-136 - OV_EBADLINK =-137 - OV_ENOSEEK =-138 - # end of codecs - - # vorbisfile - read_func = ctypes.CFUNCTYPE(c_size_t, - c_void_p, - c_size_t, - c_size_t, - c_void_p) - - seek_func = ctypes.CFUNCTYPE(c_int, - c_void_p, - ogg_int64_t, - c_int) - - close_func = ctypes.CFUNCTYPE(c_int, - c_void_p) - - tell_func = ctypes.CFUNCTYPE(c_long, - c_void_p) - - class ov_callbacks(ctypes.Structure): - """ - Wrapper for: - typedef struct ov_callbacks; - """ - - _fields_ = [("read_func", read_func), - ("seek_func", seek_func), - ("close_func", close_func), - ("tell_func", tell_func)] - - NOTOPEN = 0 - PARTOPEN = 1 - OPENED = 2 - STREAMSET = 3 - INITSET = 4 - - class OggVorbis_File(ctypes.Structure): - """ - Wrapper for: - typedef struct OggVorbis_File OggVorbis_File; - """ - - _fields_ = [("datasource", c_void_p), - ("seekable", c_int), - ("offset", ogg_int64_t), - ("end", ogg_int64_t), - ("oy", ogg_sync_state), - - ("links", c_int), - ("offsets", ogg_int64_t_p), - ("dataoffsets", ogg_int64_t_p), - ("serialnos", c_long_p), - ("pcmlengths", ogg_int64_t_p), - ("vi", vi_p), - ("vc", vc_p), - - ("pcm_offset", ogg_int64_t), - ("ready_state", c_int), - ("current_serialno", c_long), - ("current_link", c_int), - - ("bittrack", c_double), - ("samptrack", c_double), - - ("os", ogg_stream_state), - - ("vd", vorbis_dsp_state), - ("vb", vorbis_block), - - ("callbacks", ov_callbacks)] - vf_p = POINTER(OggVorbis_File) - - libvorbisfile.ov_clear.restype = c_int - libvorbisfile.ov_clear.argtypes = [vf_p] - - def ov_clear(vf): - return libvorbisfile.ov_clear(vf) - - libvorbisfile.ov_fopen.restype = c_int - libvorbisfile.ov_fopen.argtypes = [c_char_p, vf_p] - - def ov_fopen(path, vf): - return libvorbisfile.ov_fopen(to_char_p(path), vf) - - libvorbisfile.ov_open_callbacks.restype = c_int - libvorbisfile.ov_open_callbacks.argtypes = [c_void_p, vf_p, c_char_p, c_long, ov_callbacks] - - def ov_open_callbacks(datasource, vf, initial, ibytes, callbacks): - return libvorbisfile.ov_open_callbacks(datasource, vf, initial, ibytes, callbacks) - - def ov_open(*args, **kw): - raise PyOggError("ov_open is not supported, please use ov_fopen instead") - - def ov_test(*args, **kw): - raise PyOggError("ov_test is not supported") - - libvorbisfile.ov_test_callbacks.restype = c_int - libvorbisfile.ov_test_callbacks.argtypes = [c_void_p, vf_p, c_char_p, c_long, ov_callbacks] - - def ov_test_callbacks(datasource, vf, initial, ibytes, callbacks): - return libvorbisfile.ov_test_callbacks(datasource, vf, initial, ibytes, callbacks) - - libvorbisfile.ov_test_open.restype = c_int - libvorbisfile.ov_test_open.argtypes = [vf_p] - - def ov_test_open(vf): - return libvorbisfile.ov_test_open(vf) - - - - - libvorbisfile.ov_bitrate.restype = c_long - libvorbisfile.ov_bitrate.argtypes = [vf_p, c_int] - - def ov_bitrate(vf, i): - return libvorbisfile.ov_bitrate(vf, i) - - libvorbisfile.ov_bitrate_instant.restype = c_long - libvorbisfile.ov_bitrate_instant.argtypes = [vf_p] - - def ov_bitrate_instant(vf): - return libvorbisfile.ov_bitrate_instant(vf) - - libvorbisfile.ov_streams.restype = c_long - libvorbisfile.ov_streams.argtypes = [vf_p] - - def ov_streams(vf): - return libvorbisfile.ov_streams(vf) - - libvorbisfile.ov_seekable.restype = c_long - libvorbisfile.ov_seekable.argtypes = [vf_p] - - def ov_seekable(vf): - return libvorbisfile.ov_seekable(vf) - - libvorbisfile.ov_serialnumber.restype = c_long - libvorbisfile.ov_serialnumber.argtypes = [vf_p, c_int] - - def ov_serialnumber(vf, i): - return libvorbisfile.ov_serialnumber(vf, i) - - - - libvorbisfile.ov_raw_total.restype = ogg_int64_t - libvorbisfile.ov_raw_total.argtypes = [vf_p, c_int] - - def ov_raw_total(vf, i): - return libvorbisfile.ov_raw_total(vf, i) - - libvorbisfile.ov_pcm_total.restype = ogg_int64_t - libvorbisfile.ov_pcm_total.argtypes = [vf_p, c_int] - - def ov_pcm_total(vf, i): - return libvorbisfile.ov_pcm_total(vf, i) - - libvorbisfile.ov_time_total.restype = c_double - libvorbisfile.ov_time_total.argtypes = [vf_p, c_int] - - def ov_time_total(vf, i): - return libvorbisfile.ov_time_total(vf, i) - - - - - libvorbisfile.ov_raw_seek.restype = c_int - libvorbisfile.ov_raw_seek.argtypes = [vf_p, ogg_int64_t] - - def ov_raw_seek(vf, pos): - return libvorbisfile.ov_raw_seek(vf, pos) - - libvorbisfile.ov_pcm_seek.restype = c_int - libvorbisfile.ov_pcm_seek.argtypes = [vf_p, ogg_int64_t] - - def ov_pcm_seek(vf, pos): - return libvorbisfile.ov_pcm_seek(vf, pos) - - libvorbisfile.ov_pcm_seek_page.restype = c_int - libvorbisfile.ov_pcm_seek_page.argtypes = [vf_p, ogg_int64_t] - - def ov_pcm_seek_page(vf, pos): - return libvorbisfile.ov_pcm_seek_page(vf, pos) - - libvorbisfile.ov_time_seek.restype = c_int - libvorbisfile.ov_time_seek.argtypes = [vf_p, c_double] - - def ov_time_seek(vf, pos): - return libvorbisfile.ov_time_seek(vf, pos) - - libvorbisfile.ov_time_seek_page.restype = c_int - libvorbisfile.ov_time_seek_page.argtypes = [vf_p, c_double] - - def ov_time_seek_page(vf, pos): - return libvorbisfile.ov_time_seek_page(vf, pos) - - - - - libvorbisfile.ov_raw_seek_lap.restype = c_int - libvorbisfile.ov_raw_seek_lap.argtypes = [vf_p, ogg_int64_t] - - def ov_raw_seek_lap(vf, pos): - return libvorbisfile.ov_raw_seek_lap(vf, pos) - - libvorbisfile.ov_pcm_seek_lap.restype = c_int - libvorbisfile.ov_pcm_seek_lap.argtypes = [vf_p, ogg_int64_t] - - def ov_pcm_seek_lap(vf, pos): - return libvorbisfile.ov_pcm_seek_lap(vf, pos) - - libvorbisfile.ov_pcm_seek_page_lap.restype = c_int - libvorbisfile.ov_pcm_seek_page_lap.argtypes = [vf_p, ogg_int64_t] - - def ov_pcm_seek_page_lap(vf, pos): - return libvorbisfile.ov_pcm_seek_page_lap(vf, pos) - - libvorbisfile.ov_time_seek_lap.restype = c_int - libvorbisfile.ov_time_seek_lap.argtypes = [vf_p, c_double] - - def ov_time_seek_lap(vf, pos): - return libvorbisfile.ov_time_seek_lap(vf, pos) - - libvorbisfile.ov_time_seek_page_lap.restype = c_int - libvorbisfile.ov_time_seek_page_lap.argtypes = [vf_p, c_double] - - def ov_time_seek_page_lap(vf, pos): - return libvorbisfile.ov_time_seek_page_lap(vf, pos) - - - - libvorbisfile.ov_raw_tell.restype = ogg_int64_t - libvorbisfile.ov_raw_tell.argtypes = [vf_p] - - def ov_raw_tell(vf): - return libvorbisfile.ov_raw_tell(vf) - - libvorbisfile.ov_pcm_tell.restype = ogg_int64_t - libvorbisfile.ov_pcm_tell.argtypes = [vf_p] - - def ov_pcm_tell(vf): - return libvorbisfile.ov_pcm_tell(vf) - - libvorbisfile.ov_time_tell.restype = c_double - libvorbisfile.ov_time_tell.argtypes = [vf_p] - - def ov_time_tell(vf): - return libvorbisfile.ov_time_tell(vf) - - - - libvorbisfile.ov_info.restype = vi_p - libvorbisfile.ov_info.argtypes = [vf_p, c_int] - - def ov_info(vf, link): - return libvorbisfile.ov_info(vf, link) - - libvorbisfile.ov_comment.restype = vc_p - libvorbisfile.ov_comment.argtypes = [vf_p, c_int] - - def ov_comment(vf, link): - return libvorbisfile.ov_comment(vf, link) - - - - libvorbisfile.ov_read_float.restype = c_long - libvorbisfile.ov_read_float.argtypes = [vf_p, c_float_p_p_p, c_int, c_int_p] - - def ov_read_float(vf, pcm_channels, samples, bitstream): - return libvorbisfile.ov_read_float(vf, pcm_channels, samples, bitstream) - - filter_ = ctypes.CFUNCTYPE(None, - c_float_p_p, - c_long, - c_long, - c_void_p) - - try: - libvorbisfile.ov_read_filter.restype = c_long - libvorbisfile.ov_read_filter.argtypes = [vf_p, c_char_p, c_int, c_int, c_int, c_int, c_int_p, filter_, c_void_p] - - def ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, filter_, filter_param): - return libvorbisfile.ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, filter_, filter_param) - except: - pass - - libvorbisfile.ov_read.restype = c_long - libvorbisfile.ov_read.argtypes = [vf_p, c_char_p, c_int, c_int, c_int, c_int, c_int_p] - - def ov_read(vf, buffer, length, bigendianp, word, sgned, bitstream): - return libvorbisfile.ov_read(vf, buffer, length, bigendianp, word, sgned, bitstream) - - libvorbisfile.ov_crosslap.restype = c_int - libvorbisfile.ov_crosslap.argtypes = [vf_p, vf_p] - - def ov_crosslap(vf1, cf2): - return libvorbisfile.ov_crosslap(vf1, vf2) - - - - - libvorbisfile.ov_halfrate.restype = c_int - libvorbisfile.ov_halfrate.argtypes = [vf_p, c_int] - - def ov_halfrate(vf, flag): - return libvorbisfile.ov_halfrate(vf, flag) - - libvorbisfile.ov_halfrate_p.restype = c_int - libvorbisfile.ov_halfrate_p.argtypes = [vf_p] - - def ov_halfrate_p(vf): - return libvorbisfile.ov_halfrate_p(vf) - # end of vorbisfile - - try: - # vorbisenc - - # Sanity check also satisfies mypy type checking - assert libvorbisenc is not None - - libvorbisenc.vorbis_encode_init.restype = c_int - libvorbisenc.vorbis_encode_init.argtypes = [vi_p, c_long, c_long, c_long, c_long, c_long] - - def vorbis_encode_init(vi, channels, rate, max_bitrate, nominal_bitrate, min_bitrate): - return libvorbisenc.vorbis_encode_init(vi, channels, rate, max_bitrate, nominal_bitrate, min_bitrate) - - libvorbisenc.vorbis_encode_setup_managed.restype = c_int - libvorbisenc.vorbis_encode_setup_managed.argtypes = [vi_p, c_long, c_long, c_long, c_long, c_long] - - def vorbis_encode_setup_managed(vi, channels, rate, max_bitrate, nominal_bitrate, min_bitrate): - return libvorbisenc.vorbis_encode_setup_managed(vi, channels, rate, max_bitrate, nominal_bitrate, min_bitrate) - - libvorbisenc.vorbis_encode_setup_vbr.restype = c_int - libvorbisenc.vorbis_encode_setup_vbr.argtypes = [vi_p, c_long, c_long, c_float] - - def vorbis_encode_setup_vbr(vi, channels, rate, quality): - return libvorbisenc.vorbis_encode_setup_vbr(vi, channels, rate, quality) - - libvorbisenc.vorbis_encode_init_vbr.restype = c_int - libvorbisenc.vorbis_encode_init_vbr.argtypes = [vi_p, c_long, c_long, c_float] - - def vorbis_encode_init_vbr(vi, channels, rate, quality): - return libvorbisenc.vorbis_encode_init_vbr(vi, channels, rate, quality) - - libvorbisenc.vorbis_encode_setup_init.restype = c_int - libvorbisenc.vorbis_encode_setup_init.argtypes = [vi_p] - - def vorbis_encode_setup_init(vi): - return libvorbisenc.vorbis_encode_setup_init(vi) - - libvorbisenc.vorbis_encode_ctl.restype = c_int - libvorbisenc.vorbis_encode_ctl.argtypes = [vi_p, c_int, c_void_p] - - def vorbis_encode_ctl(vi, number, arg): - return libvorbisenc.vorbis_encode_ctl(vi, number, arg) - - class ovectl_ratemanage_arg(ctypes.Structure): - _fields_ = [("management_active", c_int), - ("bitrate_hard_min", c_long), - ("bitrate_hard_max", c_long), - ("bitrate_hard_window", c_double), - ("bitrate_av_lo", c_long), - ("bitrate_av_hi", c_long), - ("bitrate_av_window", c_double), - ("bitrate_av_window_center", c_double)] - - class ovectl_ratemanage2_arg(ctypes.Structure): - _fields_ = [("management_active", c_int), - ("bitrate_limit_min_kbps", c_long), - ("bitrate_limit_max_kbps", c_long), - ("bitrate_limit_reservoir_bits", c_long), - ("bitrate_limit_reservoir_bias", c_double), - ("bitrate_average_kbps", c_long), - ("bitrate_average_damping", c_double)] - - OV_ECTL_RATEMANAGE2_GET =0x14 - - OV_ECTL_RATEMANAGE2_SET =0x15 - - OV_ECTL_LOWPASS_GET =0x20 - - OV_ECTL_LOWPASS_SET =0x21 - - OV_ECTL_IBLOCK_GET =0x30 - - OV_ECTL_IBLOCK_SET =0x31 - - OV_ECTL_COUPLING_GET =0x40 - - OV_ECTL_COUPLING_SET =0x41 - - OV_ECTL_RATEMANAGE_GET =0x10 - - OV_ECTL_RATEMANAGE_SET =0x11 - - OV_ECTL_RATEMANAGE_AVG =0x12 - - OV_ECTL_RATEMANAGE_HARD =0x13 - # end of vorbisenc - except: - pass diff --git a/sbapp/pyogg/vorbis_file.py b/sbapp/pyogg/vorbis_file.py deleted file mode 100644 index 918f1e8..0000000 --- a/sbapp/pyogg/vorbis_file.py +++ /dev/null @@ -1,161 +0,0 @@ -import ctypes - -from . import vorbis -from .audio_file import AudioFile -from .pyogg_error import PyOggError - -# TODO: Issue #70: Vorbis files with multiple logical bitstreams could -# be supported by chaining VorbisFile instances (with say a 'next' -# attribute that points to the next VorbisFile that would contain the -# PCM for the next logical bitstream). A considerable constraint to -# implementing this was that examples files that demonstrated multiple -# logical bitstreams couldn't be found or created. Note that even -# Audacity doesn't handle multiple logical bitstreams (see -# https://wiki.audacityteam.org/wiki/OGG#Importing_multiple_stream_files). - -# TODO: Issue #53: Unicode file names are not well supported. -# They may work in macOS and Linux, they don't work under Windows. - -class VorbisFile(AudioFile): - def __init__(self, - path: str, - bytes_per_sample: int = 2, - signed:bool = True) -> None: - """Load an OggVorbis File. - - path specifies the location of the Vorbis file. Unicode - filenames may not work correctly under Windows. - - bytes_per_sample specifies the word size of the PCM. It may - be either 1 or 2. Specifying one byte per sample will save - memory but will likely decrease the quality of the decoded - audio. - - Only Vorbis files with a single logical bitstream are - supported. - - """ - # Sanity check the number of bytes per sample - assert bytes_per_sample==1 or bytes_per_sample==2 - - # Sanity check that the vorbis library is available (for mypy) - assert vorbis.libvorbisfile is not None - - #: Bytes per sample - self.bytes_per_sample = bytes_per_sample - - #: Samples are signed (rather than unsigned) - self.signed = signed - - # Create a Vorbis File structure - vf = vorbis.OggVorbis_File() - - # Attempt to open the Vorbis file - error = vorbis.libvorbisfile.ov_fopen( - vorbis.to_char_p(path), - ctypes.byref(vf) - ) - - # Check for errors during opening - if error != 0: - raise PyOggError( - ("File '{}' couldn't be opened or doesn't exist. "+ - "Error code : {}").format(path, error) - ) - - # Extract info from the Vorbis file - info = vorbis.libvorbisfile.ov_info( - ctypes.byref(vf), - -1 # the current logical bitstream - ) - - #: Number of channels in audio file. - self.channels = info.contents.channels - - #: Number of samples per second (per channel), 44100 for - # example. - self.frequency = info.contents.rate - - # Extract the total number of PCM samples for the first - # logical bitstream - pcm_length_samples = vorbis.libvorbisfile.ov_pcm_total( - ctypes.byref(vf), - 0 # to extract the length of the first logical bitstream - ) - - # Create a memory block to store the entire PCM - Buffer = ( - ctypes.c_char - * ( - pcm_length_samples - * self.bytes_per_sample - * self.channels - ) - ) - self.buffer = Buffer() - - # Create a pointer to the newly allocated memory. It - # seems we can only do pointer arithmetic on void - # pointers. See - # https://mattgwwalker.wordpress.com/2020/05/30/pointer-manipulation-in-python/ - buf_ptr = ctypes.cast( - ctypes.pointer(self.buffer), - ctypes.c_void_p - ) - - # Storage for the index of the logical bitstream - bitstream_previous = None - bitstream = ctypes.c_int() - - # Set bytes remaining to read into PCM - read_size = len(self.buffer) - - while True: - # Convert buffer pointer to the desired type - ptr = ctypes.cast( - buf_ptr, - ctypes.POINTER(ctypes.c_char) - ) - - # Attempt to decode PCM from the Vorbis file - result = vorbis.libvorbisfile.ov_read( - ctypes.byref(vf), - ptr, - read_size, - 0, # Little endian - self.bytes_per_sample, - int(self.signed), - ctypes.byref(bitstream) - ) - - # Check for errors - if result < 0: - raise PyOggError( - "An error occurred decoding the Vorbis file: "+ - f"Error code: {result}" - ) - - # Check that the bitstream hasn't changed as we only - # support Vorbis files with a single logical bitstream. - if bitstream_previous is None: - bitstream_previous = bitstream - else: - if bitstream_previous != bitstream: - raise PyOggError( - "PyOgg currently supports Vorbis files "+ - "with only one logical stream" - ) - - # Check for end of file - if result == 0: - break - - # Calculate the number of bytes remaining to read into PCM - read_size -= result - - # Update the pointer into the buffer - buf_ptr.value += result - - - # Close the file and clean up memory - vorbis.libvorbisfile.ov_clear(ctypes.byref(vf)) diff --git a/sbapp/pyogg/vorbis_file_stream.py b/sbapp/pyogg/vorbis_file_stream.py deleted file mode 100644 index 57677ba..0000000 --- a/sbapp/pyogg/vorbis_file_stream.py +++ /dev/null @@ -1,110 +0,0 @@ -import ctypes - -from . import vorbis -from .pyogg_error import PyOggError - -class VorbisFileStream: - def __init__(self, path, buffer_size=8192): - self.exists = False - self._buffer_size = buffer_size - - self.vf = vorbis.OggVorbis_File() - error = vorbis.ov_fopen(path, ctypes.byref(self.vf)) - if error != 0: - raise PyOggError("file couldn't be opened or doesn't exist. Error code : {}".format(error)) - - info = vorbis.ov_info(ctypes.byref(self.vf), -1) - - #: Number of channels in audio file. - self.channels = info.contents.channels - - #: Number of samples per second (per channel). Always - # 48,000. - self.frequency = info.contents.rate - - array = (ctypes.c_char*(self._buffer_size*self.channels))() - - self.buffer_ = ctypes.cast(ctypes.pointer(array), ctypes.c_char_p) - - self.bitstream = ctypes.c_int() - self.bitstream_pointer = ctypes.pointer(self.bitstream) - - self.exists = True # TODO: is this the best place for this statement? - - #: Bytes per sample - self.bytes_per_sample = 2 # TODO: Where is this defined? - - def __del__(self): - if self.exists: - vorbis.ov_clear(ctypes.byref(self.vf)) - self.exists = False - - def clean_up(self): - vorbis.ov_clear(ctypes.byref(self.vf)) - - self.exists = False - - def get_buffer(self): - """get_buffer() -> bytesBuffer, bufferLength - - Returns None when all data has been read from the file. - - """ - if not self.exists: - return None - buffer = [] - total_bytes_written = 0 - - while True: - new_bytes = vorbis.ov_read(ctypes.byref(self.vf), self.buffer_, self._buffer_size*self.channels - total_bytes_written, 0, 2, 1, self.bitstream_pointer) - - array_ = ctypes.cast(self.buffer_, ctypes.POINTER(ctypes.c_char*(self._buffer_size*self.channels))).contents - - buffer.append(array_.raw[:new_bytes]) - - total_bytes_written += new_bytes - - if new_bytes == 0 or total_bytes_written >= self._buffer_size*self.channels: - break - - out_buffer = b"".join(buffer) - - if total_bytes_written == 0: - self.clean_up() - return(None) - - return out_buffer - - def get_buffer_as_array(self): - """Provides the buffer as a NumPy array. - - Note that the underlying data type is 16-bit signed - integers. - - Does not copy the underlying data, so the returned array - should either be processed or copied before the next call - to get_buffer() or get_buffer_as_array(). - - """ - import numpy # type: ignore - - # Read the next samples from the stream - buf = self.get_buffer() - - # Check if we've come to the end of the stream - if buf is None: - return None - - # Convert the bytes buffer to a NumPy array - array = numpy.frombuffer( - buf, - dtype=numpy.int16 - ) - - # Reshape the array - return array.reshape( - (len(buf) - // self.bytes_per_sample - // self.channels, - self.channels) - ) From dfbe58621fcdd51731690ce1045730e2f59855a2 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 14:01:59 +0100 Subject: [PATCH 208/271] Cleanup --- sbapp/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 0fdffbd..95643fa 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -3187,9 +3187,9 @@ class SidebandApp(MDApp): self.information_screen.ids.information_scrollview.effect_cls = ScrollEffect self.information_screen.ids.information_logo.icon = os.path.join(self.sideband.asset_dir, "rns_256.png") - str_comps = " - [b]Reticulum[/b] (Reticulum License)\n - [b]LXMF[/b] (Reticulum 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]Able[/b] (MIT License)" + str_comps = " - [b]Reticulum[/b] (Reticulum License)\n - [b]LXMF[/b] (Reticulum License)\n - [b]LXST[/b] (Reticulum License)" + str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" + str_comps += "\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)\n - [b]Able[/b] (MIT 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+"\nRunning on RNS v"+RNS.__version__+", LXMF v"+LXMF.__version__+" and LXST v"+lxst_version+".\n\nHumbly build using the following open components:\n\n"+str_comps From bed2c760e6ef09e8e26f38e52078846d41a7af7b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 14:43:10 +0100 Subject: [PATCH 209/271] Updated readme --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 114ed01..83636c0 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,15 @@ pip3 install sbapp --user # Or, if your Python environment is externally managed: pip3 install sbapp --user --break-system-packages +# Important note! On some macOS versions, programs that +# were installed with pip does not get added to your +# PATH environment variable. If this is the case, pip +# will print out a warning about it during installation. +# In that case, you will have to manually add the path +# shown in the installation warning to your PATH, before +# you can run commands such as "sideband" or "rnstatus" +# from your shell. + # Run Sideband from the terminal: ################################# sideband From 18d180e3a10890811ac8d712ced4c1a678b39048 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 15:17:55 +0100 Subject: [PATCH 210/271] Updated dependency --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 58970b3..39550cf 100644 --- a/setup.py +++ b/setup.py @@ -116,7 +116,7 @@ setuptools.setup( install_requires=[ "rns>=1.0.4", "lxmf>=0.9.3", - "lxst>=0.4.4", + "lxst>=0.4.5", "kivy>=2.3.0", "numpy>=2.0.0", "pillow>=10.2.0", From 13fb3b299e20356da4b93c07fd6aca208a6b4a71 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 22:56:29 +0100 Subject: [PATCH 211/271] Automated builds for Windows --- Makefile | 43 +++++++++++++++++++++++++++++++++++++---- sbapp/Makefile | 8 ++++---- sbapp/share/guides.html | 1 - winbuild.bat | 16 +++++++++++++++ 4 files changed, 59 insertions(+), 9 deletions(-) create mode 100644 winbuild.bat diff --git a/Makefile b/Makefile index 7b08d25..5da567d 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,5 @@ +include environment + devapk: make -C sbapp devapk @@ -43,10 +45,43 @@ preparewheel: compile_wheel: python3 setup.py bdist_wheel -build_wheel: remove_symlinks compile_wheel create_symlinks +compile_sourcepkg: + python3 setup.py sdist -build_win_exe: - python -m PyInstaller sideband.spec --noconfirm +update_share: + $(MAKE) -C sbapp fetchshare + +build_wheel: remove_symlinks update_share compile_wheel create_symlinks + +build_spkg: remove_symlinks update_share compile_sourcepkg create_symlinks + +prepare_win_pkg: clean build_spkg + -rm -r build/winpkg + mkdir -p build/winpkg + LC_ALL=C $(MAKE) -C ../Reticulum clean build_spkg + cp ../Reticulum/dist/rns-*.*.*.tar.gz build/winpkg + cd build/winpkg; tar -zxf rns-*.*.*.tar.gz + mv build/winpkg/rns-*.*.*/RNS build/winpkg; rm -r build/winpkg/rns-*.*.* + LC_ALL=C $(MAKE) -C ../LXMF clean build_spkg + cp ../LXMF/dist/lxmf-*.*.*.tar.gz build/winpkg + cd build/winpkg; tar -zxf lxmf-*.*.*.tar.gz + mv build/winpkg/lxmf-*.*.*/LXMF build/winpkg; rm -r build/winpkg/lxmf-*.*.* + LC_ALL=C $(MAKE) -C ../LXST clean build_spkg + cp ../LXST/dist/lxst-*.*.*.tar.gz build/winpkg + cd build/winpkg; tar -zxf lxst-*.*.*.tar.gz + mv build/winpkg/lxst-*.*.*/LXST build/winpkg; rm -r build/winpkg/lxst-*.*.* + rm build/winpkg/LXST/filterlib*.so + cp dist/sbapp-*.*.*.tar.gz build/winpkg + cd build/winpkg; tar -zxf sbapp-*.*.*.tar.gz + mv build/winpkg/sbapp-*.*.*/* build/winpkg; rm -r build/winpkg/sbapp-*.*.* + rm build/winpkg/LXST/Codecs/libs/pyogg/libs/macos -r + cp winbuild.bat winbuild.ps1 build/ + mv build/winpkg build/sideband_sources + cd build; zip -r winbuild.zip sideband_sources winbuild.bat winbuild.ps1 + mv build/winbuild.zip dist/winbuild.zip + +build_winexe: prepare_win_pkg + cp dist/winbuild.zip $(WINDOWS_BUILD_TARGET) release: build_wheel apk fetchapk @@ -54,4 +89,4 @@ upload: @echo Ready to publish release, hit enter to continue @read VOID @echo Uploading to PyPi... - twine upload dist/sbapp-* \ No newline at end of file + twine upload dist/sbapp-* diff --git a/sbapp/Makefile b/sbapp/Makefile index cb54e64..cda2d7b 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -69,18 +69,18 @@ endif fetchshare: -(rm ./share/pkg/*) -(rm ./share/mirrors/* -r) - cp ../../dist_archive/rns-1.0.3-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/rnspure-1.0.3-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rns-1.0.4-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rnspure-1.0.4-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/lxmf-0.9.3-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/nomadnet-0.9.1-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/rnsh-0.1.7-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/RNode_Firmware_*_Source.zip ./share/pkg/ zip --junk-paths ./share/pkg/example_plugins.zip ../docs/example_plugins/*.py cp -r ../../dist_archive/reticulum.network ./share/mirrors/ - cp -r ../../dist_archive/unsigned.io ./share/mirrors/ cp ../../dist_archive/Reticulum\ Manual.pdf ./share/mirrors/Reticulum_Manual.pdf cp ../../dist_archive/Reticulum\ Manual.epub ./share/mirrors/Reticulum_Manual.epub - cp -r ../../rnode-flasher ./share/mirrors/ + mkdir ./share/mirrors/rnode-flasher + cp ../../rnode-flasher/RNode_Flasher.html ./share/mirrors/rnode-flasher -(rm ./share/mirrors/rnode-flasher/.git -rf) release: diff --git a/sbapp/share/guides.html b/sbapp/share/guides.html index d4cf17a..5e09caf 100644 --- a/sbapp/share/guides.html +++ b/sbapp/share/guides.html @@ -13,7 +13,6 @@ Welcome to the Guide Section!

    From here, you can browse or download various included manuals, documentation, references and guides.
      -
    • Browse a local copy of the Guides from unsigned.io
    • Browse the Reticulum Manual
    • Download the Reticulum Manual in PDF format
    • Download the Reticulum Manual in EPUB format
    • diff --git a/winbuild.bat b/winbuild.bat new file mode 100644 index 0000000..eaf61d4 --- /dev/null +++ b/winbuild.bat @@ -0,0 +1,16 @@ +@echo off +cd sideband_sources\sbapp +for /f "delims=" %%v in ('powershell.exe -Command "python gv.py"') do set version=%%v +cd ..\.. +echo Compiling Sideband %version% + +cd sideband_sources +python -m PyInstaller sideband.spec --noconfirm +cd .. + +set "source_dir=Sideband_%version%" +set "zip_file=Sideband_%version%.zip" +move sideband_sources\dist\main %source_dir% +powershell.exe -Command "Compress-Archive -Path '%source_dir%' -DestinationPath '%zip_file%' -Force" + +echo Build completed \ No newline at end of file From 96aafe0cedb5c3d793909680b66b8a2cdce908d3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 23:11:02 +0100 Subject: [PATCH 212/271] Reduced build size --- Makefile | 6 ++++-- sbapp/Makefile | 2 -- sbapp/share/guides.html | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 5da567d..204a51a 100644 --- a/Makefile +++ b/Makefile @@ -75,9 +75,11 @@ prepare_win_pkg: clean build_spkg cd build/winpkg; tar -zxf sbapp-*.*.*.tar.gz mv build/winpkg/sbapp-*.*.*/* build/winpkg; rm -r build/winpkg/sbapp-*.*.* rm build/winpkg/LXST/Codecs/libs/pyogg/libs/macos -r - cp winbuild.bat winbuild.ps1 build/ + rm build/winpkg/sbapp/Makefile + rm build/winpkg/sbapp/buildozer.spec + cp winbuild.bat build/ mv build/winpkg build/sideband_sources - cd build; zip -r winbuild.zip sideband_sources winbuild.bat winbuild.ps1 + cd build; zip -r winbuild.zip sideband_sources winbuild.bat mv build/winbuild.zip dist/winbuild.zip build_winexe: prepare_win_pkg diff --git a/sbapp/Makefile b/sbapp/Makefile index cda2d7b..d425806 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -77,8 +77,6 @@ fetchshare: cp ../../dist_archive/RNode_Firmware_*_Source.zip ./share/pkg/ zip --junk-paths ./share/pkg/example_plugins.zip ../docs/example_plugins/*.py cp -r ../../dist_archive/reticulum.network ./share/mirrors/ - cp ../../dist_archive/Reticulum\ Manual.pdf ./share/mirrors/Reticulum_Manual.pdf - cp ../../dist_archive/Reticulum\ Manual.epub ./share/mirrors/Reticulum_Manual.epub mkdir ./share/mirrors/rnode-flasher cp ../../rnode-flasher/RNode_Flasher.html ./share/mirrors/rnode-flasher -(rm ./share/mirrors/rnode-flasher/.git -rf) diff --git a/sbapp/share/guides.html b/sbapp/share/guides.html index 5e09caf..cc1741d 100644 --- a/sbapp/share/guides.html +++ b/sbapp/share/guides.html @@ -14,8 +14,8 @@ Welcome to the Guide Section!

      From here, you can browse or downl
      From d97795de9d0bcc9f7dc629f53b12fdb210fdd4dd Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 27 Nov 2025 23:28:29 +0100 Subject: [PATCH 213/271] Fixed repo server not serving space-names --- sbapp/sideband/core.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 5d4a787..82b01be 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -5110,8 +5110,7 @@ class SidebandCore(): self.wfile.write(es.encode("utf-8")) else: try: - with open(path, 'rb') as f: - data = f.read() + with open(path.replace("%20", " "), "rb") as f: data = f.read() self.send_response(200) if path.lower().endswith(".apk"): self.send_header("Content-type", "application/vnd.android.package-archive") From 30c474badeef18df0f64c8b56207c0fb98d630af Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 28 Nov 2025 12:47:47 +0100 Subject: [PATCH 214/271] Updated Android build code --- sbapp/buildozer.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 5fbfbfc..83e9631 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 = 20251122 +android.numeric_version = 20251128 requirements = kivy==2.3.0,libbz2,sqlite3,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,able_recipe,libwebp,libogg,libopus,opusfile,numpy,cryptography,codec2,pycodec2,sh,pynacl,typing-extensions,mistune>=3.0.2,beautifulsoup4,lxst From 61609de690a974370ebf2981c0410caeede9ac92 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 2 Dec 2025 19:10:54 +0100 Subject: [PATCH 215/271] Fixed UI message state progress not updating on direct message failure and retry as propagated --- sbapp/sideband/core.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 82b01be..0b2dbff 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -202,6 +202,10 @@ class SidebandCore(): self.default_config_template = rns_config if config_path == None: + # h_dir = plyer.storagepath.get_home_dir() + # if type(h_dir) == bytes: h_dir = h_dir.decode("utf-8") + # self.app_dir = os.path.join(h_dir, ".config", "sideband") + # if self.app_dir.startswith("file://"): self.app_dir = self.app_dir.replace("file://", "") self.app_dir = os.path.join(plyer.storagepath.get_home_dir(), ".config", "sideband") if self.app_dir.startswith("file://"): self.app_dir = self.app_dir.replace("file://", "") else: @@ -4433,17 +4437,16 @@ class SidebandCore(): if message.state == LXMF.LXMessage.FAILED and hasattr(message, "try_propagation_on_fail") and message.try_propagation_on_fail: if hasattr(message, "stamp_generation_failed") and message.stamp_generation_failed == True: RNS.log(f"Could not send {message} due to a stamp generation failure", RNS.LOG_ERROR) - if not no_display: - self.lxm_ingest(message, originator=True) + if not no_display: self.lxm_ingest(message, originator=True) else: RNS.log("Direct delivery of "+str(message)+" failed. Retrying as propagated message.", RNS.LOG_VERBOSE) message.try_propagation_on_fail = None message.delivery_attempts = 0 - if hasattr(message, "next_delivery_attempt"): - del message.next_delivery_attempt + if hasattr(message, "next_delivery_attempt"): del message.next_delivery_attempt message.packed = None message.desired_method = LXMF.LXMessage.PROPAGATED self._db_message_set_method(message.hash, LXMF.LXMessage.PROPAGATED) + self._db_message_set_state(message.hash, LXMF.LXMessage.OUTBOUND) self.message_router.handle_outbound(message) else: if not no_display: From da834b75395b91b4aec7139b19cefbaa275c5937 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 20 Dec 2025 00:16:47 +0100 Subject: [PATCH 216/271] Fixed invalid announce interface attachment on AutoInterface peer availability after no peers --- sbapp/sideband/core.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 0b2dbff..f02152b 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -3502,7 +3502,6 @@ class SidebandCore(): if not self.interface_local.had_peers and have_peers: RNS.log("Peers became reachable on the interface "+str(self.interface_local), RNS.LOG_DEBUG) needs_if_change_announce = True - announce_attached_interface = self.interface_local announce_delay = 10 if self.interface_local.had_peers and not have_peers: From b12dda51b871959d23bcc2b64285a4f1ab5e2ae1 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 20 Dec 2025 14:53:33 +0100 Subject: [PATCH 217/271] Updated version --- sbapp/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/main.py b/sbapp/main.py index 95643fa..824b4d3 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.8.2" +__version__ = "1.8.3" __variant__ = "" import sys From d4cf40c72f9c6779430a7d7f9a077d84208c8bc5 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 25 Dec 2025 15:40:39 +0100 Subject: [PATCH 218/271] Refactored guide screen --- sbapp/main.py | 150 ++----------------------- sbapp/ui/guide.py | 266 ++++++++++++++++++++++++++++++++++++++++++++ sbapp/ui/helpers.py | 2 + sbapp/ui/layouts.py | 108 ------------------ 4 files changed, 278 insertions(+), 248 deletions(-) create mode 100644 sbapp/ui/guide.py diff --git a/sbapp/main.py b/sbapp/main.py index 824b4d3..2aaa4f8 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -435,11 +435,12 @@ else: from ui.telemetry import Telemetry from ui.utilities import Utilities from ui.voice import Voice + from ui.guide import Guide from ui.objectdetails import ObjectDetails from ui.announces import Announces 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 ui.helpers import multilingual_markup, mdc, dark_theme_text_color from kivymd.toast import toast from jnius import cast @@ -467,10 +468,11 @@ else: from .ui.telemetry import Telemetry from .ui.utilities import Utilities from .ui.voice import Voice + from .ui.guide import Guide from .ui.objectdetails import ObjectDetails 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 .ui.helpers import multilingual_markup, mdc, dark_theme_text_color import LXST.Codecs.libs.pyogg as pyogg from LXST.Codecs.libs.pydub import AudioSegment @@ -480,8 +482,6 @@ else: from kivy.config import Config Config.set('input', 'mouse', 'mouse,disable_multitouch') -dark_theme_text_color = "ddd" - if RNS.vendor.platformutils.get_platform() == "android": from jnius import autoclass from android.runnable import run_on_ui_thread @@ -1445,6 +1445,7 @@ class SidebandApp(MDApp): else: self.icon = os.path.join(self.sideband.asset_dir, "icon.png") self.announces_view = None + self.guide_view = None if RNS.vendor.platformutils.is_android(): ActivityInfo = autoclass('android.content.pm.ActivityInfo') @@ -6674,148 +6675,17 @@ class SidebandApp(MDApp): self.root.ids.screen_manager.transition = self.slide_transition def guide_action(self, sender=None, direction="left"): - if self.root.ids.screen_manager.has_screen("guide_screen"): - self.guide_open(direction=direction) + if self.guide_view: self.guide_open() else: self.loader_action(direction=direction) def final(dt): - self.guide_init() - def o(dt): - self.guide_open(no_transition=True) + self.init_guide_view() + def o(dt): self.guide_open(no_transition=True) Clock.schedule_once(o, ll_ot) Clock.schedule_once(final, ll_ft) - def guide_init(self): - if not self.root.ids.screen_manager.has_screen("guide_screen"): - self.guide_screen = Builder.load_string(layout_guide_screen) - self.guide_screen.app = self - self.root.ids.screen_manager.add_widget(self.guide_screen) - - def link_exec(sender=None, event=None): - def lj(): - webbrowser.open("https://unsigned.io/donate") - threading.Thread(target=lj, daemon=True).start() - - guide_text1 = """ -[size=18dp][b]Introduction[/b][/size][size=5dp]\n \n[/size]Welcome to [i]Sideband[/i], an LXMF client for Android, Linux, macOS and Windows. With Sideband, you can communicate with other people or LXMF-compatible systems over Reticulum networks using LoRa, Packet Radio, WiFi, I2P, or anything else Reticulum supports. - -This short guide will give you a basic introduction to the concepts that underpin Sideband and LXMF (which is the protocol that Sideband uses to communicate). If you are not already familiar with LXMF and Reticulum, it is probably a good idea to read this guide, since Sideband is very different from other messaging apps.""" - guide_text2 = """ -[size=18dp][b]Communication Without Subjection[/b][/size][size=5dp]\n \n[/size]Sideband is completely free, permission-less, anonymous and infrastructure-less. Sideband uses the peer-to-peer and distributed messaging system LXMF. There is no sign-up, no service providers, no "end-user license agreements", no data theft and no surveillance. You own the system. - -This also means that Sideband operates differently than what you might be used to. It does not need a connection to a server on the Internet to function, and you do not have an account anywhere.""" - - guide_text3 = """ -[size=18dp][b]Operating Principles[/b][/size][size=5dp]\n \n[/size]When Sideband is started on your device for the first time, it randomly generates a 512-bit Reticulum Identity Key. This cryptographic key is then used to create an LXMF address for your use, and in turn to secure any communication to your address. Any other endpoint in [i]any[/i] Reticulum network will be able to send data to your address, as long as there is [i]some sort of physical connection[/i] between your device and the remote endpoint. You can also move around to other Reticulum networks with this address, even ones that were never connected to the network the address was created on, or that didn't exist when the address was created.\n\nYour LXMF address is yours to keep and control for as long (or short) a time you need it, and you can always delete it and create a new one. You identity keys and corresponding addresses are never registered on or controlled by any external servers or services, and will never leave your device, unless you manually export them for backup.""" - - guide_text10 = """ -[size=18dp][b]Getting Connected[/b][/size][size=5dp]\n \n[/size]If you already have Reticulum connectivity set up on the device you are running Sideband on, no further configuration should be necessary, and Sideband will simply use the available Reticulum connectivity.\n\nIf you are running Sideband on a computer, you can configure interfaces in the Reticulum configuration file ([b]~/.reticulum/config[/b] by default). If you are running Sideband on an Android device, you can configure various interface types in the [b]Connectivity[/b] section. By default, only an [i]AutoInterface[/i] is enabled, which will connect you automatically with any other local devices on the same WiFi and/or Ethernet networks. This may or may not include Reticulum Transport Nodes, which can route your traffic to wider networks.\n\nYou can enable any or all of the other available interface types to gain wider connectivity. For more specific information on interface types, configuration options, and how to effectively build your own Reticulum networks, see the [b]Reticulum Manual[b].""" - - guide_text4 = """ -[size=18dp][b]Becoming Reachable[/b][/size][size=5dp]\n \n[/size]To establish reachability for any Reticulum destination on a network, an [i]announce[/i] must be sent. By default, Sideband will announce automatically when necessary, but if you want to stay silent, automatic announces can be disabled in [b]Preferences[/b].\n\nTo send an announce manually, press the [i]Announce[/i] button in the [i]Conversations[/i] section of the program. When you send an announce, you make your LXMF address reachable for real-time messaging to the entire network you are connected to. Even in very large networks, you can expect global reachability for your address to be established in under a minute. - -If you don't move to other places in the network, and keep connected through the same hubs or gateways, it is generally not necessary to send an announce more often than once every week. If you change your entry point to the network, you may want to send an announce, or you may just want to stay quiet.""" - - guide_text5 = """ -[size=18dp][b]Relax & Disconnect[/b][/size][size=5dp]\n \n[/size]If you are not connected to the network, it is still possible for other people to message you, as long as one or more [i]Propagation Nodes[/i] exist on the network. These nodes pick up and hold encrypted in-transit messages for offline users. Messages are always encrypted before leaving the originators device, and nobody else than the intended recipient can decrypt messages in transit. - -The Propagation Nodes also distribute copies of messages between each other, such that even the failure of almost every node in the network will still allow users to sync their waiting messages. If all Propagation Nodes disappear or are destroyed, users can still communicate directly.\n\nReticulum and LXMF will degrade gracefully all the way down to single users communicating directly via long-range data radios. Anyone can start up new propagation nodes and integrate them into existing networks without permission or coordination. Even a small and cheap device like a Rasperry Pi can handle messages for millions of users. LXMF networks are designed to be quite resilient, as long as there are people using them.""" - - guide_text6 = """ -[size=18dp][b]Packets Find A Way[/b][/size][size=5dp]\n \n[/size]Connections in Reticulum networks can be wired or wireless, span many intermediary hops, run over fast links or ultra-low bandwidth radio, tunnel over the Invisible Internet (I2P), private networks, satellite connections, serial lines or anything else that Reticulum can carry data over.\n\nIn most cases it will not be possible to know what path packets takes in a Reticulum network, and apart from a destination hash, no transmitted packets carries any identifying characteristics. In Reticulum, [i]there is no source addresses[/i].\n\nAs long as you do not reveal any connecting details between your person and your LXMF address, you can remain anonymous. Sending messages to others does not reveal [i]your[/i] address to anyone else than the intended recipient.""" - - guide_text7 = """ -[size=18dp][b]Be Yourself, Be Unknown, Stay Free[/b][/size][size=5dp]\n \n[/size]Even with the above characteristics in mind, you [b]must remember[/b] that LXMF and Reticulum is not a technology that can guarantee anonymising connections that are already de-anonymised! If you use Sideband to connect to TCP Reticulum hubs over the clear Internet, from a network that can be tied to your personal identity, an adversary may learn that you are generating LXMF traffic.\n\nIf you want to avoid this, it is recommended to use I2P to connect to Reticulum hubs on the Internet. Or only connecting from within pure Reticulum networks, that take one or more hops to reach connections that span the Internet. This is a complex topic, with many more nuances than can be covered here. You are encouraged to ask on the various Reticulum discussion forums if you are in doubt. - -If you use Reticulum and LXMF on hardware that does not carry any identifiers tied to you, it is possible to establish a completely free and identification-less communication system with Reticulum and LXMF clients.""" - - guide_text8 = """ -[size=18dp][b]Keyboard Shortcuts[/b][/size][size=5dp]\n \n[/size]To ease navigation and operation of the program, Sideband has keyboard shortcuts mapped to the most common actions. A reference is included below. - -[b]Quick Actions[/b] - - [b]Ctrl-W[/b] Go back - - [b]Ctrl-Q[/b] Shut down Sideband - - [b]Ctrl-R[/b] Start LXMF sync (from Conversations screen) - - [b]Ctrl-N[/b] Create new conversation - - [b]Message Actions[/b] - - [b]Ctrl-Shift-A[/b] add message attachment - - [b]Ctrl-Shift-V[/b] add high-quality voice - - [b]Ctrl-Shift-C[/b] add low-bandwidth voice - - [b]Ctrl-Shift-I[/b] add medium-quality image - - [b]Ctrl-Shift-F[/b] add file - - [b]Ctrl-D[/b] or [b]Ctrl-S[/b] Send message - - [b]Voice & PTT Messages[/b] - - [b]Space[/b] Start/stop recording - - [b]Enter[/b] Save recording to message - - With PTT enabled, hold [b]Space[/b] to talk - - [b]Voice Calls[/b] - - [b]Ctrl-Space[/b] Answer incoming call - - [b]Ctrl-.[/b] Reject incoming call - - [b]Ctrl-.[/b] Hang up active call - - [b]Navigation[/b] - - [b]Ctrl-[i]n[/i][/b] Go to conversation number [i]n[/i] - - [b]Ctrl-R[/b] Go to Conversations - - [b]Ctrl-O[/b] Go to Objects & Devices - - [b]Ctrl-E[/b] Go to Voice - - [b]Ctrl-L[/b] Go to Announce Stream - - [b]Ctrl-M[/b] Go to Situation Map - - [b]Ctrl-U[/b] Go to Utilities - - [b]Ctrl-T[/b] Go to Telemetry configuration - - [b]Ctrl-G[/b] Go to Guide - - [b]Ctrl-Y[/b] Display own telemetry - -[b]Map Controls[/b] - - [b]Up[/b], [b]down[/b], [b]left[/b], [b]right[/b] Navigate - - [b]W[/b], [b]A[/b], [b]S[/b], [b]D[/b] Navigate - - [b]H[/b], [b]J[/b], [b]L[/b], [b]K[/b] Navigate - - [b]E[/b] or [b]+[/b] Zoom in - - [b]Q[/b] or [b]-[/b] Zoom out - - Hold [b]Shift[/b] to navigate more coarsely - - Hold [b]Alt[/b] to navigate more finely""" - - guide_text9 = """ -[size=18dp][b]Please Support This Project[/b][/size][size=5dp]\n \n[/size]It took me more than eight years to design and build the entire ecosystem of software and hardware that makes this possible. If this project is valuable to you, please go to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project with a donation. Every donation directly makes the entire Reticulum project possible. - -Thank you very much for using Free Communications Systems. -""" - info1 = guide_text1 - info2 = guide_text8 - info3 = guide_text2 - info4 = guide_text3 - info10 = guide_text10 - info5 = guide_text4 - info6 = guide_text5 - info7 = guide_text6 - info8 = guide_text7 - info9 = guide_text9 - - if self.theme_cls.theme_style == "Dark": - info1 = "[color=#"+dark_theme_text_color+"]"+info1+"[/color]" - info2 = "[color=#"+dark_theme_text_color+"]"+info2+"[/color]" - info3 = "[color=#"+dark_theme_text_color+"]"+info3+"[/color]" - info4 = "[color=#"+dark_theme_text_color+"]"+info4+"[/color]" - info5 = "[color=#"+dark_theme_text_color+"]"+info5+"[/color]" - info6 = "[color=#"+dark_theme_text_color+"]"+info6+"[/color]" - info7 = "[color=#"+dark_theme_text_color+"]"+info7+"[/color]" - info8 = "[color=#"+dark_theme_text_color+"]"+info8+"[/color]" - info9 = "[color=#"+dark_theme_text_color+"]"+info9+"[/color]" - info10 = "[color=#"+dark_theme_text_color+"]"+info10+"[/color]" - self.guide_screen.ids.guide_info1.text = info1 - self.guide_screen.ids.guide_info2.text = info2 - self.guide_screen.ids.guide_info3.text = info3 - self.guide_screen.ids.guide_info4.text = info4 - self.guide_screen.ids.guide_info5.text = info5 - self.guide_screen.ids.guide_info6.text = info6 - self.guide_screen.ids.guide_info7.text = info7 - self.guide_screen.ids.guide_info8.text = info8 - self.guide_screen.ids.guide_info9.text = info9 - self.guide_screen.ids.guide_info10.text = info10 - self.guide_screen.ids.guide_info9.bind(on_ref_press=link_exec) - self.guide_screen.ids.guide_scrollview.effect_cls = ScrollEffect + def init_guide_view(self, sender=None): + if not self.guide_view: self.guide_view = Guide(self) ################################################# diff --git a/sbapp/ui/guide.py b/sbapp/ui/guide.py new file mode 100644 index 0000000..ff16126 --- /dev/null +++ b/sbapp/ui/guide.py @@ -0,0 +1,266 @@ +import time +import RNS + +from typing import Union +from kivy.metrics import dp,sp +from kivy.lang.builder import Builder +from kivy.core.clipboard import Clipboard +from kivy.utils import escape_markup +from kivymd.uix.recycleview import MDRecycleView +from kivymd.uix.list import OneLineIconListItem +from kivymd.uix.pickers import MDColorPicker +from kivymd.uix.button import MDRectangleFlatButton +from kivymd.uix.button import MDRectangleFlatIconButton +from kivymd.uix.dialog import MDDialog +from kivy.properties import StringProperty, BooleanProperty, OptionProperty, ColorProperty, Property +from kivymd.uix.list import MDList, IconLeftWidget, IconRightWidget, OneLineAvatarIconListItem +from kivymd.icon_definitions import md_icons +from kivymd.toast import toast +from kivy.properties import StringProperty, BooleanProperty +from kivy.effects.scroll import ScrollEffect + +if RNS.vendor.platformutils.get_platform() == "android": + from ui.helpers import dark_theme_text_color +else: + from .helpers import dark_theme_text_color + +class Guide(): + def __init__(self, app): + self.app = app + self.screen = None + + if not self.app.root.ids.screen_manager.has_screen("guide_screen"): + self.screen = Builder.load_string(layout_guide_screen) + self.screen.app = self + self.app.root.ids.screen_manager.add_widget(self.screen) + + def link_exec(sender=None, event=None): + def lj(): webbrowser.open("https://unsigned.io/donate") + threading.Thread(target=lj, daemon=True).start() + + guide_text1 = """ +[size=18dp][b]Introduction[/b][/size][size=5dp]\n \n[/size]Welcome to [i]Sideband[/i], an LXMF client for Android, Linux, macOS and Windows. With Sideband, you can communicate with other people or LXMF-compatible systems over Reticulum networks using LoRa, Packet Radio, WiFi, I2P, or anything else Reticulum supports. + +This short guide will give you a basic introduction to the concepts that underpin Sideband and LXMF (which is the protocol that Sideband uses to communicate). If you are not already familiar with LXMF and Reticulum, it is probably a good idea to read this guide, since Sideband is very different from other messaging apps.""" + guide_text2 = """ +[size=18dp][b]Communication Without Subjection[/b][/size][size=5dp]\n \n[/size]Sideband is completely free, permission-less, anonymous and infrastructure-less. Sideband uses the peer-to-peer and distributed messaging system LXMF. There is no sign-up, no service providers, no "end-user license agreements", no data theft and no surveillance. You own the system. + +This also means that Sideband operates differently than what you might be used to. It does not need a connection to a server on the Internet to function, and you do not have an account anywhere.""" + + guide_text3 = """ +[size=18dp][b]Operating Principles[/b][/size][size=5dp]\n \n[/size]When Sideband is started on your device for the first time, it randomly generates a 512-bit Reticulum Identity Key. This cryptographic key is then used to create an LXMF address for your use, and in turn to secure any communication to your address. Any other endpoint in [i]any[/i] Reticulum network will be able to send data to your address, as long as there is [i]some sort of physical connection[/i] between your device and the remote endpoint. You can also move around to other Reticulum networks with this address, even ones that were never connected to the network the address was created on, or that didn't exist when the address was created.\n\nYour LXMF address is yours to keep and control for as long (or short) a time you need it, and you can always delete it and create a new one. You identity keys and corresponding addresses are never registered on or controlled by any external servers or services, and will never leave your device, unless you manually export them for backup.""" + + guide_text10 = """ +[size=18dp][b]Getting Connected[/b][/size][size=5dp]\n \n[/size]If you already have Reticulum connectivity set up on the device you are running Sideband on, no further configuration should be necessary, and Sideband will simply use the available Reticulum connectivity.\n\nIf you are running Sideband on a computer, you can configure interfaces in the Reticulum configuration file ([b]~/.reticulum/config[/b] by default). If you are running Sideband on an Android device, you can configure various interface types in the [b]Connectivity[/b] section. By default, only an [i]AutoInterface[/i] is enabled, which will connect you automatically with any other local devices on the same WiFi and/or Ethernet networks. This may or may not include Reticulum Transport Nodes, which can route your traffic to wider networks.\n\nYou can enable any or all of the other available interface types to gain wider connectivity. For more specific information on interface types, configuration options, and how to effectively build your own Reticulum networks, see the [b]Reticulum Manual[b].""" + + guide_text4 = """ +[size=18dp][b]Becoming Reachable[/b][/size][size=5dp]\n \n[/size]To establish reachability for any Reticulum destination on a network, an [i]announce[/i] must be sent. By default, Sideband will announce automatically when necessary, but if you want to stay silent, automatic announces can be disabled in [b]Preferences[/b].\n\nTo send an announce manually, press the [i]Announce[/i] button in the [i]Conversations[/i] section of the program. When you send an announce, you make your LXMF address reachable for real-time messaging to the entire network you are connected to. Even in very large networks, you can expect global reachability for your address to be established in under a minute. + +If you don't move to other places in the network, and keep connected through the same hubs or gateways, it is generally not necessary to send an announce more often than once every week. If you change your entry point to the network, you may want to send an announce, or you may just want to stay quiet.""" + + guide_text5 = """ +[size=18dp][b]Relax & Disconnect[/b][/size][size=5dp]\n \n[/size]If you are not connected to the network, it is still possible for other people to message you, as long as one or more [i]Propagation Nodes[/i] exist on the network. These nodes pick up and hold encrypted in-transit messages for offline users. Messages are always encrypted before leaving the originators device, and nobody else than the intended recipient can decrypt messages in transit. + +The Propagation Nodes also distribute copies of messages between each other, such that even the failure of almost every node in the network will still allow users to sync their waiting messages. If all Propagation Nodes disappear or are destroyed, users can still communicate directly.\n\nReticulum and LXMF will degrade gracefully all the way down to single users communicating directly via long-range data radios. Anyone can start up new propagation nodes and integrate them into existing networks without permission or coordination. Even a small and cheap device like a Rasperry Pi can handle messages for millions of users. LXMF networks are designed to be quite resilient, as long as there are people using them.""" + + guide_text6 = """ +[size=18dp][b]Packets Find A Way[/b][/size][size=5dp]\n \n[/size]Connections in Reticulum networks can be wired or wireless, span many intermediary hops, run over fast links or ultra-low bandwidth radio, tunnel over the Invisible Internet (I2P), private networks, satellite connections, serial lines or anything else that Reticulum can carry data over.\n\nIn most cases it will not be possible to know what path packets takes in a Reticulum network, and apart from a destination hash, no transmitted packets carries any identifying characteristics. In Reticulum, [i]there is no source addresses[/i].\n\nAs long as you do not reveal any connecting details between your person and your LXMF address, you can remain anonymous. Sending messages to others does not reveal [i]your[/i] address to anyone else than the intended recipient.""" + + guide_text7 = """ +[size=18dp][b]Be Yourself, Be Unknown, Stay Free[/b][/size][size=5dp]\n \n[/size]Even with the above characteristics in mind, you [b]must remember[/b] that LXMF and Reticulum is not a technology that can guarantee anonymising connections that are already de-anonymised! If you use Sideband to connect to TCP Reticulum hubs over the clear Internet, from a network that can be tied to your personal identity, an adversary may learn that you are generating LXMF traffic.\n\nIf you want to avoid this, it is recommended to use I2P to connect to Reticulum hubs on the Internet. Or only connecting from within pure Reticulum networks, that take one or more hops to reach connections that span the Internet. This is a complex topic, with many more nuances than can be covered here. You are encouraged to ask on the various Reticulum discussion forums if you are in doubt. + +If you use Reticulum and LXMF on hardware that does not carry any identifiers tied to you, it is possible to establish a completely free and identification-less communication system with Reticulum and LXMF clients.""" + + guide_text8 = """ +[size=18dp][b]Keyboard Shortcuts[/b][/size][size=5dp]\n \n[/size]To ease navigation and operation of the program, Sideband has keyboard shortcuts mapped to the most common actions. A reference is included below. + +[b]Quick Actions[/b] + - [b]Ctrl-W[/b] Go back + - [b]Ctrl-Q[/b] Shut down Sideband + - [b]Ctrl-R[/b] Start LXMF sync (from Conversations screen) + - [b]Ctrl-N[/b] Create new conversation + + [b]Message Actions[/b] + - [b]Ctrl-Shift-A[/b] add message attachment + - [b]Ctrl-Shift-V[/b] add high-quality voice + - [b]Ctrl-Shift-C[/b] add low-bandwidth voice + - [b]Ctrl-Shift-I[/b] add medium-quality image + - [b]Ctrl-Shift-F[/b] add file + - [b]Ctrl-D[/b] or [b]Ctrl-S[/b] Send message + + [b]Voice & PTT Messages[/b] + - [b]Space[/b] Start/stop recording + - [b]Enter[/b] Save recording to message + - With PTT enabled, hold [b]Space[/b] to talk + + [b]Voice Calls[/b] + - [b]Ctrl-Space[/b] Answer incoming call + - [b]Ctrl-.[/b] Reject incoming call + - [b]Ctrl-.[/b] Hang up active call + + [b]Navigation[/b] + - [b]Ctrl-[i]n[/i][/b] Go to conversation number [i]n[/i] + - [b]Ctrl-R[/b] Go to Conversations + - [b]Ctrl-O[/b] Go to Objects & Devices + - [b]Ctrl-E[/b] Go to Voice + - [b]Ctrl-L[/b] Go to Announce Stream + - [b]Ctrl-M[/b] Go to Situation Map + - [b]Ctrl-U[/b] Go to Utilities + - [b]Ctrl-T[/b] Go to Telemetry configuration + - [b]Ctrl-G[/b] Go to Guide + - [b]Ctrl-Y[/b] Display own telemetry + +[b]Map Controls[/b] + - [b]Up[/b], [b]down[/b], [b]left[/b], [b]right[/b] Navigate + - [b]W[/b], [b]A[/b], [b]S[/b], [b]D[/b] Navigate + - [b]H[/b], [b]J[/b], [b]L[/b], [b]K[/b] Navigate + - [b]E[/b] or [b]+[/b] Zoom in + - [b]Q[/b] or [b]-[/b] Zoom out + - Hold [b]Shift[/b] to navigate more coarsely + - Hold [b]Alt[/b] to navigate more finely""" + + guide_text9 = """ +[size=18dp][b]Please Support This Project[/b][/size][size=5dp]\n \n[/size]It took me more than eight years to design and build the entire ecosystem of software and hardware that makes this possible. If this project is valuable to you, please go to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project with a donation. Every donation directly makes the entire Reticulum project possible. + +Thank you very much for using Free Communications Systems. +""" + info1 = guide_text1 + info2 = guide_text8 + info3 = guide_text2 + info4 = guide_text3 + info10 = guide_text10 + info5 = guide_text4 + info6 = guide_text5 + info7 = guide_text6 + info8 = guide_text7 + info9 = guide_text9 + + if self.app.theme_cls.theme_style == "Dark": + info1 = "[color=#"+dark_theme_text_color+"]"+info1+"[/color]" + info2 = "[color=#"+dark_theme_text_color+"]"+info2+"[/color]" + info3 = "[color=#"+dark_theme_text_color+"]"+info3+"[/color]" + info4 = "[color=#"+dark_theme_text_color+"]"+info4+"[/color]" + info5 = "[color=#"+dark_theme_text_color+"]"+info5+"[/color]" + info6 = "[color=#"+dark_theme_text_color+"]"+info6+"[/color]" + info7 = "[color=#"+dark_theme_text_color+"]"+info7+"[/color]" + info8 = "[color=#"+dark_theme_text_color+"]"+info8+"[/color]" + info9 = "[color=#"+dark_theme_text_color+"]"+info9+"[/color]" + info10 = "[color=#"+dark_theme_text_color+"]"+info10+"[/color]" + self.screen.ids.guide_info1.text = info1 + self.screen.ids.guide_info2.text = info2 + self.screen.ids.guide_info3.text = info3 + self.screen.ids.guide_info4.text = info4 + self.screen.ids.guide_info5.text = info5 + self.screen.ids.guide_info6.text = info6 + self.screen.ids.guide_info7.text = info7 + self.screen.ids.guide_info8.text = info8 + self.screen.ids.guide_info9.text = info9 + self.screen.ids.guide_info10.text = info10 + self.screen.ids.guide_info9.bind(on_ref_press=link_exec) + self.screen.ids.guide_scrollview.effect_cls = ScrollEffect + +layout_guide_screen = """ +MDScreen: + name: "guide_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Guide" + anchor_title: "left" + elevation: 0 + left_action_items: + [ ['menu', lambda x: root.app.app.nav_drawer.set_state("open")] ] + right_action_items: + [ ['close', lambda x: root.app.app.close_guide_action(self)] ] + + ScrollView: + id:guide_scrollview + + MDBoxLayout: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [dp(35), dp(16), dp(35), dp(16)] + + MDLabel: + id: guide_info1 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info2 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info3 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info4 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info10 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info5 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info6 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info7 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info8 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + id: guide_info9 + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] +""" \ No newline at end of file diff --git a/sbapp/ui/helpers.py b/sbapp/ui/helpers.py index d8c0aaa..3f2f3fc 100644 --- a/sbapp/ui/helpers.py +++ b/sbapp/ui/helpers.py @@ -43,6 +43,8 @@ color_failed_alt = "Red" color_unknown_alt = "Gray" color_cancelled_alt = "Red" +dark_theme_text_color = "ddd" + class ContentNavigationDrawer(Screen): pass diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 4909255..46c67cd 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -849,114 +849,6 @@ MDScreen: # font_size: dp(24) """ -layout_guide_screen = """ -MDScreen: - name: "guide_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "Guide" - anchor_title: "left" - elevation: 0 - left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] - right_action_items: - [ - ['close', lambda x: root.app.close_guide_action(self)], - ] - - ScrollView: - id:guide_scrollview - - MDBoxLayout: - orientation: "vertical" - size_hint_y: None - height: self.minimum_height - padding: [dp(35), dp(16), dp(35), dp(16)] - - MDLabel: - id: guide_info1 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info2 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info3 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info4 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info10 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info5 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info6 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info7 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info8 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - id: guide_info9 - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] -""" - layout_information_screen = """ MDScreen: name: "information_screen" From 199d9f9bdf8431ccbedae18cf8d1a6d5185680e4 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 25 Dec 2025 15:44:21 +0100 Subject: [PATCH 219/271] Cleanup --- sbapp/main.py | 36 ++++++++++-------------------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 2aaa4f8..56a5172 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -5345,56 +5345,40 @@ class SidebandApp(MDApp): if not self.announces_view: self.announces_view = Announces(self) self.sideband.setstate("app.flags.new_announces", True) - - for child in self.announces_view.ids.announces_scrollview.children: - self.announces_view.ids.announces_scrollview.remove_widget(child) - + for child in self.announces_view.ids.announces_scrollview.children: self.announces_view.ids.announces_scrollview.remove_widget(child) self.announces_view.ids.announces_scrollview.effect_cls = ScrollEffect self.announces_view.ids.announces_scrollview.add_widget(self.announces_view.get_widget()) - self.announces_view.update() def announces_action(self, sender=None, direction="left"): - if self.announces_view: - self.announces_open(direction=direction) + if self.announces_view: self.announces_open(direction=direction) else: self.loader_action(direction=direction) def final(dt): self.init_announces_view() - def o(dt): - self.announces_open(no_transition=True) + def o(dt): self.announces_open(no_transition=True) Clock.schedule_once(o, ll_ot) Clock.schedule_once(final, ll_ft) def announces_open(self, sender=None, direction="left", no_transition=False): - if no_transition: - self.root.ids.screen_manager.transition = self.no_transition + if no_transition: self.root.ids.screen_manager.transition = self.no_transition else: self.root.ids.screen_manager.transition = self.slide_transition self.root.ids.screen_manager.transition.direction = direction self.root.ids.nav_drawer.set_state("closed") - - if self.sideband.getstate("app.flags.new_announces"): - self.announces_view.update() - + if self.sideband.getstate("app.flags.new_announces"): self.announces_view.update() self.root.ids.screen_manager.current = "announces_screen" self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) + if no_transition: self.root.ids.screen_manager.transition = self.slide_transition - if no_transition: - self.root.ids.screen_manager.transition = self.slide_transition + def close_announces_action(self, sender=None): self.open_conversations(direction="right") - def close_announces_action(self, sender=None): - self.open_conversations(direction="right") - - def announce_filter_action(self, sender=None): - pass + def announce_filter_action(self, sender=None): pass def screen_transition_complete(self, sender): - if self.root.ids.screen_manager.current == "announces_screen": - pass - if self.root.ids.screen_manager.current == "conversations_screen": - pass + if self.root.ids.screen_manager.current == "announces_screen": pass + if self.root.ids.screen_manager.current == "conversations_screen": pass ### Keys screen ###################################### From 2e8a17854ecbbc19a796ccd138a6b376dc93f496 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 25 Dec 2025 16:10:16 +0100 Subject: [PATCH 220/271] Refactored keys screen --- sbapp/main.py | 145 ++---------------------- sbapp/ui/keys.py | 270 ++++++++++++++++++++++++++++++++++++++++++++ sbapp/ui/layouts.py | 121 -------------------- 3 files changed, 281 insertions(+), 255 deletions(-) create mode 100644 sbapp/ui/keys.py diff --git a/sbapp/main.py b/sbapp/main.py index 56a5172..7fe6601 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -436,6 +436,7 @@ else: from ui.utilities import Utilities from ui.voice import Voice from ui.guide import Guide + from ui.keys import Keys from ui.objectdetails import ObjectDetails from ui.announces import Announces from ui.messages import Messages, ts_format, messages_screen_kv @@ -469,6 +470,7 @@ else: from .ui.utilities import Utilities from .ui.voice import Voice from .ui.guide import Guide + from .ui.keys import Keys from .ui.objectdetails import ObjectDetails from .ui.messages import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem @@ -1446,6 +1448,7 @@ class SidebandApp(MDApp): self.announces_view = None self.guide_view = None + self.keys_view = None if RNS.vendor.platformutils.is_android(): ActivityInfo = autoclass('android.content.pm.ActivityInfo') @@ -5384,37 +5387,20 @@ class SidebandApp(MDApp): ###################################### def keys_action(self, sender=None, direction="left"): - if self.root.ids.screen_manager.has_screen("keys_screen"): - self.keys_open(direction=direction) + if self.root.ids.screen_manager.has_screen("keys_screen"): self.keys_open(direction=direction) else: self.loader_action(direction=direction) def final(dt): - self.keys_init() - def o(dt): - self.keys_open(no_transition=True) + self.init_keys_view() + def o(dt): self.keys_open(no_transition=True) Clock.schedule_once(o, ll_ot) Clock.schedule_once(final, ll_ft) - def keys_init(self): - if not self.root.ids.screen_manager.has_screen("keys_screen"): - self.keys_screen = Builder.load_string(layout_keys_screen) - self.keys_screen.app = self - self.root.ids.screen_manager.add_widget(self.keys_screen) - self.bind_clipboard_actions(self.keys_screen.ids) - - self.keys_screen.ids.keys_scrollview.effect_cls = ScrollEffect - info1 = "[size=18dp][b]Encryption Keys[/b][/size][size=5dp]\n \n[/size]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." - info2 = "[size=18dp][b]Backup & Restore[/b][/size][size=5dp]\n \n[/size]You can backup your entire Sideband profile for import on a computer or other device. The exported backup archive will be saved in the downloads folder of your device. Please note that the exported archive contains all your messages, data and encryption keys. Take extreme care to keep this archive secure." - - if not RNS.vendor.platformutils.get_platform() == "android": - self.widget_hide(self.keys_screen.ids.keys_share) - - self.keys_screen.ids.keys_info.text = info1 - self.keys_screen.ids.backup_info.text = info2 + def init_keys_view(self, sender=None): + if not self.keys_view: self.keys_view = Keys(self) def keys_open(self, sender=None, direction="left", no_transition=False): - if no_transition: - self.root.ids.screen_manager.transition = self.no_transition + if no_transition: self.root.ids.screen_manager.transition = self.no_transition else: self.root.ids.screen_manager.transition = self.slide_transition self.root.ids.screen_manager.transition.direction = direction @@ -5423,119 +5409,10 @@ class SidebandApp(MDApp): self.root.ids.screen_manager.current = "keys_screen" self.root.ids.nav_drawer.set_state("closed") self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) + if no_transition: self.root.ids.screen_manager.transition = self.slide_transition - if no_transition: - self.root.ids.screen_manager.transition = self.slide_transition + def close_keys_action(self, sender=None): self.open_conversations(direction="right") - def close_keys_action(self, sender=None): - self.open_conversations(direction="right") - - def _profile_backup_job(self): - import tarfile - from ui.helpers import file_ts_format - output_path = plyer.storagepath.get_downloads_dir() - time_str = time.strftime(file_ts_format, time.localtime(time.time())) - target_file = f"{output_path}/sideband_backup_{time_str}.tar.gz" - tar = tarfile.open(target_file, "w:gz") - tar.add(f"{self.sideband.app_dir}/app_storage", arcname="Sideband Backup") - tar.close() - - def job(dt): - self.keys_screen.ids.keys_backup.disabled = False - toast("Backup done") - ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog(text=f"Backup has been saved to {target_file}", - buttons=[ok_button]) - def dl_yes(s): dialog.dismiss() - - ok_button.bind(on_release=dl_yes) - dialog.open() - - Clock.schedule_once(job, 0.3) - - def profile_backup_action(self, sender=None): - self.keys_screen.ids.keys_backup.disabled = True - toast("Creating backup...") - threading.Thread(target=self._profile_backup_job, daemon=True).start() - - def identity_display_action(self, sender=None): - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - - dialog = MDDialog( - text="Your Identity key, in base32 format is as follows:\n\n[b]"+str(base64.b32encode(self.sideband.identity.get_private_key()).decode("utf-8"))+"[/b]", - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - dialog.dismiss() - - yes_button.bind(on_release=dl_yes) - dialog.open() - - def identity_copy_action(self, sender=None): - c_yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.color_reject, text_color=self.color_reject) - c_no_button = MDRectangleFlatButton(text="No, go back",font_size=dp(18)) - c_dialog = MDDialog(text="[b]Caution![/b]\n\nYour Identity key will be copied to the system clipboard. Take extreme care that no untrusted app steals your key by reading the clipboard data. Clear the system clipboard immediately after pasting your key where you need it.\n\nAre you sure that you wish to proceed?", buttons=[ c_no_button, c_yes_button ]) - def c_dl_no(s): - c_dialog.dismiss() - def c_dl_yes(s): - c_dialog.dismiss() - yes_button = MDRectangleFlatButton(text="OK") - dialog = MDDialog(text="Your Identity key was copied to the system clipboard", buttons=[ yes_button ]) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - - Clipboard.copy(str(base64.b32encode(self.sideband.identity.get_private_key()).decode("utf-8"))) - dialog.open() - - c_yes_button.bind(on_release=c_dl_yes) - c_no_button.bind(on_release=c_dl_no) - - c_dialog.open() - - def identity_share_action(self, sender=None): - if RNS.vendor.platformutils.get_platform() == "android": - self.share_text(str(base64.b32encode(self.sideband.identity.get_private_key()).decode("utf-8"))) - - def identity_restore_action(self, sender=None): - c_yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.color_reject, text_color=self.color_reject) - c_no_button = MDRectangleFlatButton(text="No, go back",font_size=dp(18)) - c_dialog = MDDialog(text="[b]Caution![/b]\n\nYou are about to import a new Identity key into Sideband. The currently active key will be irreversibly destroyed, and you will loose your LXMF address if you have not already backed up your current Identity key.\n\nAre you sure that you wish to import the key?", buttons=[ c_no_button, c_yes_button ]) - def c_dl_no(s): - c_dialog.dismiss() - def c_dl_yes(s): - c_dialog.dismiss() - b32_text = self.keys_screen.ids.key_restore_text.text - - try: - key_bytes = base64.b32decode(b32_text) - new_id = RNS.Identity.from_bytes(key_bytes) - - if new_id != None: - new_id.to_file(self.sideband.identity_path) - - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog(text="[b]The provided Identity key data was imported[/b]\n\nThe app will now exit. Please restart Sideband to use the new Identity.", buttons=[ yes_button ]) - def dl_yes(s): - dialog.dismiss() - self.quit_action(sender=self) - yes_button.bind(on_release=dl_yes) - dialog.open() - - except Exception as e: - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog(text="[b]The provided Identity key data was not valid[/b]\n\nThe error reported by Reticulum was:\n\n[i]"+str(e)+"[/i]\n\nNo Identity was imported into Sideband.", buttons=[ yes_button ]) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - dialog.open() - - - c_yes_button.bind(on_release=c_dl_yes) - c_no_button.bind(on_release=c_dl_no) - - c_dialog.open() ### Plugins & Services screen ###################################### diff --git a/sbapp/ui/keys.py b/sbapp/ui/keys.py new file mode 100644 index 0000000..5b5e8aa --- /dev/null +++ b/sbapp/ui/keys.py @@ -0,0 +1,270 @@ +import time +import RNS + +import base64 +import threading +from kivy.metrics import dp,sp +from kivy.lang.builder import Builder +from kivy.core.clipboard import Clipboard +from kivymd.uix.button import MDRectangleFlatButton +from kivymd.uix.dialog import MDDialog +from kivymd.toast import toast +from kivy.effects.scroll import ScrollEffect + +if RNS.vendor.platformutils.get_platform() == "android": + from ui.helpers import dark_theme_text_color +else: + from .helpers import dark_theme_text_color + +class Keys(): + def __init__(self, app): + self.app = app + self.keys_screen = None + + if not self.app.root.ids.screen_manager.has_screen("keys_screen"): + self.keys_screen = Builder.load_string(layout_keys_screen) + self.keys_screen.app = self + self.app.root.ids.screen_manager.add_widget(self.keys_screen) + self.app.bind_clipboard_actions(self.keys_screen.ids) + + self.keys_screen.ids.keys_scrollview.effect_cls = ScrollEffect + info1 = "[size=18dp][b]Encryption Keys[/b][/size][size=5dp]\n \n[/size]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." + info2 = "[size=18dp][b]Backup & Restore[/b][/size][size=5dp]\n \n[/size]You can backup your entire Sideband profile for import on a computer or other device. The exported backup archive will be saved in the downloads folder of your device. Please note that the exported archive contains all your messages, data and encryption keys. Take extreme care to keep this archive secure." + + if not RNS.vendor.platformutils.get_platform() == "android": + self.app.widget_hide(self.keys_screen.ids.keys_share) + + self.keys_screen.ids.keys_info.text = info1 + self.keys_screen.ids.backup_info.text = info2 + + + def _profile_backup_job(self): + import tarfile + import plyer + from .helpers import file_ts_format + from kivy.clock import Clock + output_path = plyer.storagepath.get_downloads_dir() + time_str = time.strftime(file_ts_format, time.localtime(time.time())) + target_file = f"{output_path}/sideband_backup_{time_str}.tar.gz" + tar = tarfile.open(target_file, "w:gz") + tar.add(f"{self.app.sideband.app_dir}/app_storage", arcname="Sideband Backup") + tar.close() + + def job(dt): + self.keys_screen.ids.keys_backup.disabled = False + toast("Backup done") + ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog(text=f"Backup has been saved to {target_file}", + buttons=[ok_button]) + def dl_yes(s): dialog.dismiss() + + ok_button.bind(on_release=dl_yes) + dialog.open() + + Clock.schedule_once(job, 0.3) + + def profile_backup_action(self, sender=None): + self.keys_screen.ids.keys_backup.disabled = True + toast("Creating backup...") + threading.Thread(target=self._profile_backup_job, daemon=True).start() + + def identity_display_action(self, sender=None): + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + + dialog = MDDialog( + text="Your Identity key, in base32 format is as follows:\n\n[b]"+str(base64.b32encode(self.app.sideband.identity.get_private_key()).decode("utf-8"))+"[/b]", + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + + yes_button.bind(on_release=dl_yes) + dialog.open() + + def identity_copy_action(self, sender=None): + c_yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + c_no_button = MDRectangleFlatButton(text="No, go back",font_size=dp(18)) + c_dialog = MDDialog(text="[b]Caution![/b]\n\nYour Identity key will be copied to the system clipboard. Take extreme care that no untrusted app steals your key by reading the clipboard data. Clear the system clipboard immediately after pasting your key where you need it.\n\nAre you sure that you wish to proceed?", buttons=[ c_no_button, c_yes_button ]) + def c_dl_no(s): + c_dialog.dismiss() + def c_dl_yes(s): + c_dialog.dismiss() + yes_button = MDRectangleFlatButton(text="OK") + dialog = MDDialog(text="Your Identity key was copied to the system clipboard", buttons=[ yes_button ]) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + + Clipboard.copy(str(base64.b32encode(self.app.sideband.identity.get_private_key()).decode("utf-8"))) + dialog.open() + + c_yes_button.bind(on_release=c_dl_yes) + c_no_button.bind(on_release=c_dl_no) + + c_dialog.open() + + def identity_share_action(self, sender=None): + if RNS.vendor.platformutils.get_platform() == "android": + self.share_text(str(base64.b32encode(self.app.sideband.identity.get_private_key()).decode("utf-8"))) + + def identity_restore_action(self, sender=None): + c_yes_button = MDRectangleFlatButton(text="Yes",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_reject, text_color=self.app.color_reject) + c_no_button = MDRectangleFlatButton(text="No, go back",font_size=dp(18)) + c_dialog = MDDialog(text="[b]Caution![/b]\n\nYou are about to import a new Identity key into Sideband. The currently active key will be irreversibly destroyed, and you will loose your LXMF address if you have not already backed up your current Identity key.\n\nAre you sure that you wish to import the key?", buttons=[ c_no_button, c_yes_button ]) + def c_dl_no(s): + c_dialog.dismiss() + def c_dl_yes(s): + c_dialog.dismiss() + b32_text = self.keys_screen.ids.key_restore_text.text + + try: + key_bytes = base64.b32decode(b32_text) + new_id = RNS.Identity.from_bytes(key_bytes) + + if new_id != None: + new_id.to_file(self.app.sideband.identity_path) + + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog(text="[b]The provided Identity key data was imported[/b]\n\nThe app will now exit. Please restart Sideband to use the new Identity.", buttons=[ yes_button ]) + def dl_yes(s): + dialog.dismiss() + self.app.quit_action(sender=self) + yes_button.bind(on_release=dl_yes) + dialog.open() + + except Exception as e: + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog(text="[b]The provided Identity key data was not valid[/b]\n\nThe error reported by Reticulum was:\n\n[i]"+str(e)+"[/i]\n\nNo Identity was imported into Sideband.", buttons=[ yes_button ]) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + dialog.open() + + + c_yes_button.bind(on_release=c_dl_yes) + c_no_button.bind(on_release=c_dl_no) + + c_dialog.open() + + +layout_keys_screen = """ +MDScreen: + name: "keys_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Backup & Keys" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.close_keys_action(self)], + ] + + ScrollView: + id:keys_scrollview + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(35), dp(35), dp(35), dp(35)] + + + MDLabel: + id: backup_info + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDRectangleFlatIconButton: + id: keys_backup + icon: "home-export-outline" + text: "Backup Sideband Profile" + 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.app.profile_backup_action(self) + + MDRectangleFlatIconButton: + id: keys_restore + icon: "home-import-outline" + text: "Restore Sideband Profile" + disabled: True + 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.app.profile_backup_action(self) + + MDLabel: + id: keys_info + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDRectangleFlatIconButton: + id: keys_display + icon: "eye" + text: "Display Identity Key" + 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.app.identity_display_action(self) + + MDRectangleFlatIconButton: + id: keys_copy + icon: "file-key" + text: "Copy Key To Clipboard" + 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.app.identity_copy_action(self) + + MDRectangleFlatIconButton: + id: keys_share + icon: "upload-lock" + text: "Send Key To Other App" + 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.app.identity_share_action(self) + + MDBoxLayout: + orientation: "vertical" + # spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(12), dp(0), dp(0)] + + MDTextField: + id: key_restore_text + hint_text: "Enter base32 key for import" + mode: "rectangle" + # size_hint: [1.0, None] + pos_hint: {"center_x": .5} + + MDRectangleFlatIconButton: + id: keys_restore + icon: "download-lock" + text: "Restore Identity From Key" + 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.app.identity_restore_action(self) +""" \ No newline at end of file diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 46c67cd..6ef961e 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -1053,127 +1053,6 @@ MDScreen: id: map_layout """ -layout_keys_screen = """ -MDScreen: - name: "keys_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "Backup & Keys" - anchor_title: "left" - elevation: 0 - left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] - right_action_items: - [ - ['close', lambda x: root.app.close_keys_action(self)], - ] - - ScrollView: - id:keys_scrollview - - MDBoxLayout: - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(35), dp(35), dp(35), dp(35)] - - - MDLabel: - id: backup_info - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDRectangleFlatIconButton: - id: keys_backup - icon: "home-export-outline" - text: "Backup Sideband Profile" - 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.app.profile_backup_action(self) - - MDRectangleFlatIconButton: - id: keys_restore - icon: "home-import-outline" - text: "Restore Sideband Profile" - disabled: True - 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.app.profile_backup_action(self) - - MDLabel: - id: keys_info - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDRectangleFlatIconButton: - id: keys_display - icon: "eye" - text: "Display Identity Key" - 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.app.identity_display_action(self) - - MDRectangleFlatIconButton: - id: keys_copy - icon: "file-key" - text: "Copy Key To Clipboard" - 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.app.identity_copy_action(self) - - MDRectangleFlatIconButton: - id: keys_share - icon: "upload-lock" - text: "Send Key To Other App" - 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.app.identity_share_action(self) - - MDBoxLayout: - orientation: "vertical" - # spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(12), dp(0), dp(0)] - - MDTextField: - id: key_restore_text - hint_text: "Enter base32 key for import" - mode: "rectangle" - # size_hint: [1.0, None] - pos_hint: {"center_x": .5} - - MDRectangleFlatIconButton: - id: keys_restore - icon: "download-lock" - text: "Restore Identity From Key" - 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.app.identity_restore_action(self) -""" - layout_plugins_screen = """ MDScreen: name: "plugins_screen" From 7ddea1e175924e7a878e34e7f92398d6df37ae32 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 25 Dec 2025 22:20:34 +0100 Subject: [PATCH 221/271] Refactored hardware screen --- sbapp/main.py | 971 +---------------------- sbapp/sideband/core.py | 6 +- sbapp/ui/hardware.py | 1691 ++++++++++++++++++++++++++++++++++++++++ sbapp/ui/layouts.py | 714 ----------------- 4 files changed, 1712 insertions(+), 1670 deletions(-) create mode 100644 sbapp/ui/hardware.py diff --git a/sbapp/main.py b/sbapp/main.py index 7fe6601..3974c05 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -437,6 +437,7 @@ else: from ui.voice import Voice from ui.guide import Guide from ui.keys import Keys + from ui.hardware import Hardware from ui.objectdetails import ObjectDetails from ui.announces import Announces from ui.messages import Messages, ts_format, messages_screen_kv @@ -471,6 +472,7 @@ else: from .ui.voice import Voice from .ui.guide import Guide from .ui.keys import Keys + from .ui.hardware import Hardware from .ui.objectdetails import ObjectDetails from .ui.messages import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem @@ -546,6 +548,7 @@ class SidebandApp(MDApp): self.map_layer = None self.map_screen = None self.telemetry_screen = None + self.connectivity_screen = None self.map_cache = self.sideband.map_cache self.offline_source = None self.map_settings_screen = None @@ -558,9 +561,6 @@ class SidebandApp(MDApp): self.connectivity_ready = False self.hardware_ready = False self.repository_ready = False - self.hardware_rnode_ready = False - self.hardware_modem_ready = False - self.hardware_serial_ready = False self.hw_error_dialog = None self.final_load_completed = False @@ -1139,18 +1139,17 @@ class SidebandApp(MDApp): def request_location_permissions(self): if not self.has_location_permissions(): - RNS.log("Requesting location permission", RNS.LOG_DEBUG) - request_permissions(["android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"]) + if RNS.vendor.platformutils.is_android(): + RNS.log("Requesting location permission", RNS.LOG_DEBUG) + request_permissions(["android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"]) def check_bluetooth_permissions(self): if RNS.vendor.platformutils.get_platform() == "android": mActivity = autoclass('org.kivy.android.PythonActivity').mActivity Context = autoclass('android.content.Context') - if android_api_version > 30: - bt_permission_name = "android.permission.BLUETOOTH_CONNECT" - else: - bt_permission_name = "android.permission.BLUETOOTH" + if android_api_version > 30: bt_permission_name = "android.permission.BLUETOOTH_CONNECT" + else: bt_permission_name = "android.permission.BLUETOOTH" if check_permission(bt_permission_name): RNS.log("Have bluetooth connect permissions", RNS.LOG_DEBUG) @@ -1302,7 +1301,7 @@ class SidebandApp(MDApp): toast("Starting Bluetooth scan...") RNS.log("Starting bluetooth scan", RNS.LOG_DEBUG) self.discovered_bt_devices = {} - threading.Thread(target=self.hardware_rnode_scan_job, daemon=True).start() + if self.hardware_view: threading.Thread(target=self.hardware_view.hardware_rnode_scan_job, daemon=True).start() BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') self.bt_found_action = BluetoothDevice.ACTION_FOUND @@ -1449,6 +1448,7 @@ class SidebandApp(MDApp): self.announces_view = None self.guide_view = None self.keys_view = None + self.hardware_view = None if RNS.vendor.platformutils.is_android(): ActivityInfo = autoclass('android.content.pm.ActivityInfo') @@ -4381,966 +4381,33 @@ class SidebandApp(MDApp): ### Hardware screen ###################################### def hardware_action(self, sender=None, direction="left"): - if self.hardware_ready: - self.hardware_open(direction=direction) + if self.hardware_ready: self.hardware_open(direction=direction) else: self.loader_action(direction=direction) def final(dt): - self.hardware_init() - def o(dt): - self.hardware_open(no_transition=True) + self.init_hardware_view() + def o(dt): self.hardware_open(no_transition=True) Clock.schedule_once(o, ll_ot) Clock.schedule_once(final, ll_ft) def hardware_open(self, sender=None, direction="left", no_transition=False): - if no_transition: - self.root.ids.screen_manager.transition = self.no_transition + if no_transition: self.root.ids.screen_manager.transition = self.no_transition else: self.root.ids.screen_manager.transition = self.slide_transition self.root.ids.screen_manager.transition.direction = direction - self.hardware_init() self.root.ids.screen_manager.transition.direction = direction self.root.ids.screen_manager.current = "hardware_screen" self.root.ids.nav_drawer.set_state("closed") self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) - if no_transition: - self.root.ids.screen_manager.transition = self.slide_transition + if no_transition: self.root.ids.screen_manager.transition = self.slide_transition - def close_sub_hardware_action(self, sender=None): - self.hardware_action(direction="right") - - def hardware_init(self, sender=None): - if not self.hardware_ready: - if not self.root.ids.screen_manager.has_screen("hardware_screen"): - self.hardware_screen = Builder.load_string(layout_hardware_screen) - self.hardware_screen.app = self - self.root.ids.screen_manager.add_widget(self.hardware_screen) + def init_hardware_view(self, sender=None): + if not self.hardware_view: self.hardware_view = Hardware(self) - self.hardware_screen.ids.hardware_scrollview.effect_cls = ScrollEffect - - def con_hide_settings(): - self.widget_hide(self.hardware_screen.ids.hardware_rnode_button) - self.widget_hide(self.hardware_screen.ids.hardware_modem_button) - self.widget_hide(self.hardware_screen.ids.hardware_serial_button) - - if RNS.vendor.platformutils.get_platform() == "android": - if not self.sideband.getpersistent("service.is_controlling_connectivity"): - info = "Sideband is connected via a shared Reticulum instance running on this system.\n\n" - info += "To configure hardware parameters, edit the relevant configuration file for the instance." - self.hardware_screen.ids.hardware_info.text = info - con_hide_settings() - - else: - info = "When using external hardware for communicating, you may configure various parameters, such as channel settings, modulation schemes, interface speeds and access parameters. You can set up these parameters per device type, and Sideband will apply the configuration when opening a device of that type.\n\n" - info += "Hardware configurations can also be exported or imported as [i]config motes[/i], which are self-contained plaintext strings that are easy to share with others. When importing a config mote, Sideband will automatically set all relevant parameters as specified within it.\n\n" - info += "For changes to hardware parameters to take effect, you must shut down and restart Sideband.\n" - self.hardware_screen.ids.hardware_info.text = info - - else: - info = "" - - if self.sideband.reticulum.is_connected_to_shared_instance: - info = "Sideband is connected via a shared Reticulum instance running on this system.\n\n" - info += "To configure hardware parameters, edit the configuration file located at:\n\n" - if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) - else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) - else: - info = "Sideband is currently running a standalone or master Reticulum instance on this system.\n\n" - info += "To configure hardware parameters, edit the configuration file located at:\n\n" - if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) - else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) - - self.hardware_screen.ids.hardware_info.text = info - - con_hide_settings() - - self.hardware_ready = True - - def close_hardware_action(self, sender=None): - self.open_conversations(direction="right") - - ## RNode hardware screen - def hardware_rnode_action(self, sender=None, direction="left"): - if self.hardware_rnode_ready: - self.hardware_rnode_open(direction=direction) - else: - self.loader_action(direction=direction) - def final(dt): - self.hardware_rnode_init() - def o(dt): - self.hardware_rnode_open(no_transition=True) - Clock.schedule_once(o, ll_ot) - Clock.schedule_once(final, ll_ft) - - def hardware_rnode_open(self, sender=None, direction="left", no_transition=False): - if no_transition: - self.root.ids.screen_manager.transition = self.no_transition - else: - self.root.ids.screen_manager.transition = self.slide_transition - self.root.ids.screen_manager.transition.direction = direction - - self.root.ids.screen_manager.transition.direction = "left" - self.root.ids.screen_manager.current = "hardware_rnode_screen" - self.root.ids.nav_drawer.set_state("closed") - self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) - - if no_transition: - self.root.ids.screen_manager.transition = self.slide_transition - - def hardware_rnode_save(self): - try: self.sideband.config["hw_rnode_frequency"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_frequency.text)*1000000) - except: pass - - try: self.sideband.config["hw_rnode_bandwidth"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text)*1000) - except: pass - - try: self.sideband.config["hw_rnode_tx_power"] = int(self.hardware_rnode_screen.ids.hardware_rnode_txpower.text) - except: pass - - try: self.sideband.config["hw_rnode_spreading_factor"] = int(self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text) - except: pass - - try: self.sideband.config["hw_rnode_coding_rate"] = int(self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text) - except: pass - - try: self.sideband.config["hw_rnode_atl_short"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text) - except: self.sideband.config["hw_rnode_atl_short"] = None - - try: self.sideband.config["hw_rnode_atl_long"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text) - except: self.sideband.config["hw_rnode_atl_long"] = None - - if self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text == "": self.sideband.config["hw_rnode_beaconinterval"] = None - else: - try: self.sideband.config["hw_rnode_beaconinterval"] = int(self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text) - except: pass - - if self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text == "": self.sideband.config["hw_rnode_beacondata"] = None - else: self.sideband.config["hw_rnode_beacondata"] = self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text - - if self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text == "": self.sideband.config["hw_rnode_bt_device"] = None - else: self.sideband.config["hw_rnode_bt_device"] = self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text - - if self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text == "": self.sideband.config["hw_rnode_tcp_host"] = None - else: self.sideband.config["hw_rnode_tcp_host"] = self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text - - self.sideband.save_configuration() - - def hardware_rnode_scan_job(self): - time.sleep(1.25) - added_devices = [] - scan_timeout = time.time()+16 - while time.time() < scan_timeout: - RNS.log("Scanning...", RNS.LOG_DEBUG) - for device_addr in self.discovered_bt_devices: - if device_addr not in added_devices and not device_addr in self.bt_bonded_devices: - new_device = self.discovered_bt_devices[device_addr] - added_devices.append(device_addr) - RNS.log(f"Adding device: {new_device}") - def add_factory(add_device): - def add_job(dt): - pair_addr = add_device["address"] - btn_text = "Pair "+add_device["name"] - def run_pair(sender): - self.hardware_rnode_pair_device_action(pair_addr) - def job(): self.hardware_rnode_pair_check_job(pair_addr, add_device["name"]) - threading.Thread(target=job, daemon=True).start() - - device_button = MDRectangleFlatButton(text=btn_text, font_size=dp(16), padding=[dp(0), dp(14), dp(0), dp(14)], size_hint=[1.0, None]) - device_button.bind(on_release=run_pair) - self.hardware_rnode_screen.ids.rnode_scan_results.add_widget(device_button) - return add_job - - Clock.schedule_once(add_factory(new_device), 0.1) - - time.sleep(2) - - def job(dt): - self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Pair New Device" - Clock.schedule_once(job, 0.2) - - if len(added_devices) == 0: - def job(dt): toast("No unpaired RNodes discovered") - Clock.schedule_once(job, 0.2) - - def hardware_rnode_pair_check_job(self, pair_addr, device_name): - timeout = time.time()+45 - pairing_confirmed = False - while not pairing_confirmed and time.time() < timeout: - time.sleep(2) - self.bluetooth_update_bonded_devices() - if pair_addr in self.bt_bonded_devices: - pairing_confirmed = True - RNS.log(f"Pairing with {device_name} ({pair_addr}) successful", RNS.LOG_NOTICE) - def job(dt=None): toast(f"Paired with {device_name}") - Clock.schedule_once(job, 0.2) - - def hardware_rnode_pair_device_action(self, pair_addr): - RNS.log(f"Pair action for {pair_addr}", RNS.LOG_DEBUG) - self.stop_bluetooth_scan() - BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket') - if self.bt_adapter == None: self.bt_adapter = BluetoothAdapter.getDefaultAdapter() - addr_bytes = bytes.fromhex(pair_addr.replace(":", "")) - remote_device = self.bt_adapter.getRemoteDevice(addr_bytes) - RNS.log(f"Remote device: {remote_device}", RNS.LOG_DEBUG) - remote_device.createBond() - RNS.log("Create bond call returned", RNS.LOG_DEBUG) - - def hardware_rnode_bt_scan_action(self, sender=None): - self.discovered_bt_devices = {} - rw = [] - for child in self.hardware_rnode_screen.ids.rnode_scan_results.children: rw.append(child) - for w in rw: self.hardware_rnode_screen.ids.rnode_scan_results.remove_widget(w) - - Clock.schedule_once(self.bluetooth_scan_action, 0.5) - - def hardware_rnode_bt_on_action(self, sender=None): - self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = True - def re_enable(): - time.sleep(2) - while self.sideband.getstate("executing.bt_on"): - time.sleep(1) - self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = False - threading.Thread(target=re_enable, daemon=True).start() - self.sideband.setstate("wants.bt_on", True) - - def hardware_rnode_bt_off_action(self, sender=None): - self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = True - def re_enable(): - time.sleep(2) - while self.sideband.getstate("executing.bt_off"): - time.sleep(1) - self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = False - threading.Thread(target=re_enable, daemon=True).start() - self.sideband.setstate("wants.bt_off", True) - - def hardware_rnode_bt_pair_action(self, sender=None): - self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True - self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = True - def re_enable(): - time.sleep(2) - while self.sideband.getstate("executing.bt_pair"): - time.sleep(1) - self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = False - self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = False - threading.Thread(target=re_enable, daemon=True).start() - self.sideband.setstate("wants.bt_pair", True) - - def hardware_rnode_bt_toggle_action(self, sender=None, event=None): - if sender.active: - self.sideband.config["hw_rnode_bluetooth"] = True - self.request_bluetooth_permissions() - else: - self.sideband.config["hw_rnode_bluetooth"] = False - - self.sideband.save_configuration() - - def hardware_rnode_ble_toggle_action(self, sender=None, event=None): - if sender.active: - self.sideband.config["hw_rnode_ble"] = True - self.request_bluetooth_permissions() - else: - self.sideband.config["hw_rnode_ble"] = False - - self.sideband.save_configuration() - - def hardware_rnode_framebuffer_toggle_action(self, sender=None, event=None): - if sender.active: - self.sideband.config["hw_rnode_enable_framebuffer"] = True - else: - self.sideband.config["hw_rnode_enable_framebuffer"] = False - - self.sideband.save_configuration() - - def hardware_rnode_tcp_toggle_action(self, sender=None, event=None): - if sender.active: self.sideband.config["hw_rnode_tcp"] = True - else: self.sideband.config["hw_rnode_tcp"] = False - - self.sideband.save_configuration() - - def hardware_rnode_init(self, sender=None): - if not self.hardware_rnode_ready: - if not self.root.ids.screen_manager.has_screen("hardware_rnode_screen"): - self.hardware_rnode_screen = Builder.load_string(layout_hardware_rnode_screen) - self.hardware_rnode_screen.app = self - self.root.ids.screen_manager.add_widget(self.hardware_rnode_screen) - - self.hardware_rnode_screen.ids.hardware_rnode_scrollview.effect_cls = ScrollEffect - def save_connectivity(sender=None, event=None): - if self.hardware_rnode_validate(): - self.hardware_rnode_save() - - def focus_save(sender=None, event=None): - if sender != None: - if not sender.focus: - save_connectivity(sender=sender) - - if self.sideband.config["hw_rnode_frequency"] != None: t_freq = str(self.sideband.config["hw_rnode_frequency"]/1000000.0) - else: t_freq = "" - - if self.sideband.config["hw_rnode_bandwidth"] != None: t_bw = str(self.sideband.config["hw_rnode_bandwidth"]/1000.0) - else: t_bw = str(62.5) - - if self.sideband.config["hw_rnode_tx_power"] != None: t_p = str(self.sideband.config["hw_rnode_tx_power"]) - else: t_p = str(0) - - if self.sideband.config["hw_rnode_spreading_factor"] != None: t_sf = str(self.sideband.config["hw_rnode_spreading_factor"]) - else: t_sf = str(8) - - if self.sideband.config["hw_rnode_coding_rate"] != None: t_cr = str(self.sideband.config["hw_rnode_coding_rate"]) - else: t_cr = str(6) - - if self.sideband.config["hw_rnode_beaconinterval"] != None: t_bi = str(self.sideband.config["hw_rnode_beaconinterval"]) - else: t_bi = "" - - if self.sideband.config["hw_rnode_beacondata"] != None: t_bd = str(self.sideband.config["hw_rnode_beacondata"]) - else: t_bd = "" - - if self.sideband.config["hw_rnode_bt_device"] != None: t_btd = str(self.sideband.config["hw_rnode_bt_device"]) - else: t_btd = "" - - if self.sideband.config["hw_rnode_tcp_host"] != None: t_th = str(self.sideband.config["hw_rnode_tcp_host"]) - else: t_th = "" - - if self.sideband.config["hw_rnode_atl_short"] != None: t_ats = str(self.sideband.config["hw_rnode_atl_short"]) - else: t_ats = "" - - if self.sideband.config["hw_rnode_atl_long"] != None: t_atl = str(self.sideband.config["hw_rnode_atl_long"]) - else: t_atl = "" - - self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.active = self.sideband.config["hw_rnode_bluetooth"] - self.hardware_rnode_screen.ids.hardware_rnode_ble.active = self.sideband.config["hw_rnode_ble"] - self.hardware_rnode_screen.ids.hardware_rnode_tcp.active = self.sideband.config["hw_rnode_tcp"] - self.hardware_rnode_screen.ids.hardware_rnode_framebuffer.active = self.sideband.config["hw_rnode_enable_framebuffer"] - self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = t_freq - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = t_bw - self.hardware_rnode_screen.ids.hardware_rnode_txpower.text = t_p - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text = t_sf - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text = t_cr - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = t_bi - self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text = t_bd - self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text = t_btd - self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text = t_th - self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text = t_ats - self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text = t_atl - self.hardware_rnode_screen.ids.hardware_rnode_frequency.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_txpower.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_beacondata.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_bt_device.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.bind(focus=focus_save) - self.hardware_rnode_screen.ids.hardware_rnode_frequency.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_txpower.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_beacondata.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_atl_short.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_atl_long.bind(on_text_validate=save_connectivity) - self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.bind(active=self.hardware_rnode_bt_toggle_action) - self.hardware_rnode_screen.ids.hardware_rnode_ble.bind(active=self.hardware_rnode_ble_toggle_action) - self.hardware_rnode_screen.ids.hardware_rnode_framebuffer.bind(active=self.hardware_rnode_framebuffer_toggle_action) - self.hardware_rnode_screen.ids.hardware_rnode_tcp.bind(active=self.hardware_rnode_tcp_toggle_action) - - self.hardware_rnode_ready = True - - def hardware_rnode_validate(self, sender=None): - valid = True - try: - val = float(self.hardware_rnode_screen.ids.hardware_rnode_frequency.text) - if not val > 0: - raise ValueError("Invalid frequency") - self.hardware_rnode_screen.ids.hardware_rnode_frequency.error = False - self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = str(val) - except: - self.hardware_rnode_screen.ids.hardware_rnode_frequency.error = True - valid = False - - try: - 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") - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.error = False - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = str(val) - except: - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.error = True - valid = False - - try: - val = int(self.hardware_rnode_screen.ids.hardware_rnode_txpower.text) - if not val >= 0: - raise ValueError("Invalid TX power") - self.hardware_rnode_screen.ids.hardware_rnode_txpower.error = False - self.hardware_rnode_screen.ids.hardware_rnode_txpower.text = str(val) - except: - self.hardware_rnode_screen.ids.hardware_rnode_txpower.error = True - valid = False - - try: - val = int(self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text) - if val < 7 or val > 12: - raise ValueError("Invalid sf") - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.error = False - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text = str(val) - except: - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.error = True - valid = False - - try: - val = int(self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text) - if val < 5 or val > 8: - raise ValueError("Invalid cr") - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.error = False - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text = str(val) - except: - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.error = True - valid = False - - try: - if self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text != "": - val = int(self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text) - if val < 10: - raise ValueError("Invalid beacon interval") - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = str(val) - - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.error = False - except: - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = "" - valid = False - - return valid - - def hardware_rnode_import(self, sender=None): - mote = None - try: - mote = Clipboard.paste() - except Exception as e: - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog( - title="Import Failed", - text="Could not read data from your clipboard, please check your system permissions.", - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - dialog.open() - - try: - config = msgpack.unpackb(base64.b32decode(mote)) - self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = str(config["f"]/1000000.0) - self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = str(config["b"]/1000.0) - self.hardware_rnode_screen.ids.hardware_rnode_txpower.text = str(config["t"]) - self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text = str(config["s"]) - self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text = str(config["c"]) - - if "n" in config and config["n"] != None: - ifn = str(config["n"]) - else: - ifn = "" - if "p" in config and config["p"] != None: - ifp = str(config["p"]) - else: - ifp = "" - - self.connectivity_screen.ids.connectivity_rnode_ifac_netname.text = ifn - self.sideband.config["connect_rnode_ifac_netname"] = ifn - self.connectivity_screen.ids.connectivity_rnode_ifac_passphrase.text = ifp - self.sideband.config["connect_rnode_ifac_passphrase"] = ifp - - if config["i"] != None: - ti = str(config["i"]) - else: - ti = "" - self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = ti - if config["d"] != None: - td = str(config["d"]) - else: - td = "" - self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text = td - - if self.hardware_rnode_validate(): - self.hardware_rnode_save() - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog( - title="Configuration Imported", - text="The config mote was imported and saved as your active configuration.", - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - dialog.open() - else: - raise ValueError("Invalid mote") - - except Exception as e: - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog( - title="Import Failed", - text="The read data did not contain a valid config mote. If any data was decoded, you may try to correct it by editing the relevant fields. The reported error was:\n\n"+str(e), - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - dialog.open() - - def hardware_rnode_export(self, sender=None): - mote = None - try: - mote = base64.b32encode(msgpack.packb({ - "f": self.sideband.config["hw_rnode_frequency"], - "b": self.sideband.config["hw_rnode_bandwidth"], - "t": self.sideband.config["hw_rnode_tx_power"], - "s": self.sideband.config["hw_rnode_spreading_factor"], - "c": self.sideband.config["hw_rnode_coding_rate"], - "i": self.sideband.config["hw_rnode_beaconinterval"], - "d": self.sideband.config["hw_rnode_beacondata"], - "n": self.sideband.config["connect_rnode_ifac_netname"], - "p": self.sideband.config["connect_rnode_ifac_passphrase"], - })) - except Exception as e: - pass - - if mote != None: - Clipboard.copy(mote) - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog( - title="Configuration Exported", - text="The config mote was created and copied to your clipboard.", - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - dialog.open() - else: - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog( - title="Export Failed", - text="The config mote could not be created, please check your settings.", - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - dialog.dismiss() - yes_button.bind(on_release=dl_yes) - dialog.open() - - ## Modem hardware screen - - def hardware_modem_action(self, sender=None, direction="left"): - if self.hardware_modem_ready: - self.hardware_modem_open(direction=direction) - else: - self.loader_action(direction=direction) - def final(dt): - self.hardware_modem_init() - def o(dt): - self.hardware_modem_open(no_transition=True) - Clock.schedule_once(o, ll_ot) - Clock.schedule_once(final, ll_ft) - - def hardware_modem_open(self, sender=None, direction="left", no_transition=False): - if no_transition: - self.root.ids.screen_manager.transition = self.no_transition - else: - self.root.ids.screen_manager.transition = self.slide_transition - self.root.ids.screen_manager.transition.direction = direction - - self.hardware_modem_init() - self.root.ids.screen_manager.transition.direction = "left" - self.root.ids.screen_manager.current = "hardware_modem_screen" - self.root.ids.nav_drawer.set_state("closed") - self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) - - if no_transition: - self.root.ids.screen_manager.transition = self.slide_transition - - def hardware_modem_init(self, sender=None): - if not self.hardware_modem_ready: - if not self.root.ids.screen_manager.has_screen("hardware_modem_screen"): - self.hardware_modem_screen = Builder.load_string(layout_hardware_modem_screen) - self.hardware_modem_screen.app = self - self.root.ids.screen_manager.add_widget(self.hardware_modem_screen) - - self.hardware_modem_screen.ids.hardware_modem_scrollview.effect_cls = ScrollEffect - def save_connectivity(sender=None, event=None): - if self.hardware_modem_validate(): - self.hardware_modem_save() - - def focus_save(sender=None, event=None): - if sender != None: - if not sender.focus: - save_connectivity(sender=sender) - - if self.sideband.config["hw_modem_baudrate"] != None: - t_b = str(self.sideband.config["hw_modem_baudrate"]) - else: - t_b = "" - - if self.sideband.config["hw_modem_databits"] != None: - t_db = str(self.sideband.config["hw_modem_databits"]) - else: - t_db = "" - - if self.sideband.config["hw_modem_parity"] != None: - t_p = str(self.sideband.config["hw_modem_parity"]) - else: - t_p = "" - - if self.sideband.config["hw_modem_stopbits"] != None: - t_sb = str(self.sideband.config["hw_modem_stopbits"]) - else: - t_sb = "" - - if self.sideband.config["hw_modem_preamble"] != None: - t_pa = str(self.sideband.config["hw_modem_preamble"]) - else: - t_pa = "" - - if self.sideband.config["hw_modem_tail"] != None: - t_t = str(self.sideband.config["hw_modem_tail"]) - else: - t_t = "" - - if self.sideband.config["hw_modem_persistence"] != None: - t_ps = str(self.sideband.config["hw_modem_persistence"]) - else: - t_ps = "" - - if self.sideband.config["hw_modem_slottime"] != None: - t_st = str(self.sideband.config["hw_modem_slottime"]) - else: - t_st = "" - - if self.sideband.config["hw_modem_beaconinterval"] != None: - t_bi = str(self.sideband.config["hw_modem_beaconinterval"]) - else: - t_bi = "" - if self.sideband.config["hw_modem_beacondata"] != None: - t_bd = str(self.sideband.config["hw_modem_beacondata"]) - else: - t_bd = "" - - self.hardware_modem_screen.ids.hardware_modem_baudrate.text = t_b - self.hardware_modem_screen.ids.hardware_modem_databits.text = t_db - self.hardware_modem_screen.ids.hardware_modem_parity.text = t_p - self.hardware_modem_screen.ids.hardware_modem_stopbits.text = t_sb - self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text = t_bi - self.hardware_modem_screen.ids.hardware_modem_beacondata.text = t_bd - self.hardware_modem_screen.ids.hardware_modem_preamble.text = t_pa - self.hardware_modem_screen.ids.hardware_modem_tail.text = t_t - self.hardware_modem_screen.ids.hardware_modem_persistence.text = t_ps - self.hardware_modem_screen.ids.hardware_modem_slottime.text = t_st - self.hardware_modem_screen.ids.hardware_modem_baudrate.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_databits.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_parity.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_stopbits.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_beaconinterval.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_beacondata.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_preamble.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_tail.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_persistence.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_slottime.bind(focus=focus_save) - self.hardware_modem_screen.ids.hardware_modem_baudrate.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_databits.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_parity.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_stopbits.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_beaconinterval.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_beacondata.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_preamble.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_tail.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_persistence.bind(on_text_validate=save_connectivity) - self.hardware_modem_screen.ids.hardware_modem_slottime.bind(on_text_validate=save_connectivity) - - self.hardware_modem_ready = True - - def hardware_modem_save(self): - self.sideband.config["hw_modem_baudrate"] = int(self.hardware_modem_screen.ids.hardware_modem_baudrate.text) - self.sideband.config["hw_modem_databits"] = int(self.hardware_modem_screen.ids.hardware_modem_databits.text) - self.sideband.config["hw_modem_parity"] = self.hardware_modem_screen.ids.hardware_modem_parity.text - self.sideband.config["hw_modem_stopbits"] = int(self.hardware_modem_screen.ids.hardware_modem_stopbits.text) - self.sideband.config["hw_modem_preamble"] = int(self.hardware_modem_screen.ids.hardware_modem_preamble.text) - self.sideband.config["hw_modem_tail"] = int(self.hardware_modem_screen.ids.hardware_modem_tail.text) - self.sideband.config["hw_modem_persistence"] = int(self.hardware_modem_screen.ids.hardware_modem_persistence.text) - self.sideband.config["hw_modem_slottime"] = int(self.hardware_modem_screen.ids.hardware_modem_slottime.text) - - if self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text == "": - self.sideband.config["hw_modem_beaconinterval"] = None - else: - self.sideband.config["hw_modem_beaconinterval"] = int(self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text) - - if self.hardware_modem_screen.ids.hardware_modem_beacondata.text == "": - self.sideband.config["hw_modem_beacondata"] = None - else: - self.sideband.config["hw_modem_beacondata"] = self.hardware_modem_screen.ids.hardware_modem_beacondata.text - - self.sideband.save_configuration() - - def hardware_modem_validate(self, sender=None): - valid = True - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_baudrate.text) - if not val > 0: - raise ValueError("Invalid baudrate") - self.hardware_modem_screen.ids.hardware_modem_baudrate.error = False - self.hardware_modem_screen.ids.hardware_modem_baudrate.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_baudrate.error = True - valid = False - - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_databits.text) - if not val > 0: - raise ValueError("Invalid databits") - self.hardware_modem_screen.ids.hardware_modem_databits.error = False - self.hardware_modem_screen.ids.hardware_modem_databits.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_databits.error = True - valid = False - - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_stopbits.text) - if not val > 0: - raise ValueError("Invalid stopbits") - self.hardware_modem_screen.ids.hardware_modem_stopbits.error = False - self.hardware_modem_screen.ids.hardware_modem_stopbits.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_stopbits.error = True - valid = False - - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_preamble.text) - if not (val >= 0 and val <= 1000): - raise ValueError("Invalid preamble") - self.hardware_modem_screen.ids.hardware_modem_preamble.error = False - self.hardware_modem_screen.ids.hardware_modem_preamble.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_preamble.error = True - valid = False - - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_tail.text) - if not (val > 0 and val <= 500): - raise ValueError("Invalid tail") - self.hardware_modem_screen.ids.hardware_modem_tail.error = False - self.hardware_modem_screen.ids.hardware_modem_tail.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_tail.error = True - valid = False - - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_slottime.text) - if not (val > 0 and val <= 500): - raise ValueError("Invalid slottime") - self.hardware_modem_screen.ids.hardware_modem_slottime.error = False - self.hardware_modem_screen.ids.hardware_modem_slottime.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_slottime.error = True - valid = False - - try: - val = int(self.hardware_modem_screen.ids.hardware_modem_persistence.text) - if not (val > 0 and val <= 255): - raise ValueError("Invalid persistence") - self.hardware_modem_screen.ids.hardware_modem_persistence.error = False - self.hardware_modem_screen.ids.hardware_modem_persistence.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_persistence.error = True - valid = False - - try: - val = self.hardware_modem_screen.ids.hardware_modem_parity.text - nval = val.lower() - if nval in ["e", "ev", "eve", "even"]: - val = "even" - if nval in ["o", "od", "odd"]: - val = "odd" - if nval in ["n", "no", "non", "none", "not", "null", "off"]: - val = "none" - if not val in ["even", "odd", "none"]: - raise ValueError("Invalid parity") - self.hardware_modem_screen.ids.hardware_modem_parity.error = False - self.hardware_modem_screen.ids.hardware_modem_parity.text = str(val) - except: - self.hardware_modem_screen.ids.hardware_modem_parity.error = True - valid = False - - try: - if self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text != "": - val = int(self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text) - if val < 10: - raise ValueError("Invalid bi") - self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text = str(val) - - self.hardware_modem_screen.ids.hardware_modem_beaconinterval.error = False - except: - self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text = "" - valid = False - - return valid - - ## Serial hardware screen - def hardware_serial_action(self, sender=None, direction="left"): - if self.hardware_serial_ready: - self.hardware_serial_open(direction=direction) - else: - self.loader_action(direction=direction) - def final(dt): - self.hardware_serial_init() - def o(dt): - self.hardware_serial_open(no_transition=True) - Clock.schedule_once(o, ll_ot) - Clock.schedule_once(final, ll_ft) - - def hardware_serial_open(self, sender=None, direction="left", no_transition=False): - if no_transition: - self.root.ids.screen_manager.transition = self.no_transition - else: - self.root.ids.screen_manager.transition = self.slide_transition - self.root.ids.screen_manager.transition.direction = direction - - self.root.ids.screen_manager.transition.direction = "left" - self.root.ids.screen_manager.current = "hardware_serial_screen" - self.root.ids.nav_drawer.set_state("closed") - self.sideband.setstate("app.displaying", self.root.ids.screen_manager.current) - - if no_transition: - self.root.ids.screen_manager.transition = self.slide_transition - - def hardware_serial_init(self, sender=None): - if not self.hardware_serial_ready: - if not self.root.ids.screen_manager.has_screen("hardware_serial_screen"): - self.hardware_serial_screen = Builder.load_string(layout_hardware_serial_screen) - self.hardware_serial_screen.app = self - self.root.ids.screen_manager.add_widget(self.hardware_serial_screen) - - self.hardware_serial_screen.ids.hardware_serial_scrollview.effect_cls = ScrollEffect - def save_connectivity(sender=None, event=None): - if self.hardware_serial_validate(): - self.hardware_serial_save() - - def focus_save(sender=None, event=None): - if sender != None: - if not sender.focus: - save_connectivity(sender=sender) - - if self.sideband.config["hw_serial_baudrate"] != None: - t_b = str(self.sideband.config["hw_serial_baudrate"]) - else: - t_b = "" - - if self.sideband.config["hw_serial_databits"] != None: - t_db = str(self.sideband.config["hw_serial_databits"]) - else: - t_db = "" - - if self.sideband.config["hw_serial_parity"] != None: - t_p = str(self.sideband.config["hw_serial_parity"]) - else: - t_p = "" - - if self.sideband.config["hw_serial_stopbits"] != None: - t_sb = str(self.sideband.config["hw_serial_stopbits"]) - else: - t_sb = "" - - self.hardware_serial_screen.ids.hardware_serial_baudrate.text = t_b - self.hardware_serial_screen.ids.hardware_serial_databits.text = t_db - self.hardware_serial_screen.ids.hardware_serial_parity.text = t_p - self.hardware_serial_screen.ids.hardware_serial_stopbits.text = t_sb - self.hardware_serial_screen.ids.hardware_serial_baudrate.bind(focus=focus_save) - self.hardware_serial_screen.ids.hardware_serial_databits.bind(focus=focus_save) - self.hardware_serial_screen.ids.hardware_serial_parity.bind(focus=focus_save) - self.hardware_serial_screen.ids.hardware_serial_stopbits.bind(focus=focus_save) - self.hardware_serial_screen.ids.hardware_serial_baudrate.bind(on_text_validate=save_connectivity) - self.hardware_serial_screen.ids.hardware_serial_databits.bind(on_text_validate=save_connectivity) - self.hardware_serial_screen.ids.hardware_serial_parity.bind(on_text_validate=save_connectivity) - self.hardware_serial_screen.ids.hardware_serial_stopbits.bind(on_text_validate=save_connectivity) - - self.hardware_serial_ready = True - - def hardware_serial_validate(self, sender=None): - valid = True - try: - val = int(self.hardware_serial_screen.ids.hardware_serial_baudrate.text) - if not val > 0: - raise ValueError("Invalid baudrate") - self.hardware_serial_screen.ids.hardware_serial_baudrate.error = False - self.hardware_serial_screen.ids.hardware_serial_baudrate.text = str(val) - except: - self.hardware_serial_screen.ids.hardware_serial_baudrate.error = True - valid = False - - try: - val = int(self.hardware_serial_screen.ids.hardware_serial_databits.text) - if not val > 0: - raise ValueError("Invalid databits") - self.hardware_serial_screen.ids.hardware_serial_databits.error = False - self.hardware_serial_screen.ids.hardware_serial_databits.text = str(val) - except: - self.hardware_serial_screen.ids.hardware_serial_databits.error = True - valid = False - - try: - val = int(self.hardware_serial_screen.ids.hardware_serial_stopbits.text) - if not val > 0: - raise ValueError("Invalid stopbits") - self.hardware_serial_screen.ids.hardware_serial_stopbits.error = False - self.hardware_serial_screen.ids.hardware_serial_stopbits.text = str(val) - except: - self.hardware_serial_screen.ids.hardware_serial_stopbits.error = True - valid = False - - try: - val = self.hardware_serial_screen.ids.hardware_serial_parity.text - nval = val.lower() - if nval in ["e", "ev", "eve", "even"]: - val = "even" - if nval in ["o", "od", "odd"]: - val = "odd" - if nval in ["n", "no", "non", "none", "not", "null", "off"]: - val = "none" - if not val in ["even", "odd", "none"]: - raise ValueError("Invalid parity") - self.hardware_serial_screen.ids.hardware_serial_parity.error = False - self.hardware_serial_screen.ids.hardware_serial_parity.text = str(val) - except: - self.hardware_serial_screen.ids.hardware_serial_parity.error = True - valid = False - - return valid - - def hardware_serial_save(self): - self.sideband.config["hw_serial_baudrate"] = int(self.hardware_serial_screen.ids.hardware_serial_baudrate.text) - self.sideband.config["hw_serial_databits"] = int(self.hardware_serial_screen.ids.hardware_serial_databits.text) - self.sideband.config["hw_serial_parity"] = self.hardware_serial_screen.ids.hardware_serial_parity.text - self.sideband.config["hw_serial_stopbits"] = int(self.hardware_serial_screen.ids.hardware_serial_stopbits.text) - - self.sideband.save_configuration() + def close_sub_hardware_action(self, sender=None): self.hardware_action(direction="right") + def close_hardware_action(self, sender=None): self.open_conversations(direction="right") ### Announce Stream screen ###################################### diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index f02152b..7d58d4d 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2036,10 +2036,8 @@ class SidebandCore(): except Exception as e: RNS.log("Error on client RPC connection: "+str(e), RNS.LOG_ERROR) RNS.trace_exception(e) - try: - connection.close() - except: - pass + try: connection.close() + except: pass return rpc_client_job diff --git a/sbapp/ui/hardware.py b/sbapp/ui/hardware.py new file mode 100644 index 0000000..24cc650 --- /dev/null +++ b/sbapp/ui/hardware.py @@ -0,0 +1,1691 @@ +import time +import RNS + +import base64 +import threading +import RNS.vendor.umsgpack as msgpack +from kivy.metrics import dp,sp +from kivy.lang.builder import Builder +from kivy.core.clipboard import Clipboard +from kivymd.uix.button import MDRectangleFlatButton +from kivymd.uix.dialog import MDDialog +from kivymd.toast import toast +from kivy.effects.scroll import ScrollEffect +from kivy.clock import Clock +from kivy.uix.screenmanager import NoTransition, SlideTransition + +TRANSITION_DURATION = 0.25 +if RNS.vendor.platformutils.is_android(): + ll_ot = 0.55 + ll_ft = 0.275 +else: + ll_ot = 0.4 + ll_ft = 0.275 + +if RNS.vendor.platformutils.is_android(): + from ui.helpers import dark_theme_text_color + from jnius import autoclass + BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter') +else: + from .helpers import dark_theme_text_color + + +class Hardware(): + + def __init__(self, app): + self.app = app + self.keys_screen = None + self.hardware_rnode_ready = False + self.hardware_modem_ready = False + self.hardware_serial_ready = False + + self.no_transition = NoTransition() + self.slide_transition = SlideTransition() + + if not self.app.hardware_ready: + if not self.app.root.ids.screen_manager.has_screen("hardware_screen"): + self.hardware_screen = Builder.load_string(layout_hardware_screen) + self.hardware_screen.app = self + self.app.root.ids.screen_manager.add_widget(self.hardware_screen) + + self.hardware_screen.ids.hardware_scrollview.effect_cls = ScrollEffect + + def con_hide_settings(): + return # TODO: RESET + self.app.widget_hide(self.hardware_screen.ids.hardware_rnode_button) + self.app.widget_hide(self.hardware_screen.ids.hardware_modem_button) + self.app.widget_hide(self.hardware_screen.ids.hardware_serial_button) + + if RNS.vendor.platformutils.get_platform() == "android": + if not self.app.sideband.getpersistent("service.is_controlling_connectivity"): + info = "Sideband is connected via a shared Reticulum instance running on this system.\n\n" + info += "To configure hardware parameters, edit the relevant configuration file for the instance." + self.hardware_screen.ids.hardware_info.text = info + con_hide_settings() + + else: + info = "When using external hardware for communicating, you may configure various parameters, such as channel settings, modulation schemes, interface speeds and access parameters. You can set up these parameters per device type, and Sideband will apply the configuration when opening a device of that type.\n\n" + info += "Hardware configurations can also be exported or imported as [i]config motes[/i], which are self-contained plaintext strings that are easy to share with others. When importing a config mote, Sideband will automatically set all relevant parameters as specified within it.\n\n" + info += "For changes to hardware parameters to take effect, you must shut down and restart Sideband.\n" + self.hardware_screen.ids.hardware_info.text = info + + else: + info = "" + + if self.app.sideband.reticulum.is_connected_to_shared_instance: + info = "Sideband is connected via a shared Reticulum instance running on this system.\n\n" + info += "To configure hardware parameters, edit the configuration file located at:\n\n" + if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) + else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) + else: + info = "Sideband is currently running a standalone or master Reticulum instance on this system.\n\n" + info += "To configure hardware parameters, edit the configuration file located at:\n\n" + if not RNS.vendor.platformutils.is_windows(): info += str(RNS.Reticulum.configpath) + else: info += str(RNS.Reticulum.configpath.replace("/", "\\")) + + self.hardware_screen.ids.hardware_info.text = info + + con_hide_settings() + + self.app.hardware_ready = True + + ## RNode hardware screen + def hardware_rnode_action(self, sender=None, direction="left"): + if self.hardware_rnode_ready: + self.hardware_rnode_open(direction=direction) + else: + self.app.loader_action(direction=direction) + def final(dt): + self.hardware_rnode_init() + def o(dt): + self.hardware_rnode_open(no_transition=True) + Clock.schedule_once(o, ll_ot) + Clock.schedule_once(final, ll_ft) + + def hardware_rnode_open(self, sender=None, direction="left", no_transition=False): + if no_transition: + self.app.root.ids.screen_manager.transition = self.no_transition + else: + self.app.root.ids.screen_manager.transition = self.slide_transition + self.app.root.ids.screen_manager.transition.direction = direction + + self.app.root.ids.screen_manager.transition.direction = "left" + self.app.root.ids.screen_manager.current = "hardware_rnode_screen" + self.app.root.ids.nav_drawer.set_state("closed") + self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) + + if no_transition: + self.app.root.ids.screen_manager.transition = self.slide_transition + + def hardware_rnode_save(self): + try: self.app.sideband.config["hw_rnode_frequency"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_frequency.text)*1000000) + except: pass + + try: self.app.sideband.config["hw_rnode_bandwidth"] = int(float(self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text)*1000) + except: pass + + try: self.app.sideband.config["hw_rnode_tx_power"] = int(self.hardware_rnode_screen.ids.hardware_rnode_txpower.text) + except: pass + + try: self.app.sideband.config["hw_rnode_spreading_factor"] = int(self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text) + except: pass + + try: self.app.sideband.config["hw_rnode_coding_rate"] = int(self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text) + except: pass + + try: self.app.sideband.config["hw_rnode_atl_short"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text) + except: self.app.sideband.config["hw_rnode_atl_short"] = None + + try: self.app.sideband.config["hw_rnode_atl_long"] = float(self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text) + except: self.app.sideband.config["hw_rnode_atl_long"] = None + + if self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text == "": self.app.sideband.config["hw_rnode_beaconinterval"] = None + else: + try: self.app.sideband.config["hw_rnode_beaconinterval"] = int(self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text) + except: pass + + if self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text == "": self.app.sideband.config["hw_rnode_beacondata"] = None + else: self.app.sideband.config["hw_rnode_beacondata"] = self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text + + if self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text == "": self.app.sideband.config["hw_rnode_bt_device"] = None + else: self.app.sideband.config["hw_rnode_bt_device"] = self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text + + if self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text == "": self.app.sideband.config["hw_rnode_tcp_host"] = None + else: self.app.sideband.config["hw_rnode_tcp_host"] = self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text + + self.app.sideband.save_configuration() + + def hardware_rnode_scan_job(self): + time.sleep(1.25) + added_devices = [] + scan_timeout = time.time()+16 + def job(dt): + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Scanning..." + Clock.schedule_once(job, 0.2) + while time.time() < scan_timeout: + RNS.log("Scanning...", RNS.LOG_DEBUG) + for device_addr in self.app.discovered_bt_devices: + if device_addr not in added_devices and not device_addr in self.app.bt_bonded_devices: + new_device = self.app.discovered_bt_devices[device_addr] + added_devices.append(device_addr) + RNS.log(f"Adding device: {new_device}") + def add_factory(add_device): + def add_job(dt): + pair_addr = add_device["address"] + btn_text = "Pair "+add_device["name"] + def run_pair(sender): + pair_result = self.hardware_rnode_pair_device_action(pair_addr) + if pair_result != "already_paired": + def job(): self.hardware_rnode_pair_check_job(pair_addr, add_device["name"]) + threading.Thread(target=job, daemon=True).start() + + device_button = MDRectangleFlatButton(text=btn_text, font_size=dp(16), padding=[dp(0), dp(14), dp(0), dp(14)], size_hint=[1.0, None]) + device_button.bind(on_release=run_pair) + self.hardware_rnode_screen.ids.rnode_scan_results.add_widget(device_button) + return add_job + + Clock.schedule_once(add_factory(new_device), 0.1) + + time.sleep(2) + + def job(dt): + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_scan_button.text = "Pair New Device" + Clock.schedule_once(job, 0.2) + + if len(added_devices) == 0: + def job(dt): toast("No unpaired RNodes discovered") + Clock.schedule_once(job, 0.2) + + def hardware_rnode_pair_check_job(self, pair_addr, device_name): + timeout = time.time()+45 + pairing_confirmed = False + while not pairing_confirmed and time.time() < timeout: + time.sleep(2) + self.app.bluetooth_update_bonded_devices() + if pair_addr in self.app.bt_bonded_devices: + pairing_confirmed = True + RNS.log(f"Pairing with {device_name} ({pair_addr}) successful", RNS.LOG_NOTICE) + def job(dt=None): toast(f"Paired with {device_name}") + Clock.schedule_once(job, 0.2) + + def hardware_rnode_pair_device_action(self, pair_addr): + RNS.log(f"Pair action for {pair_addr}", RNS.LOG_DEBUG) + self.app.stop_bluetooth_scan() + if pair_addr in self.app.bt_bonded_devices: + def job(dt): toast("Selected device already paired") + Clock.schedule_once(job, 0.1) + return "already_paired" + + else: + BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket') + if self.app.bt_adapter == None: self.app.bt_adapter = BluetoothAdapter.getDefaultAdapter() + addr_bytes = bytes.fromhex(pair_addr.replace(":", "")) + remote_device = self.app.bt_adapter.getRemoteDevice(addr_bytes) + RNS.log(f"Remote device: {remote_device}", RNS.LOG_DEBUG) + remote_device.createBond() + + def hardware_rnode_bt_scan_action(self, sender=None): + self.app.discovered_bt_devices = {} + rw = [] + for child in self.hardware_rnode_screen.ids.rnode_scan_results.children: rw.append(child) + for w in rw: self.hardware_rnode_screen.ids.rnode_scan_results.remove_widget(w) + + Clock.schedule_once(self.app.bluetooth_scan_action, 0.5) + + def hardware_rnode_bt_on_action(self, sender=None): + self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = True + def re_enable(): + time.sleep(2) + while self.app.sideband.getstate("executing.bt_on"): time.sleep(1) + self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = False + threading.Thread(target=re_enable, daemon=True).start() + self.app.sideband.setstate("wants.bt_on", True) + + def hardware_rnode_bt_off_action(self, sender=None): + self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = True + def re_enable(): + time.sleep(2) + while self.app.sideband.getstate("executing.bt_off"): time.sleep(1) + self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = False + threading.Thread(target=re_enable, daemon=True).start() + self.app.sideband.setstate("wants.bt_off", True) + + def hardware_rnode_bt_pair_action(self, sender=None): + self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = True + self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = True + def re_enable(): + time.sleep(2) + while self.app.sideband.getstate("executing.bt_pair"): time.sleep(1) + self.hardware_rnode_screen.ids.hardware_rnode_bt_off_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_pair_button.disabled = False + self.hardware_rnode_screen.ids.hardware_rnode_bt_on_button.disabled = False + threading.Thread(target=re_enable, daemon=True).start() + self.app.sideband.setstate("wants.bt_pair", True) + + def hardware_rnode_bt_toggle_action(self, sender=None, event=None): + if sender.active: + self.app.sideband.config["hw_rnode_bluetooth"] = True + self.app.request_bluetooth_permissions() + else: + self.app.sideband.config["hw_rnode_bluetooth"] = False + + self.app.sideband.save_configuration() + + def hardware_rnode_ble_toggle_action(self, sender=None, event=None): + if sender.active: + self.app.sideband.config["hw_rnode_ble"] = True + self.app.request_bluetooth_permissions() + else: + self.app.sideband.config["hw_rnode_ble"] = False + + self.app.sideband.save_configuration() + + def hardware_rnode_framebuffer_toggle_action(self, sender=None, event=None): + if sender.active: + self.app.sideband.config["hw_rnode_enable_framebuffer"] = True + else: + self.app.sideband.config["hw_rnode_enable_framebuffer"] = False + + self.app.sideband.save_configuration() + + def hardware_rnode_tcp_toggle_action(self, sender=None, event=None): + if sender.active: self.app.sideband.config["hw_rnode_tcp"] = True + else: self.app.sideband.config["hw_rnode_tcp"] = False + + self.app.sideband.save_configuration() + + def hardware_rnode_init(self, sender=None): + if not self.hardware_rnode_ready: + if not self.app.root.ids.screen_manager.has_screen("hardware_rnode_screen"): + self.hardware_rnode_screen = Builder.load_string(layout_hardware_rnode_screen) + self.hardware_rnode_screen.app = self + self.app.root.ids.screen_manager.add_widget(self.hardware_rnode_screen) + + self.hardware_rnode_screen.ids.hardware_rnode_scrollview.effect_cls = ScrollEffect + def save_connectivity(sender=None, event=None): + if self.hardware_rnode_validate(): + self.hardware_rnode_save() + + def focus_save(sender=None, event=None): + if sender != None: + if not sender.focus: + save_connectivity(sender=sender) + + if self.app.sideband.config["hw_rnode_frequency"] != None: t_freq = str(self.app.sideband.config["hw_rnode_frequency"]/1000000.0) + else: t_freq = "" + + if self.app.sideband.config["hw_rnode_bandwidth"] != None: t_bw = str(self.app.sideband.config["hw_rnode_bandwidth"]/1000.0) + else: t_bw = str(62.5) + + if self.app.sideband.config["hw_rnode_tx_power"] != None: t_p = str(self.app.sideband.config["hw_rnode_tx_power"]) + else: t_p = str(0) + + if self.app.sideband.config["hw_rnode_spreading_factor"] != None: t_sf = str(self.app.sideband.config["hw_rnode_spreading_factor"]) + else: t_sf = str(8) + + if self.app.sideband.config["hw_rnode_coding_rate"] != None: t_cr = str(self.app.sideband.config["hw_rnode_coding_rate"]) + else: t_cr = str(6) + + if self.app.sideband.config["hw_rnode_beaconinterval"] != None: t_bi = str(self.app.sideband.config["hw_rnode_beaconinterval"]) + else: t_bi = "" + + if self.app.sideband.config["hw_rnode_beacondata"] != None: t_bd = str(self.app.sideband.config["hw_rnode_beacondata"]) + else: t_bd = "" + + if self.app.sideband.config["hw_rnode_bt_device"] != None: t_btd = str(self.app.sideband.config["hw_rnode_bt_device"]) + else: t_btd = "" + + if self.app.sideband.config["hw_rnode_tcp_host"] != None: t_th = str(self.app.sideband.config["hw_rnode_tcp_host"]) + else: t_th = "" + + if self.app.sideband.config["hw_rnode_atl_short"] != None: t_ats = str(self.app.sideband.config["hw_rnode_atl_short"]) + else: t_ats = "" + + if self.app.sideband.config["hw_rnode_atl_long"] != None: t_atl = str(self.app.sideband.config["hw_rnode_atl_long"]) + else: t_atl = "" + + self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.active = self.app.sideband.config["hw_rnode_bluetooth"] + self.hardware_rnode_screen.ids.hardware_rnode_ble.active = self.app.sideband.config["hw_rnode_ble"] + self.hardware_rnode_screen.ids.hardware_rnode_tcp.active = self.app.sideband.config["hw_rnode_tcp"] + self.hardware_rnode_screen.ids.hardware_rnode_framebuffer.active = self.app.sideband.config["hw_rnode_enable_framebuffer"] + self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = t_freq + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = t_bw + self.hardware_rnode_screen.ids.hardware_rnode_txpower.text = t_p + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text = t_sf + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text = t_cr + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = t_bi + self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text = t_bd + self.hardware_rnode_screen.ids.hardware_rnode_bt_device.text = t_btd + self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.text = t_th + self.hardware_rnode_screen.ids.hardware_rnode_atl_short.text = t_ats + self.hardware_rnode_screen.ids.hardware_rnode_atl_long.text = t_atl + self.hardware_rnode_screen.ids.hardware_rnode_frequency.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_txpower.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_beacondata.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_bt_device.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_tcp_host.bind(focus=focus_save) + self.hardware_rnode_screen.ids.hardware_rnode_frequency.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_txpower.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_beacondata.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_atl_short.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_atl_long.bind(on_text_validate=save_connectivity) + self.hardware_rnode_screen.ids.hardware_rnode_bluetooth.bind(active=self.hardware_rnode_bt_toggle_action) + self.hardware_rnode_screen.ids.hardware_rnode_ble.bind(active=self.hardware_rnode_ble_toggle_action) + self.hardware_rnode_screen.ids.hardware_rnode_framebuffer.bind(active=self.hardware_rnode_framebuffer_toggle_action) + self.hardware_rnode_screen.ids.hardware_rnode_tcp.bind(active=self.hardware_rnode_tcp_toggle_action) + + self.hardware_rnode_ready = True + + def hardware_rnode_validate(self, sender=None): + valid = True + try: + val = float(self.hardware_rnode_screen.ids.hardware_rnode_frequency.text) + if not val > 0: + raise ValueError("Invalid frequency") + self.hardware_rnode_screen.ids.hardware_rnode_frequency.error = False + self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = str(val) + except: + self.hardware_rnode_screen.ids.hardware_rnode_frequency.error = True + valid = False + + try: + 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") + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.error = False + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = str(val) + except: + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.error = True + valid = False + + try: + val = int(self.hardware_rnode_screen.ids.hardware_rnode_txpower.text) + if not val >= 0: + raise ValueError("Invalid TX power") + self.hardware_rnode_screen.ids.hardware_rnode_txpower.error = False + self.hardware_rnode_screen.ids.hardware_rnode_txpower.text = str(val) + except: + self.hardware_rnode_screen.ids.hardware_rnode_txpower.error = True + valid = False + + try: + val = int(self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text) + if val < 7 or val > 12: + raise ValueError("Invalid sf") + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.error = False + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text = str(val) + except: + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.error = True + valid = False + + try: + val = int(self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text) + if val < 5 or val > 8: + raise ValueError("Invalid cr") + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.error = False + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text = str(val) + except: + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.error = True + valid = False + + try: + if self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text != "": + val = int(self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text) + if val < 10: + raise ValueError("Invalid beacon interval") + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = str(val) + + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.error = False + except: + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = "" + valid = False + + return valid + + def hardware_rnode_import(self, sender=None): + mote = None + try: + mote = Clipboard.paste() + except Exception as e: + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog( + title="Import Failed", + text="Could not read data from your clipboard, please check your system permissions.", + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + dialog.open() + + try: + config = msgpack.unpackb(base64.b32decode(mote)) + self.hardware_rnode_screen.ids.hardware_rnode_frequency.text = str(config["f"]/1000000.0) + self.hardware_rnode_screen.ids.hardware_rnode_bandwidth.text = str(config["b"]/1000.0) + self.hardware_rnode_screen.ids.hardware_rnode_txpower.text = str(config["t"]) + self.hardware_rnode_screen.ids.hardware_rnode_spreadingfactor.text = str(config["s"]) + self.hardware_rnode_screen.ids.hardware_rnode_codingrate.text = str(config["c"]) + + if "n" in config and config["n"] != None: + ifn = str(config["n"]) + else: + ifn = "" + if "p" in config and config["p"] != None: + ifp = str(config["p"]) + else: + ifp = "" + + if self.app.connectivity_screen != None: + self.app.connectivity_screen.ids.connectivity_rnode_ifac_netname.text = ifn + self.app.connectivity_screen.ids.connectivity_rnode_ifac_passphrase.text = ifp + + self.app.sideband.config["connect_rnode_ifac_netname"] = ifn + self.app.sideband.config["connect_rnode_ifac_passphrase"] = ifp + + if config["i"] != None: ti = str(config["i"]) + else: ti = "" + self.hardware_rnode_screen.ids.hardware_rnode_beaconinterval.text = ti + + if config["d"] != None: td = str(config["d"]) + else: td = "" + self.hardware_rnode_screen.ids.hardware_rnode_beacondata.text = td + + if self.hardware_rnode_validate(): + self.hardware_rnode_save() + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog( + title="Configuration Imported", + text="The config mote was imported and saved as your active configuration.", + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + dialog.open() + else: + raise ValueError("Invalid mote") + + except Exception as e: + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog( + title="Import Failed", + text="The read data did not contain a valid config mote. If any data was decoded, you may try to correct it by editing the relevant fields. The reported error was:\n\n"+str(e), + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + dialog.open() + + def hardware_rnode_export(self, sender=None): + mote = None + try: + mote = base64.b32encode(msgpack.packb({ + "f": self.app.sideband.config["hw_rnode_frequency"], + "b": self.app.sideband.config["hw_rnode_bandwidth"], + "t": self.app.sideband.config["hw_rnode_tx_power"], + "s": self.app.sideband.config["hw_rnode_spreading_factor"], + "c": self.app.sideband.config["hw_rnode_coding_rate"], + "i": self.app.sideband.config["hw_rnode_beaconinterval"], + "d": self.app.sideband.config["hw_rnode_beacondata"], + "n": self.app.sideband.config["connect_rnode_ifac_netname"], + "p": self.app.sideband.config["connect_rnode_ifac_passphrase"], + })) + except Exception as e: + RNS.trace_exception(e) + + if mote != None: + Clipboard.copy(mote) + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog( + title="Configuration Exported", + text="The config mote was created and copied to your clipboard.", + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + dialog.open() + else: + yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) + dialog = MDDialog( + title="Export Failed", + text="The config mote could not be created, please check your settings.", + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + yes_button.bind(on_release=dl_yes) + dialog.open() + + ## Modem hardware screen + + def hardware_modem_action(self, sender=None, direction="left"): + if self.hardware_modem_ready: + self.hardware_modem_open(direction=direction) + else: + self.app.loader_action(direction=direction) + def final(dt): + self.hardware_modem_init() + def o(dt): + self.hardware_modem_open(no_transition=True) + Clock.schedule_once(o, ll_ot) + Clock.schedule_once(final, ll_ft) + + def hardware_modem_open(self, sender=None, direction="left", no_transition=False): + if no_transition: + self.app.root.ids.screen_manager.transition = self.no_transition + else: + self.app.root.ids.screen_manager.transition = self.slide_transition + self.app.root.ids.screen_manager.transition.direction = direction + + self.hardware_modem_init() + self.app.root.ids.screen_manager.transition.direction = "left" + self.app.root.ids.screen_manager.current = "hardware_modem_screen" + self.app.root.ids.nav_drawer.set_state("closed") + self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) + + if no_transition: + self.app.root.ids.screen_manager.transition = self.slide_transition + + def hardware_modem_init(self, sender=None): + if not self.hardware_modem_ready: + if not self.app.root.ids.screen_manager.has_screen("hardware_modem_screen"): + self.hardware_modem_screen = Builder.load_string(layout_hardware_modem_screen) + self.hardware_modem_screen.app = self + self.app.root.ids.screen_manager.add_widget(self.hardware_modem_screen) + + self.hardware_modem_screen.ids.hardware_modem_scrollview.effect_cls = ScrollEffect + def save_connectivity(sender=None, event=None): + if self.hardware_modem_validate(): + self.hardware_modem_save() + + def focus_save(sender=None, event=None): + if sender != None: + if not sender.focus: + save_connectivity(sender=sender) + + if self.app.sideband.config["hw_modem_baudrate"] != None: + t_b = str(self.app.sideband.config["hw_modem_baudrate"]) + else: + t_b = "" + + if self.app.sideband.config["hw_modem_databits"] != None: + t_db = str(self.app.sideband.config["hw_modem_databits"]) + else: + t_db = "" + + if self.app.sideband.config["hw_modem_parity"] != None: + t_p = str(self.app.sideband.config["hw_modem_parity"]) + else: + t_p = "" + + if self.app.sideband.config["hw_modem_stopbits"] != None: + t_sb = str(self.app.sideband.config["hw_modem_stopbits"]) + else: + t_sb = "" + + if self.app.sideband.config["hw_modem_preamble"] != None: + t_pa = str(self.app.sideband.config["hw_modem_preamble"]) + else: + t_pa = "" + + if self.app.sideband.config["hw_modem_tail"] != None: + t_t = str(self.app.sideband.config["hw_modem_tail"]) + else: + t_t = "" + + if self.app.sideband.config["hw_modem_persistence"] != None: + t_ps = str(self.app.sideband.config["hw_modem_persistence"]) + else: + t_ps = "" + + if self.app.sideband.config["hw_modem_slottime"] != None: + t_st = str(self.app.sideband.config["hw_modem_slottime"]) + else: + t_st = "" + + if self.app.sideband.config["hw_modem_beaconinterval"] != None: + t_bi = str(self.app.sideband.config["hw_modem_beaconinterval"]) + else: + t_bi = "" + if self.app.sideband.config["hw_modem_beacondata"] != None: + t_bd = str(self.app.sideband.config["hw_modem_beacondata"]) + else: + t_bd = "" + + self.hardware_modem_screen.ids.hardware_modem_baudrate.text = t_b + self.hardware_modem_screen.ids.hardware_modem_databits.text = t_db + self.hardware_modem_screen.ids.hardware_modem_parity.text = t_p + self.hardware_modem_screen.ids.hardware_modem_stopbits.text = t_sb + self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text = t_bi + self.hardware_modem_screen.ids.hardware_modem_beacondata.text = t_bd + self.hardware_modem_screen.ids.hardware_modem_preamble.text = t_pa + self.hardware_modem_screen.ids.hardware_modem_tail.text = t_t + self.hardware_modem_screen.ids.hardware_modem_persistence.text = t_ps + self.hardware_modem_screen.ids.hardware_modem_slottime.text = t_st + self.hardware_modem_screen.ids.hardware_modem_baudrate.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_databits.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_parity.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_stopbits.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_beaconinterval.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_beacondata.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_preamble.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_tail.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_persistence.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_slottime.bind(focus=focus_save) + self.hardware_modem_screen.ids.hardware_modem_baudrate.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_databits.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_parity.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_stopbits.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_beaconinterval.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_beacondata.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_preamble.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_tail.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_persistence.bind(on_text_validate=save_connectivity) + self.hardware_modem_screen.ids.hardware_modem_slottime.bind(on_text_validate=save_connectivity) + + self.hardware_modem_ready = True + + def hardware_modem_save(self): + self.app.sideband.config["hw_modem_baudrate"] = int(self.hardware_modem_screen.ids.hardware_modem_baudrate.text) + self.app.sideband.config["hw_modem_databits"] = int(self.hardware_modem_screen.ids.hardware_modem_databits.text) + self.app.sideband.config["hw_modem_parity"] = self.hardware_modem_screen.ids.hardware_modem_parity.text + self.app.sideband.config["hw_modem_stopbits"] = int(self.hardware_modem_screen.ids.hardware_modem_stopbits.text) + self.app.sideband.config["hw_modem_preamble"] = int(self.hardware_modem_screen.ids.hardware_modem_preamble.text) + self.app.sideband.config["hw_modem_tail"] = int(self.hardware_modem_screen.ids.hardware_modem_tail.text) + self.app.sideband.config["hw_modem_persistence"] = int(self.hardware_modem_screen.ids.hardware_modem_persistence.text) + self.app.sideband.config["hw_modem_slottime"] = int(self.hardware_modem_screen.ids.hardware_modem_slottime.text) + + if self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text == "": + self.app.sideband.config["hw_modem_beaconinterval"] = None + else: + self.app.sideband.config["hw_modem_beaconinterval"] = int(self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text) + + if self.hardware_modem_screen.ids.hardware_modem_beacondata.text == "": + self.app.sideband.config["hw_modem_beacondata"] = None + else: + self.app.sideband.config["hw_modem_beacondata"] = self.hardware_modem_screen.ids.hardware_modem_beacondata.text + + self.app.sideband.save_configuration() + + def hardware_modem_validate(self, sender=None): + valid = True + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_baudrate.text) + if not val > 0: + raise ValueError("Invalid baudrate") + self.hardware_modem_screen.ids.hardware_modem_baudrate.error = False + self.hardware_modem_screen.ids.hardware_modem_baudrate.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_baudrate.error = True + valid = False + + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_databits.text) + if not val > 0: + raise ValueError("Invalid databits") + self.hardware_modem_screen.ids.hardware_modem_databits.error = False + self.hardware_modem_screen.ids.hardware_modem_databits.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_databits.error = True + valid = False + + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_stopbits.text) + if not val > 0: + raise ValueError("Invalid stopbits") + self.hardware_modem_screen.ids.hardware_modem_stopbits.error = False + self.hardware_modem_screen.ids.hardware_modem_stopbits.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_stopbits.error = True + valid = False + + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_preamble.text) + if not (val >= 0 and val <= 1000): + raise ValueError("Invalid preamble") + self.hardware_modem_screen.ids.hardware_modem_preamble.error = False + self.hardware_modem_screen.ids.hardware_modem_preamble.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_preamble.error = True + valid = False + + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_tail.text) + if not (val > 0 and val <= 500): + raise ValueError("Invalid tail") + self.hardware_modem_screen.ids.hardware_modem_tail.error = False + self.hardware_modem_screen.ids.hardware_modem_tail.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_tail.error = True + valid = False + + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_slottime.text) + if not (val > 0 and val <= 500): + raise ValueError("Invalid slottime") + self.hardware_modem_screen.ids.hardware_modem_slottime.error = False + self.hardware_modem_screen.ids.hardware_modem_slottime.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_slottime.error = True + valid = False + + try: + val = int(self.hardware_modem_screen.ids.hardware_modem_persistence.text) + if not (val > 0 and val <= 255): + raise ValueError("Invalid persistence") + self.hardware_modem_screen.ids.hardware_modem_persistence.error = False + self.hardware_modem_screen.ids.hardware_modem_persistence.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_persistence.error = True + valid = False + + try: + val = self.hardware_modem_screen.ids.hardware_modem_parity.text + nval = val.lower() + if nval in ["e", "ev", "eve", "even"]: + val = "even" + if nval in ["o", "od", "odd"]: + val = "odd" + if nval in ["n", "no", "non", "none", "not", "null", "off"]: + val = "none" + if not val in ["even", "odd", "none"]: + raise ValueError("Invalid parity") + self.hardware_modem_screen.ids.hardware_modem_parity.error = False + self.hardware_modem_screen.ids.hardware_modem_parity.text = str(val) + except: + self.hardware_modem_screen.ids.hardware_modem_parity.error = True + valid = False + + try: + if self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text != "": + val = int(self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text) + if val < 10: + raise ValueError("Invalid bi") + self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text = str(val) + + self.hardware_modem_screen.ids.hardware_modem_beaconinterval.error = False + except: + self.hardware_modem_screen.ids.hardware_modem_beaconinterval.text = "" + valid = False + + return valid + + ## Serial hardware screen + def hardware_serial_action(self, sender=None, direction="left"): + if self.hardware_serial_ready: + self.hardware_serial_open(direction=direction) + else: + self.app.loader_action(direction=direction) + def final(dt): + self.hardware_serial_init() + def o(dt): + self.hardware_serial_open(no_transition=True) + Clock.schedule_once(o, ll_ot) + Clock.schedule_once(final, ll_ft) + + def hardware_serial_open(self, sender=None, direction="left", no_transition=False): + if no_transition: + self.app.root.ids.screen_manager.transition = self.no_transition + else: + self.app.root.ids.screen_manager.transition = self.slide_transition + self.app.root.ids.screen_manager.transition.direction = direction + + self.app.root.ids.screen_manager.transition.direction = "left" + self.app.root.ids.screen_manager.current = "hardware_serial_screen" + self.app.root.ids.nav_drawer.set_state("closed") + self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) + + if no_transition: + self.app.root.ids.screen_manager.transition = self.slide_transition + + def hardware_serial_init(self, sender=None): + if not self.hardware_serial_ready: + if not self.app.root.ids.screen_manager.has_screen("hardware_serial_screen"): + self.hardware_serial_screen = Builder.load_string(layout_hardware_serial_screen) + self.hardware_serial_screen.app = self + self.app.root.ids.screen_manager.add_widget(self.hardware_serial_screen) + + self.hardware_serial_screen.ids.hardware_serial_scrollview.effect_cls = ScrollEffect + def save_connectivity(sender=None, event=None): + if self.hardware_serial_validate(): + self.hardware_serial_save() + + def focus_save(sender=None, event=None): + if sender != None: + if not sender.focus: + save_connectivity(sender=sender) + + if self.app.sideband.config["hw_serial_baudrate"] != None: + t_b = str(self.app.sideband.config["hw_serial_baudrate"]) + else: + t_b = "" + + if self.app.sideband.config["hw_serial_databits"] != None: + t_db = str(self.app.sideband.config["hw_serial_databits"]) + else: + t_db = "" + + if self.app.sideband.config["hw_serial_parity"] != None: + t_p = str(self.app.sideband.config["hw_serial_parity"]) + else: + t_p = "" + + if self.app.sideband.config["hw_serial_stopbits"] != None: + t_sb = str(self.app.sideband.config["hw_serial_stopbits"]) + else: + t_sb = "" + + self.hardware_serial_screen.ids.hardware_serial_baudrate.text = t_b + self.hardware_serial_screen.ids.hardware_serial_databits.text = t_db + self.hardware_serial_screen.ids.hardware_serial_parity.text = t_p + self.hardware_serial_screen.ids.hardware_serial_stopbits.text = t_sb + self.hardware_serial_screen.ids.hardware_serial_baudrate.bind(focus=focus_save) + self.hardware_serial_screen.ids.hardware_serial_databits.bind(focus=focus_save) + self.hardware_serial_screen.ids.hardware_serial_parity.bind(focus=focus_save) + self.hardware_serial_screen.ids.hardware_serial_stopbits.bind(focus=focus_save) + self.hardware_serial_screen.ids.hardware_serial_baudrate.bind(on_text_validate=save_connectivity) + self.hardware_serial_screen.ids.hardware_serial_databits.bind(on_text_validate=save_connectivity) + self.hardware_serial_screen.ids.hardware_serial_parity.bind(on_text_validate=save_connectivity) + self.hardware_serial_screen.ids.hardware_serial_stopbits.bind(on_text_validate=save_connectivity) + + self.hardware_serial_ready = True + + def hardware_serial_validate(self, sender=None): + valid = True + try: + val = int(self.hardware_serial_screen.ids.hardware_serial_baudrate.text) + if not val > 0: + raise ValueError("Invalid baudrate") + self.hardware_serial_screen.ids.hardware_serial_baudrate.error = False + self.hardware_serial_screen.ids.hardware_serial_baudrate.text = str(val) + except: + self.hardware_serial_screen.ids.hardware_serial_baudrate.error = True + valid = False + + try: + val = int(self.hardware_serial_screen.ids.hardware_serial_databits.text) + if not val > 0: + raise ValueError("Invalid databits") + self.hardware_serial_screen.ids.hardware_serial_databits.error = False + self.hardware_serial_screen.ids.hardware_serial_databits.text = str(val) + except: + self.hardware_serial_screen.ids.hardware_serial_databits.error = True + valid = False + + try: + val = int(self.hardware_serial_screen.ids.hardware_serial_stopbits.text) + if not val > 0: + raise ValueError("Invalid stopbits") + self.hardware_serial_screen.ids.hardware_serial_stopbits.error = False + self.hardware_serial_screen.ids.hardware_serial_stopbits.text = str(val) + except: + self.hardware_serial_screen.ids.hardware_serial_stopbits.error = True + valid = False + + try: + val = self.hardware_serial_screen.ids.hardware_serial_parity.text + nval = val.lower() + if nval in ["e", "ev", "eve", "even"]: + val = "even" + if nval in ["o", "od", "odd"]: + val = "odd" + if nval in ["n", "no", "non", "none", "not", "null", "off"]: + val = "none" + if not val in ["even", "odd", "none"]: + raise ValueError("Invalid parity") + self.hardware_serial_screen.ids.hardware_serial_parity.error = False + self.hardware_serial_screen.ids.hardware_serial_parity.text = str(val) + except: + self.hardware_serial_screen.ids.hardware_serial_parity.error = True + valid = False + + return valid + + def hardware_serial_save(self): + self.app.sideband.config["hw_serial_baudrate"] = int(self.hardware_serial_screen.ids.hardware_serial_baudrate.text) + self.app.sideband.config["hw_serial_databits"] = int(self.hardware_serial_screen.ids.hardware_serial_databits.text) + self.app.sideband.config["hw_serial_parity"] = self.hardware_serial_screen.ids.hardware_serial_parity.text + self.app.sideband.config["hw_serial_stopbits"] = int(self.hardware_serial_screen.ids.hardware_serial_stopbits.text) + + self.app.sideband.save_configuration() + +layout_hardware_screen = """ +MDScreen: + name: "hardware_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Hardware" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.app.close_hardware_action(self)], + ] + + ScrollView: + id: hardware_scrollview + + MDBoxLayout: + orientation: "vertical" + spacing: "8dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(48), dp(28), dp(16)] + + MDLabel: + text: "Configure Hardware Parameters\\n" + font_style: "H6" + + MDLabel: + id: hardware_info + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(35)] + + MDRectangleFlatIconButton: + id: hardware_rnode_button + icon: "radio-handheld" + text: "RNode" + 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.app.hardware_rnode_action(self) + + MDRectangleFlatIconButton: + id: hardware_modem_button + icon: "router-wireless" + text: "Radio Modem" + 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.app.hardware_modem_action(self) + disabled: False + + MDRectangleFlatIconButton: + id: hardware_serial_button + icon: "cable-data" + text: "Serial Port" + 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.app.hardware_serial_action(self) + disabled: False +""" + +layout_hardware_modem_screen = """ +MDScreen: + name: "hardware_modem_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Radio Modem" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.app.close_sub_hardware_action(self)], + ] + + ScrollView: + id: hardware_modem_scrollview + + MDBoxLayout: + orientation: "vertical" + spacing: "8dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(48), dp(28), dp(16)] + + MDLabel: + text: "Modem Hardware Parameters\\n" + font_style: "H6" + + MDLabel: + id: hardware_modem_info + markup: True + text: "To communicate using a Radio Modem, you will need to specify the following parameters. Serial port parameters must be set to match those of the modem. CSMA parameters can be left at their default values in most cases.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + text: "Port Options" + font_style: "H6" + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_modem_baudrate + hint_text: "Baud Rate" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(24)] + + MDTextField: + id: hardware_modem_databits + hint_text: "Data Bits" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_modem_parity + hint_text: "Parity" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_modem_stopbits + hint_text: "Stop Bits" + text: "" + font_size: dp(24) + + MDLabel: + text: "CSMA Parameters" + font_style: "H6" + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(0)] + + MDTextField: + id: hardware_modem_preamble + hint_text: "Preamble (ms)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_modem_tail + hint_text: "TX Tail (ms)" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(24)] + + MDTextField: + id: hardware_modem_persistence + hint_text: "Persistence (1-255)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_modem_slottime + hint_text: "Slot Time (ms)" + text: "" + font_size: dp(24) + + MDLabel: + text: "Optional Settings" + font_style: "H6" + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_modem_beaconinterval + hint_text: "Beacon Interval (seconds)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_modem_beacondata + hint_text: "Beacon Data" + text: "" + font_size: dp(24) +""" + +layout_hardware_rnode_screen = """ +MDScreen: + name: "hardware_rnode_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "RNode" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.app.close_sub_hardware_action(self)], + ] + + ScrollView: + id: hardware_rnode_scrollview + + MDBoxLayout: + orientation: "vertical" + spacing: "8dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(48), dp(28), dp(16)] + + MDLabel: + text: "RNode Hardware Parameters\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "To communicate using an RNode, you will need to specify the following parameters. For two or more RNodes to be able to communicate, all parameters must match, except for the [i]Coding Rate[/i] and [i]TX Power[/i] parameter, which can vary between devices.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(48)] + + MDRectangleFlatIconButton: + id: rnode_mote_export + icon: "upload" + text: "Export" + 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.app.hardware_rnode_export(self) + + MDRectangleFlatIconButton: + id: rnode_mote_import + icon: "download" + text: "Import" + 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.app.hardware_rnode_import(self) + + MDLabel: + text: "Radio Options\\n" + font_style: "H6" + + # MDTextField: + # id: hardware_rnode_modulation + # hint_text: "Modulation" + # text: "LoRa" + # disabled: True + # font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_frequency + hint_text: "Frequency (MHz)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_rnode_bandwidth + hint_text: "Bandwidth (KHz)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_rnode_txpower + hint_text: "TX Power (dBm)" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(24)] + + MDTextField: + id: hardware_rnode_spreadingfactor + hint_text: "Spreading Factor" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_rnode_codingrate + hint_text: "Coding Rate" + text: "" + font_size: dp(24) + + MDLabel: + text: "Optional Settings" + font_style: "H6" + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_beaconinterval + hint_text: "Beacon Interval (seconds)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_rnode_beacondata + hint_text: "Beacon Data" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_atl_short + hint_text: "Airime Limit % (15s)" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_rnode_atl_long + hint_text: "Airime Limit % (1h)" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,dp(14),dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Control RNode Display" + font_style: "H6" + + MDSwitch: + id: hardware_rnode_framebuffer + pos_hint: {"center_y": 0.3} + active: False + + MDLabel: + text: "•" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2+14), 0, dp(22+24)] + + MDLabel: + text: "WiFi & Ethernet Connection\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info_wifi + markup: True + text: "If your device is hosting or connected to a WiFi network, you can connect it by entering its IP address or hostname below." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,dp(12),dp(24),dp(0)] + height: dp(36) + + MDLabel: + text: "Connect using WiFi" + font_style: "H6" + + MDSwitch: + id: hardware_rnode_tcp + pos_hint: {"center_y": 0.3} + active: False + + MDBoxLayout: + orientation: "vertical" + # spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_tcp_host + hint_text: "RNode IP address or hostname" + text: "" + font_size: dp(24) + + MDLabel: + text: "•" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2+14), 0, dp(22+24)] + + MDLabel: + text: "Bluetooth Connection\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "If you enable connection via Bluetooth, Sideband will attempt to connect to any available and paired RNodes over Bluetooth.\\n\\nIf your RNode uses BLE (ESP32-S3 and nRF devices) instead of classic Bluetooth, enable the [i]Device requires BLE[/i] option as well." + 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: "Connect using Bluetooth" + font_style: "H6" + + MDSwitch: + id: hardware_rnode_bluetooth + pos_hint: {"center_y": 0.3} + active: False + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(48)] + height: dp(86) + + MDLabel: + text: "Device requires BLE" + font_style: "H6" + + MDSwitch: + id: hardware_rnode_ble + pos_hint: {"center_y": 0.3} + active: False + + MDLabel: + text: "Bluetooth Pairing\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode. If the in-app pairing does not find any devices, use the Bluetooth settings of your device to scan and pair.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(12)] + + MDRectangleFlatIconButton: + id: hardware_rnode_bt_scan_button + icon: "bluetooth-connect" + text: "Pair New Device" + 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.app.hardware_rnode_bt_scan_action(self) + + MDBoxLayout: + id: rnode_scan_results + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(12+24)] + + MDLabel: + text: "Preffered Bluetooth Device\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "Sideband will connect to the first available RNode that is paired. If you want to always use a specific RNode, you can enter its name here, for example \\"RNode A8EB\\"." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_rnode_bt_device + hint_text: "Preferred RNode Device Name" + text: "" + font_size: dp(24) + + MDLabel: + text: "•" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2+14), 0, dp(22)] + + MDLabel: + text: "\\n\\nDevice Bluetooth Control\\n" + font_style: "H6" + + MDLabel: + id: hardware_rnode_info + markup: True + text: "\\n\\nIf your RNode does not have a physical pairing button, you can enable Bluetooth and put it into pairing mode by first connecting it via a USB cable, and using the buttons below. When plugging in the RNode over USB, you must grant Sideband permission to the USB device for this to work.\\n\\nYou can also change Bluetooth settings using the \\"rnodeconf\\" utility from a computer.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDRectangleFlatIconButton: + id: hardware_rnode_bt_on_button + icon: "bluetooth" + text: "Enable Bluetooth" + 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.app.hardware_rnode_bt_on_action(self) + + MDRectangleFlatIconButton: + id: hardware_rnode_bt_off_button + icon: "bluetooth-off" + text: "Disable Bluetooth" + 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.app.hardware_rnode_bt_off_action(self) + disabled: False + + MDRectangleFlatIconButton: + id: hardware_rnode_bt_pair_button + icon: "link-variant" + text: "Start Pairing Mode" + 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.app.hardware_rnode_bt_pair_action(self) + disabled: False +""" + +layout_hardware_serial_screen = """ +MDScreen: + name: "hardware_serial_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Serial Port" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.app.close_sub_hardware_action(self)], + ] + + ScrollView: + id: hardware_serial_scrollview + + MDBoxLayout: + orientation: "vertical" + spacing: "8dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(48), dp(28), dp(16)] + + MDLabel: + text: "Serial Hardware Parameters\\n" + font_style: "H6" + + MDLabel: + id: hardware_serial_info + markup: True + text: "To communicate using a serial port, you will need to specify the following parameters. If communicating directly to another Reticulum instance over serial, the parameters must match the other device.\\n\\nIf you are using a serial-connected device to pass on data to other Reticulum instances, it should be configured to pass data transparently to the desired endpoints.\\n" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDLabel: + text: "Port Options" + font_style: "H6" + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + # padding: [dp(0), dp(0), dp(0), dp(35)] + + MDTextField: + id: hardware_serial_baudrate + hint_text: "Baud Rate" + text: "" + font_size: dp(24) + + MDBoxLayout: + orientation: "horizontal" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(24)] + + MDTextField: + id: hardware_serial_databits + hint_text: "Data Bits" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_serial_parity + hint_text: "Parity" + text: "" + font_size: dp(24) + + MDTextField: + id: hardware_serial_stopbits + hint_text: "Stop Bits" + text: "" + font_size: dp(24) +""" diff --git a/sbapp/ui/layouts.py b/sbapp/ui/layouts.py index 6ef961e..7faf7a4 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -1978,717 +1978,3 @@ MDScreen: text_size: self.width, None height: self.texture_size[1] """ - -layout_hardware_screen = """ -MDScreen: - name: "hardware_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "Hardware" - anchor_title: "left" - elevation: 0 - left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] - right_action_items: - [ - ['close', lambda x: root.app.close_hardware_action(self)], - ] - - ScrollView: - id: hardware_scrollview - - MDBoxLayout: - orientation: "vertical" - spacing: "8dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(28), dp(48), dp(28), dp(16)] - - MDLabel: - text: "Configure Hardware Parameters\\n" - font_style: "H6" - - MDLabel: - id: hardware_info - markup: True - text: "" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - - MDBoxLayout: - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(35), dp(0), dp(35)] - - MDRectangleFlatIconButton: - id: hardware_rnode_button - icon: "radio-handheld" - text: "RNode" - 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.app.hardware_rnode_action(self) - - MDRectangleFlatIconButton: - id: hardware_modem_button - icon: "router-wireless" - text: "Radio Modem" - 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.app.hardware_modem_action(self) - disabled: False - - MDRectangleFlatIconButton: - id: hardware_serial_button - icon: "cable-data" - text: "Serial Port" - 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.app.hardware_serial_action(self) - disabled: False -""" - -layout_hardware_modem_screen = """ -MDScreen: - name: "hardware_modem_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "Radio Modem" - anchor_title: "left" - elevation: 0 - left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] - right_action_items: - [ - ['close', lambda x: root.app.close_sub_hardware_action(self)], - ] - - ScrollView: - id: hardware_modem_scrollview - - MDBoxLayout: - orientation: "vertical" - spacing: "8dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(28), dp(48), dp(28), dp(16)] - - MDLabel: - text: "Modem Hardware Parameters\\n" - font_style: "H6" - - MDLabel: - id: hardware_modem_info - markup: True - text: "To communicate using a Radio Modem, you will need to specify the following parameters. Serial port parameters must be set to match those of the modem. CSMA parameters can be left at their default values in most cases.\\n" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - text: "Port Options" - font_style: "H6" - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_modem_baudrate - hint_text: "Baud Rate" - text: "" - font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(24)] - - MDTextField: - id: hardware_modem_databits - hint_text: "Data Bits" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_modem_parity - hint_text: "Parity" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_modem_stopbits - hint_text: "Stop Bits" - text: "" - font_size: dp(24) - - MDLabel: - text: "CSMA Parameters" - font_style: "H6" - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(0)] - - MDTextField: - id: hardware_modem_preamble - hint_text: "Preamble (ms)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_modem_tail - hint_text: "TX Tail (ms)" - text: "" - font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(24)] - - MDTextField: - id: hardware_modem_persistence - hint_text: "Persistence (1-255)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_modem_slottime - hint_text: "Slot Time (ms)" - text: "" - font_size: dp(24) - - MDLabel: - text: "Optional Settings" - font_style: "H6" - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_modem_beaconinterval - hint_text: "Beacon Interval (seconds)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_modem_beacondata - hint_text: "Beacon Data" - text: "" - font_size: dp(24) -""" - -layout_hardware_rnode_screen = """ -MDScreen: - name: "hardware_rnode_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "RNode" - anchor_title: "left" - elevation: 0 - left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] - right_action_items: - [ - ['close', lambda x: root.app.close_sub_hardware_action(self)], - ] - - ScrollView: - id: hardware_rnode_scrollview - - MDBoxLayout: - orientation: "vertical" - spacing: "8dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(28), dp(48), dp(28), dp(16)] - - MDLabel: - text: "RNode Hardware Parameters\\n" - font_style: "H6" - - MDLabel: - id: hardware_rnode_info - markup: True - text: "To communicate using an RNode, you will need to specify the following parameters. For two or more RNodes to be able to communicate, all parameters must match, except for the [i]Coding Rate[/i] and [i]TX Power[/i] parameter, which can vary between devices.\\n" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(48)] - - MDRectangleFlatIconButton: - id: rnode_mote_export - icon: "upload" - text: "Export" - 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.app.hardware_rnode_export(self) - - MDRectangleFlatIconButton: - id: rnode_mote_import - icon: "download" - text: "Import" - 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.app.hardware_rnode_import(self) - - MDLabel: - text: "Radio Options\\n" - font_style: "H6" - - # MDTextField: - # id: hardware_rnode_modulation - # hint_text: "Modulation" - # text: "LoRa" - # disabled: True - # font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_rnode_frequency - hint_text: "Frequency (MHz)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_rnode_bandwidth - hint_text: "Bandwidth (KHz)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_rnode_txpower - hint_text: "TX Power (dBm)" - text: "" - font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(24)] - - MDTextField: - id: hardware_rnode_spreadingfactor - hint_text: "Spreading Factor" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_rnode_codingrate - hint_text: "Coding Rate" - text: "" - font_size: dp(24) - - MDLabel: - text: "Optional Settings" - font_style: "H6" - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_rnode_beaconinterval - hint_text: "Beacon Interval (seconds)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_rnode_beacondata - hint_text: "Beacon Data" - text: "" - font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_rnode_atl_short - hint_text: "Airime Limit % (15s)" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_rnode_atl_long - hint_text: "Airime Limit % (1h)" - text: "" - font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - size_hint_y: None - padding: [0,dp(14),dp(24),dp(0)] - height: dp(48) - - MDLabel: - text: "Control RNode Display" - font_style: "H6" - - MDSwitch: - id: hardware_rnode_framebuffer - pos_hint: {"center_y": 0.3} - active: False - - MDLabel: - text: "•" - font_style: "H6" - text_size: self.size - halign: "center" - size_hint_y: None - height: self.texture_size[1] - padding: [0, dp(2+14), 0, dp(22+24)] - - MDLabel: - text: "WiFi & Ethernet Connection\\n" - font_style: "H6" - - MDLabel: - id: hardware_rnode_info_wifi - markup: True - text: "If your device is hosting or connected to a WiFi network, you can connect it by entering its IP address or hostname below." - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDBoxLayout: - orientation: "horizontal" - size_hint_y: None - padding: [0,dp(12),dp(24),dp(0)] - height: dp(36) - - MDLabel: - text: "Connect using WiFi" - font_style: "H6" - - MDSwitch: - id: hardware_rnode_tcp - pos_hint: {"center_y": 0.3} - active: False - - MDBoxLayout: - orientation: "vertical" - # spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_rnode_tcp_host - hint_text: "RNode IP address or hostname" - text: "" - font_size: dp(24) - - MDLabel: - text: "•" - font_style: "H6" - text_size: self.size - halign: "center" - size_hint_y: None - height: self.texture_size[1] - padding: [0, dp(2+14), 0, dp(22+24)] - - MDLabel: - text: "Bluetooth Connection\\n" - font_style: "H6" - - MDLabel: - id: hardware_rnode_info - markup: True - text: "If you enable connection via Bluetooth, Sideband will attempt to connect to any available and paired RNodes over Bluetooth.\\n\\nIf your RNode uses BLE (ESP32-S3 and nRF devices) instead of classic Bluetooth, enable the [i]Device requires BLE[/i] option as well." - 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: "Connect using Bluetooth" - font_style: "H6" - - MDSwitch: - id: hardware_rnode_bluetooth - pos_hint: {"center_y": 0.3} - active: False - - MDBoxLayout: - orientation: "horizontal" - size_hint_y: None - padding: [0,0,dp(24),dp(48)] - height: dp(86) - - MDLabel: - text: "Device requires BLE" - font_style: "H6" - - MDSwitch: - id: hardware_rnode_ble - pos_hint: {"center_y": 0.3} - active: False - - MDLabel: - text: "Bluetooth Pairing\\n" - font_style: "H6" - - MDLabel: - id: hardware_rnode_info - markup: True - text: "To put an RNode into pairing mode, hold down the multi-function user button for more than 5 seconds, and release it. The display will indicate pairing mode. If the in-app pairing does not find any devices, use the Bluetooth settings of your device to scan and pair.\\n" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDBoxLayout: - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(12)] - - MDRectangleFlatIconButton: - id: hardware_rnode_bt_scan_button - icon: "bluetooth-connect" - text: "Pair New Device" - 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.app.hardware_rnode_bt_scan_action(self) - - MDBoxLayout: - id: rnode_scan_results - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(12+24)] - - MDLabel: - text: "Preffered Bluetooth Device\\n" - font_style: "H6" - - MDLabel: - id: hardware_rnode_info - markup: True - text: "Sideband will connect to the first available RNode that is paired. If you want to always use a specific RNode, you can enter its name here, for example \\"RNode A8EB\\"." - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDBoxLayout: - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_rnode_bt_device - hint_text: "Preferred RNode Device Name" - text: "" - font_size: dp(24) - - MDLabel: - text: "•" - font_style: "H6" - text_size: self.size - halign: "center" - size_hint_y: None - height: self.texture_size[1] - padding: [0, dp(2+14), 0, dp(22)] - - MDLabel: - text: "\\n\\nDevice Bluetooth Control\\n" - font_style: "H6" - - MDLabel: - id: hardware_rnode_info - markup: True - text: "\\n\\nIf your RNode does not have a physical pairing button, you can enable Bluetooth and put it into pairing mode by first connecting it via a USB cable, and using the buttons below. When plugging in the RNode over USB, you must grant Sideband permission to the USB device for this to work.\\n\\nYou can also change Bluetooth settings using the \\"rnodeconf\\" utility from a computer.\\n" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDBoxLayout: - orientation: "vertical" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDRectangleFlatIconButton: - id: hardware_rnode_bt_on_button - icon: "bluetooth" - text: "Enable Bluetooth" - 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.app.hardware_rnode_bt_on_action(self) - - MDRectangleFlatIconButton: - id: hardware_rnode_bt_off_button - icon: "bluetooth-off" - text: "Disable Bluetooth" - 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.app.hardware_rnode_bt_off_action(self) - disabled: False - - MDRectangleFlatIconButton: - id: hardware_rnode_bt_pair_button - icon: "link-variant" - text: "Start Pairing Mode" - 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.app.hardware_rnode_bt_pair_action(self) - disabled: False -""" - -layout_hardware_serial_screen = """ -MDScreen: - name: "hardware_serial_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "Serial Port" - anchor_title: "left" - elevation: 0 - left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] - right_action_items: - [ - ['close', lambda x: root.app.close_sub_hardware_action(self)], - ] - - ScrollView: - id: hardware_serial_scrollview - - MDBoxLayout: - orientation: "vertical" - spacing: "8dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(28), dp(48), dp(28), dp(16)] - - MDLabel: - text: "Serial Hardware Parameters\\n" - font_style: "H6" - - MDLabel: - id: hardware_serial_info - markup: True - text: "To communicate using a serial port, you will need to specify the following parameters. If communicating directly to another Reticulum instance over serial, the parameters must match the other device.\\n\\nIf you are using a serial-connected device to pass on data to other Reticulum instances, it should be configured to pass data transparently to the desired endpoints.\\n" - size_hint_y: None - text_size: self.width, None - height: self.texture_size[1] - - MDLabel: - text: "Port Options" - font_style: "H6" - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - # padding: [dp(0), dp(0), dp(0), dp(35)] - - MDTextField: - id: hardware_serial_baudrate - hint_text: "Baud Rate" - text: "" - font_size: dp(24) - - MDBoxLayout: - orientation: "horizontal" - spacing: "24dp" - size_hint_y: None - height: self.minimum_height - padding: [dp(0), dp(0), dp(0), dp(24)] - - MDTextField: - id: hardware_serial_databits - hint_text: "Data Bits" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_serial_parity - hint_text: "Parity" - text: "" - font_size: dp(24) - - MDTextField: - id: hardware_serial_stopbits - hint_text: "Stop Bits" - text: "" - font_size: dp(24) -""" From 7786d2a8f15bcb2691421ba409e86fbcbca5c3c7 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 25 Dec 2025 22:41:46 +0100 Subject: [PATCH 222/271] Cleanup --- sbapp/ui/hardware.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sbapp/ui/hardware.py b/sbapp/ui/hardware.py index 24cc650..cf0b5c8 100644 --- a/sbapp/ui/hardware.py +++ b/sbapp/ui/hardware.py @@ -51,7 +51,6 @@ class Hardware(): self.hardware_screen.ids.hardware_scrollview.effect_cls = ScrollEffect def con_hide_settings(): - return # TODO: RESET self.app.widget_hide(self.hardware_screen.ids.hardware_rnode_button) self.app.widget_hide(self.hardware_screen.ids.hardware_modem_button) self.app.widget_hide(self.hardware_screen.ids.hardware_serial_button) From b8d0e79c96e1f5a2d399bd4dca5c876181bee90f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 28 Dec 2025 01:05:25 +0100 Subject: [PATCH 223/271] Updated readme --- MIRROR.md | 33 +++++++++++++++++++++++++++++++++ README.md | 2 ++ 2 files changed, 35 insertions(+) create mode 100644 MIRROR.md diff --git a/MIRROR.md b/MIRROR.md new file mode 100644 index 0000000..ef2fdd4 --- /dev/null +++ b/MIRROR.md @@ -0,0 +1,33 @@ +This repository is a public mirror. All potential future development is happening elsewhere. + +I am stepping back from all public-facing interaction with this project. Reticulum has always been primarily my work, and continuing in the current public, internet-facing model is no longer sustainable. + +The software remains available for use as-is. Occasional updates may appear at unpredictable intervals, but there will be no support, no responses to issues, no discussions, and no community management in this or any other public venue. If it doesn't work for you, it doesn't work. That is the entire extent of available troubleshooting assistance I can offer you. + +If you've followed this project for a while, you already know what this means. You know who designed, wrote and tested this, and you know how many years of my life it took. You'll also know about both my particular challenges and strengths, and how I believe anything worth building needs to be built and maintained with our own hands. + +Seven months ago, I said I needed to step back, that I was exhausted, and that I needed to recover. I believed a public resolve would be enough to effectuate that, but while striving to get just a few more useful features and protocols out, the unproductive requests and demands also ramped up, and I got pulled back into the same patterns and draining interactions that I'd explicitly said I couldn't sustain anymore. + +So here's what you might have already guessed: I'm done playing the game by rules I can't win at. + +Everything you need is right here, and by any sensible measure, it's done. Anyone who wants to invest the time, skill and persistence can build on it, or completely re-imagine it with different priorities. That was always the point. + +The people who actually contributed - you know who you are, and you know I mean it when I say: Thank you. All of you who've used this to build something real - that was the goal, and you did it without needing me to hold your hand. + +The rest of you: You have what you need. Use it or don't. I am not going to be the person who explains it to you anymore. + +This is not a temporary break. It's not "see you after some rest", but a recognition that the current model is fundamentally incompatible with my life, my health, and my reality. + +If you want to support continued work, you can do so at the donation links listed in this repository. But please understand, that this is not purchasing support or guaranteeing updates. It is support for work that happens on my timeline, according to my capacity, which at the moment is not what it was. + +If you want Reticulum to continue evolving, you have the power to make that happen. The protocol is public domain. The code is open source. Everything you need is right here. I've provided the tools, but building what comes next is not my responsibility anymore. It's yours. + +To the small group of people who has actually been here, and understood what this work was and what it cost - you already know where to find me if it actually matters. + +To everyone else: This is where we part ways. No hard feelings. It's just time. + +--- + +असतो मा सद्गमय +तमसो मा ज्योतिर्गमय +मृत्योर्मा अमृतं गमय diff --git a/README.md b/README.md index 83636c0..7c5392a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ Sideband ========= +*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere.* + Sideband is an extensible LXMF messaging and LXST telephony client, situational awareness tracker and remote control and monitoring system for Android, Linux, macOS and Windows. It allows you to communicate with other people or LXMF-compatible systems over Reticulum networks using LoRa, Packet Radio, WiFi, I2P, Encrypted QR Paper Messages, or anything else Reticulum supports. ![Screenshot](https://github.com/markqvist/Sideband/raw/main/docs/screenshots/devices_small.webp) From 63d0e4179185e4a9dd55a7aeea8fb173963edc8d Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 4 Jan 2026 01:05:59 +0100 Subject: [PATCH 224/271] Updated versions --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 39550cf..7b9548a 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.0.4", - "lxmf>=0.9.3", + "rns>=1.1.0", + "lxmf>=0.9.4", "lxst>=0.4.5", "kivy>=2.3.0", "numpy>=2.0.0", From 800616b5427c8a4e395b3d775053ebd07ad36d3c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Fri, 9 Jan 2026 01:19:56 +0100 Subject: [PATCH 225/271] Cleanup --- sbapp/main.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 3974c05..e11465a 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -27,12 +27,6 @@ import base64 import threading import RNS.vendor.umsgpack as msgpack -from LXST._version import __version__ as lxst_version -from LXST.Primitives.Recorders import FileRecorder -from LXST.Primitives.Players import FilePlayer -from LXST.Codecs import Opus -from LXST.Filters import BandPass, AGC - WINDOW_DEFAULT_WIDTH = 494 WINDOW_DEFAULT_HEIGHT = 800 WINDOW_HEIGHT_MARGIN = 0 @@ -257,6 +251,12 @@ elif args.import_settings: exit(1) if not args.daemon: + from LXST._version import __version__ as lxst_version + from LXST.Primitives.Recorders import FileRecorder + from LXST.Primitives.Players import FilePlayer + from LXST.Codecs import Opus + from LXST.Filters import BandPass, AGC + from kivy.logger import Logger, LOG_LEVELS from PIL import Image as PilImage import io From bac1d59c5df240eb87c2de74a8824a646f86d3b3 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 10 Jan 2026 00:27:43 +0100 Subject: [PATCH 226/271] Fixed attachment messages with no text content not displaying in user interface --- sbapp/sideband/core.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 7d58d4d..fe8bcbf 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -3097,7 +3097,13 @@ class SidebandCore(): else: RNS.log("Received telemetry stream field with no data: "+str(lxm.fields[LXMF.FIELD_TELEMETRY_STREAM]), RNS.LOG_DEBUG) - if own_command or len(lxm.content) != 0 or len(lxm.title) != 0: + attach_msg = False + if lxm.fields != None and len(lxm.fields) > 0: + if LXMF.FIELD_IMAGE in lxm.fields: attach_msg = True + if LXMF.FIELD_AUDIO in lxm.fields: attach_msg = True + if LXMF.FIELD_FILE_ATTACHMENTS in lxm.fields: attach_msg = True + + if own_command or len(lxm.content) != 0 or len(lxm.title) != 0 or attach_msg: with self.db_lock: db = self.__db_connect() dbc = db.cursor() From ead24279eb4fc3586e67ddf9d57bd425db0b3c4b Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 10 Jan 2026 13:54:15 +0100 Subject: [PATCH 227/271] Updated versions --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 7b9548a..8fffab3 100644 --- a/setup.py +++ b/setup.py @@ -114,9 +114,9 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.0", + "rns>=1.1.2", "lxmf>=0.9.4", - "lxst>=0.4.5", + "lxst>=0.4.6", "kivy>=2.3.0", "numpy>=2.0.0", "pillow>=10.2.0", From 72d70259a23dfa918dbaf916613e250632a6de5a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 10 Jan 2026 21:57:04 +0100 Subject: [PATCH 228/271] Added Zen of Reticulum --- Zen of Reticulum.md | 415 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 415 insertions(+) create mode 100644 Zen of Reticulum.md diff --git a/Zen of Reticulum.md b/Zen of Reticulum.md new file mode 100644 index 0000000..aa286be --- /dev/null +++ b/Zen of Reticulum.md @@ -0,0 +1,415 @@ +# Zen of Reticulum + +## I: The Illusion Of The Center + +For the better part of a generation, we have been taught to visualize the digital world through the lens of hierarchy. The mental maps we carry are dominated by a single, misleading image: **The Cloud**. + +We imagine the network as a vast, ethereal space "up there" or "out there". A centralized repository of services and data to which we, the lowly clients, must connect. We build our software with this assumption hardcoded into our logic: *There is a server. The server has the authority. The server knows the way. I must find the server to function*. + +This is the Client-Server mental model, and it is the primary obstacle to understanding Reticulum. + +### Fallacy Of The Cloud + +The first step in the Zen of Reticulum is to realize that *there is no cloud*. There is only other people's computers. When you build for the cloud, you are building *for* a landlord. You are accepting that your application's existence is conditional on the permission, uptime, and continued goodwill of a central authority. + +In Reticulum, you must shift your thinking from "connecting to" to "being among". Reticulum is not a service you subscribe to - *it is a fabric you inhabit*. There is no "up there". There is only *here* and *there*, and the space between them is peer-to-peer. + +### Decentralization Or Uncentralizability? + +It is common to hear the word "decentralized" thrown around in modern tech circles. But often, this is merely a marketing term for "slightly distributed centralization". A blockchain with a few dominant miners, or a federated protocol with a few giant servers. *In practice*, it's still centralized. It simply has a few centers instead of one. + +Reticulum goes further. It wants **Uncentralizability**. + +This is not a wishful political stance, but a foundational mathematical characteristic of the protocol, onto which everything else has been built. Reticulum assumes that every peer on the network is potentially hostile, and every link is potentially compromised. It is designed with no "privileged" nodes. While some nodes may act as Transport Instances - forwarding traffic for others - they do so *blindly*, and they only know about their immediate surroundings, and nothing more. They route based on cryptographic proofs, not on administrative privilege. They cannot see who is talking to whom, nor can they selectively manipulate traffic without breaking their own ability to route entirely. + +The system is designed to make hierarchy structurally impossible. You cannot hijack an address, because there is no central registry to hijack. You cannot block a user, because there is no central switch to flip. You can offer paths through the network, but you can't force anyone to use them. + +### Death To The Address + +To break free of the center, you must also let go of the concept of the "Address". + +In the IP world, an address is a location. It is a coordinate in a *deeply hierarchical* and static grid. If you move your computer to a different house, your address changes. If your router reboots, your address might change. Your *identity* is bound to your *location*, and therefore, it is fragile, and easily controlled. + +Reticulum abolishes this link between *Identity* and *Location*. + +In Reticulum, an address is not a place; it is a **Hash of an Identity**. It is a cryptographic representation of *who* you are, not *where* you are. Because of this, your address is portable. You can take a laptop from a WiFi cafe in Berlin, to a LoRa mesh in the mountains, to a packet radio link on a boat, and your "address" - your *Destination Hash* - never changes. + +The network does not route to a place; it routes to a *person* (or a machine). When you send a packet, you are not targeting a coordinate in a grid; you are encrypting a message for a specific entity. The network dynamically discovers where that entity currently resides, and it does so in a way where no one really knows where that entity is actually located physically. + +**Consider:** + +- **The Old Way:** *"I am at `192.168.1.5`. Come find me"*. +- **The Zen Way:** *"I am `<327c1b2f87c9353e01769b01090b18f2>`. Wherever I am, my peers can reach me"*. + +Once you stop thinking about servers and start thinking about portable identities, where everyone can always reach everyone else directly, the illusion of the center fades away. You realize there *is* no center holding the network together. No coordinators or bureaucrats required. The network is simply the sum of its peers, communicating directly, sovereignly, and without a master. + + +## II: Physics Of Trust +*Paranoia Is A Great Design Principle* + +If we accept that there is no center - that the network is a chaotic, peer-to-peer mesh - we are forced to confront a terrifying reality: **There is no one guarding the door**. + +In the traditional networking mindset, we rely on the concept of the "trusted core". We assume our local coffee shop WiFi is safe, or that the backbone providers are neutral custodians. We build our security like a castle: strong walls on the outside, soft and trusting on the inside. We use encryption only when we step out into the "wild" internet. + +### Hostile Environments + +The Zen of Reticulum requires you to invert this. You must assume that *every* environment is hostile. This isn't cynicism, just uncaring physics. + +When you transmit information over radio waves, you are shouting into a crowded room. Anyone can listen. When you traverse the internet, your packets pass through routers controlled by strangers, corporations, and state actors. Assuming privacy in this environment without cryptographic protection is not optimism but gross negligence. + +Reticulum is built on the premise that every link is tapped, and every peer is a potential adversary. If your system cannot survive an adversary owning the physical layer, it cannot survive at all. + +But this is the paradox: By assuming the network is hostile, you make it safe. When you accept the dangers for what they are, they become manageable. When you stop trusting the infrastructure and start trusting the math, you eliminate the single point of failure: Human integrity. + +### Encryption Is Not A Feature + +In the world of TCP/IP, encryption is an afterthought. It is a layer we slap on top of the protocol (HTTPS, TLS) to patch the security holes of the original design. It is a "feature" you sometimes *enable* for "sensitive data". This is fundamentally flawed, since all data is sensitive. + +In Reticulum, encryption is **gravity**. + +It is not optional. It is not a plugin. It is the *fundamental force that allows the network to exist*. If you were to strip the encryption from Reticulum, the routing would break. The Transport system uses cryptographic signatures and entropy to verify paths and pass information. If packets were plaintext, intermediate nodes could not prove that a route was valid, nor could endpoints prevent spoofing or tampering. + +In Reticulum, the entropy of the encrypted packet *is* the routing logic. + +To ask for a version of Reticulum without encryption is like asking for a version of the ocean without liquid. You are not asking for a feature change; you're asking for a different physical universe. We design for a universe where information has mass, structure, and integrity. + +### Zero-Trust Architectures + +We must unlearn our reliance on **Institutional Trust**. + +For decades, we have been trained to trust authorities. We trust a website because a chain of Certificate Authorities (companies we don't know) vouches for it. We trust an app because it is in an app store (run by a corporation we don't control). We trust a message because it comes from a phone number assigned by a telecom. Yet, everything in our digital information sphere today is more untrustworthy and risky than a medieval second-hand underwear market. + +Reticulum replaces institutional trust with **Cryptographic Proof**. + +In Reticulum, you do not trust a node because it has a nice hostname or because it is listed in a directory. You trust it because it holds the private key corresponding to the Destination Hash you are communicating with. This trust is binary, mathematical, and **absolute**. Either the signature matches, or it does not. There is no "maybe". + +This shift moves the power from the institution to the individual. You become the ultimate arbiter of your own trust relationships. You decide which keys to accept, which paths to follow, and which identities to recognize. + +**Consider:** + +- **The Old Way:** *"I trust this site because the browser says the lock icon is green"*. +- **The Zen Way:** *"I trust this destination because I have verified its hash fingerprint out-of-band, and the math confirms the signature"*. + +When you internalize the Physics of Trust, you stop looking for protection from firewalls, VPNs, and Terms of Service agreements. You realize that true security comes from the design of the protocol itself. You can stop trusting the cloud, and you start trusting the code - because you can verify it yourself. + + +## III: Merits Of Scarcity +*Every Bit Counts* + +We have grown addicted to abundance. In the modern digital ecosystem, bandwidth is treated as an endless, flat ocean. We stream high-definition video without a thought, we ship entire libraries of code just to render a single button, and we measure performance in gigabits per second. This abundance has hollowed out our craft. When constraints vanish, efficiency dies, and with it, a certain kind of Clarity and Quality. + +Reticulum asks you to step out of the ocean and onto the tightrope. + +### The Bandwidth Fallacy + +The Zen of Reticulum requires the realization that **5 bits per second is a valid speed**. + +To a modern developer, this sounds like paralysis. But there is a profound freedom in limits: When you have a gigabit connection, you can be incredibly sloppy. You can be wasteful. You can push your problems onto the infrastructure. *"It’s slow? Get a faster router"*. + +But on a high-latency, low-bandwidth link (be it a noisy HF radio channel or a tenuous LoRa hop) you cannot push problems anywhere. You must solve them. The network does not negotiate with waste. + +This forces a shift from consumption to interaction. You are no longer, then, consuming a service provided by a fat pipe; you are engaging in a careful negotiation with the physical medium. The medium becomes a partner in the conversation, not just a dumb conduit. You suddenly need to *understand the world to be in it*. + +### Cost Of A Byte + +In a scarce economy, a byte is not just data, but energy, time, and space. + +Every byte you transmit consumes battery life on a solar-powered node. It occupies valuable airtime that could have been used by another peer. It represents a measurable slice of the electromagnetic spectrum. + +When you internalize this, you begin to write code differently. You stop asking, "How much data can I send?" and start asking, "What is the *minimum* amount of information required to convey this intent? How can I best utilize my informational entropy?" + +This is where the elegance of Reticulum shines. The protocol is designed to strip away the non-essential. A link establishment takes three very small packets. A destination hash fits in 16 bytes. The overhead is vanishingly small, leaving almost the entire channel for the message itself. + +**Consider:** + +- **The Old Way:** *"I need to send a status update. I'll send a JSON object with metadata, timestamps, and user profile info (15KB)."* +- **The Zen Way:** *"I need to send a status update. I'll send a single byte representing the state code. The context is already known."* + +This is of course optimization, but more importantly, *it is a form of respect*. Efficiency in a shared medium is an act of stewardship. By taking only what you need from the network, you leave room for others. The network listens to those who speak with purpose. + +### Flow & Time + +Scarcity also teaches us about time. We have become addicted to the *synchronous* now - the instant ping, the real-time stream. But Reticulum embraces *asynchronous* time. + +When links are intermittent and latency is measured in minutes or hours, "real-time" is an illusion. Reticulum doesn't encourage **Store and Forward** as a mere fallback, but as a primary mode of existence. You write a message, it propagates when it can, and it arrives when it arrives. + +This changes the psychological texture of communication. It removes the anxiety of the immediate response. It allows for contemplation. You are not demanding the recipient's attention *right now*; you are placing a gift in their path, to be found when they are ready. + +By designing for delay, you design for resilience. You are no longer building a house of cards that collapses when a single packet drops. You are building a stone arch that distributes the load *over time*. + +### Liberation From Limits + +There is a strange optimism in scarcity. When you are forced to work within strict constraints, you are forced to prioritize. *You* must decide what truly matters. *That* is the real core of agency. + +In the infinite fantasy world of The Cloud, everything is urgent, so nothing is. In the economy of Reticulum, the cost of transmission forces you to weigh the value of your message. Do you really need to send that heart beat? Is that photo essential? + +When you strip away the noise, what remains is *signal*. + +This discipline creates a different kind of developer. It creates a craftsman who understands that the best code is the code you don't have to write. It creates a user who understands that the most powerful message is the one that is *understood*, not the one that is loudest. In the world of Reticulum, you are not a mere consumer of bandwidth; you are an architect of intent. + + +## IV: Sovereignty Through Infrastructure +**Be Your Own Network** + +We live in an era of digital tenancy. We lease our connectivity from ISPs. We rent our storage from cloud providers. We even borrow our identity from social media platforms. We are tenants in a house we did not build, governed by rules we did not write, subject to eviction at the whim of a landlord who has never met us. + +The Zen of Reticulum is the realization that you *can* own the house. + +### A Carrier-Grade Fallacy + +For decades, we have been gaslit into believing that networking is really not just hard, but impossible. It is presented as a dark art reserved for telcos and billionaires, requiring millions of dollars of fiber optics, climate-controlled data centers, and armies of engineers. We are told that building reliable infrastructure is "too complex" for the individual or small organization. + +This is a big, fat lie. + +Physics is simple. A radio wave needs a transmitter and a receiver. A packet needs a path. The "complexity" of the modern internet is largely bureaucratic - a mountain of billing systems, regulatory capture, and legacy cruft designed to keep the gatekeepers in power. + +Reticulum strips away the bureaucracy. It runs on hardware that costs the price of a dinner. It runs on spectrum that is free to use. It demonstrates that a robust, planetary-scale network does not require a Fortune 500 company. It requires only the will to deploy, and the distributed, uncoordinated efforts of many individuals. + +### Personal Infrastructure + +This is where the rubber meets the road. You can read about Reticulum, you can understand the theory, but the insights only arrive when you plug in a radio and run a Transport Node. Suddenly, you are no longer a consumer. You're an operator. + +This shift is subtle but profound. When you run your own infrastructure, the network ceases to be a service that is provided *to* you. It becomes a space that you *inhabit*. You become responsible for the flow of information. You gain an intimate understanding of the medium - the way the weather affects the radio waves, the way the topology changes, the way the packets dance through the ether. + +There is a quiet competence that comes from this. You stop asking "Is the internet down?" and start asking "Is *my* links up?" You stop waiting for a technician and start checking the logs. This is a form of strength. To understand the system that carries your words is to be free from the mystery that keeps you dependent. + +### The Ability To Disconnect + +Why go to the trouble? Why buy the radio, write the config, and leave the Pi running in the corner? + +Because the old, centralized network is fragile. And because most of us doesn't even really want to be there anymore. + +The internet we rely on today is a chain of single points of failure. Cut the undersea cable, and a continent goes dark. Shut down the power grid, and the cloud evaporates. Deprioritize the "wrong" traffic, and the flow of information is strangled. + +Sovereignty is the ability to survive the cut, whether or not that cut was an accident or on purpose. + +When you build your own infrastructure, you build a lifeline. Reticulum is designed to function over media that the traditional internet cannot touch - bare wires, battery-powered radios, ad-hoc WiFi meshes. When the grid fails, or the censors arrive, or the bill goes unpaid, your Reticulum network continues to hum. + +This is not about "dropping out" of society. It is about building a substrate on which an actual *Society* can function. + +**Consider:** + +- **The Old Way:** "My connection is slow. I should call my ISP and complain." +- **The Zen Way:** "The path is noisy. I will adjust the antenna or find a better route." + +By taking ownership of the infrastructure, you take ownership of your voice. You stop shouting into someone else's megaphone and start building your own. The network is no longer something that happens to you; it is something you make happen. + + +# V: Identity and Nomadism +**A Fluid Self** + +In the old world, you are defined by your coordinates. If you are at `34.109.71.5`, you're *here*. If you unplug the cable and walk down the street, you vanish. Your digital self evaporates because it was tethered to the wall. You are a ghost in the endless machinations of gears, levers and transistors, bound to the hardware, and those that own it. + +This creates a subtle, constant anxiety. We are terrified of disconnecting because, in the architecture of the old web, disconnecting is a kind of death. + +The Zen of Reticulum offers a different way to be. + +### Portable Existence + +In Reticulum, your identity is not a location, or a username granted by a service. It is a cryptographic key - a complex, unique mathematical signature that exists independently of the physical world. You can carry it only in your mind, if you want to. + +Think of it less like a street address and more like a name. *A true name*. + +If you travel from Berlin to Tokyo, you do not change your name. You are still you. The people who know you can still recognize you. Reticulum applies this principle to the network layer. Your Destination Hash is **invariant**. It travels with you, stored securely on your device, *immutable as a stone*. + +This changes the relationship between you and the machine. You are not "logged into" the network via a specific gateway. You *are* the endpoint. The network does not connect to a place; *it converges on you*. + +### Roaming Nodes + +This freedom introduces a new concept of time and space: **Nomadism**. + +Because your identity is portable, your connectivity can be fluid. You can be sitting at a desk connected to a fiber backbone one moment, and walking through a field connected only to a long-range LoRa mesh the next. To the rest of the network, nothing has changed. Your friends do not need to update your contact info. The messages they send do not bounce back. The network senses the shift in the medium and reroutes the flow of data automatically. + +You are no longer a stationary node in a fixed grid. You are a wanderer in a fluid medium. + +The interfaces - whether it is WiFi, Ethernet, Packet Radio, or a physical wire - is merely the clothing your node wears. You change it to suit the environment. Underneath, you remain the same. This is the liberation of the protocol. It treats the physical medium as a transient circumstance, not a definition of self. + +**Consider:** + +- **The Old Way:** *"I lost connection. I have to reconnect to the VPN to tell them where I am now."* +- **The Zen Way:** *"I moved. The network subtly bends to accomodate this new reality."* + +### Announcing Presence + +How does the network find a wanderer? It listens. + +In the IP world, we query directories. We ask a server, "Where is Mark?" The server checks its database and gives us a coordinate. This means that someone, somewhere, is keeping track of you. It assumes and *requires* surveillance. + +Reticulum replaces surveillance with **Announces**. + +Instead of asking a central authority where you are, you simply state your presence. You broadcast a cryptographic proof: "I am here, and I am who I say I am". This ripples out through the mesh. Your neighbors hear it, update their path tables, and pass it on. + +This is a quiet, organic process. It is the digital equivalent of lighting lanterns in the dark. You do not need to chase the light; you let the light find you. It respects your autonomy. You choose when to announce, how often to speak, and to whom. You also choose when to disappear - for but a moment or perpetually. + +### Anchor In The Flow + +There is a deep peace in this nomadism. It teaches you that stability does not come from standing still. Stability comes from *internal coherence*. + +By holding your own private key, you hold your own center of gravity. The world around you; the infrastructure, the topography and the availability of links can all shift chaotically. Storms can knock out towers. Cables can be cut. The internet can go down. + +But as long as you possess your key, you possess your identity. The entire infrastructure can be destroyed and rebuilt, and you are still you. Nothing lasts, yet nothing is lost. + +You become a sovereign entity moving through the noise, connected not by the rigidity of cables, but by the fluidity of recognition. The network becomes a place you inhabit, rather than a utility you subscribe to: You are at home in the ether. + + +## VI: Ethics Of The Tool +**Technology With Conscience** + +You have unlearned the center. You have accepted the physics of trust. You have embraced the economy of scarcity and the freedom of unbound nomadism. You are standing in a new space. Now, look at the tool in your hand. + +In the old world, we were taught that technology is neutral. We are told that "guns don't kill people, people do", or that a component is just a component, indifferent to what its combinatorial potential is. This is a convenient lie. It serves only to allow the builders to wash their hands of responsibility. + +But we know better now. We know that **architecture is politics**, and *politics is control*. The way you build a system determines how it will be used. If you build a system optimized for mass surveillance, you *will* get a panopticon. If you build a system optimized for centralized control, you *will* get a dictatorship. If you build a system optimized for extraction, you *will* get a parasite. + +The Zen of Reticulum asserts that a tool is never neutral. + +On the very contrary: A tool is intent, **crystallized**. + +### The Harm Principle + +Why does the Reticulum License forbid the software from being used in systems designed to harm humans? Is it not just a restriction on freedom? + +It is a restriction on *license*, yes, but it is an expansion of *freedom*. + +Building powerful tools without a moral compass is in no way virtuous or commendable, it is plain and simple irresponsibility. + +A tool that can easily be used to oppress is a real danger to the user. If you build a network that can be turned against you by a tyrant, you are not free. You are merely waiting for the leash to tighten. By encoding the "Harm Principle" into the legal DNA of the reference implementation, we are building a safeguard. We are stating, clearly and immutably, that *this tool* is for **life**, not for death. + +This aligns the software with the interests of humanity. It cements that the network cannot be conscripted into a kill-system, a weaponized drone controller, or a torture device without breaking the license and the law. It is a line drawn in the sand - not by a government or external authority, but by the creators of the tool itself. + +**Consider:** + +- **The Old Way:** *"It's just software. How people use it is not my problem."* +- **The Zen Way:** *"This software is a habitat. I will not allow it to be used to build a cage."* + +It is *your* choice whether to align with this - we are not forcing this stance on anyone. If you choose to align with life over death, with creativity over destruction, we grant you an immensely powerful tool, to own and build with as you please. If you do not, we deny it. + +If you do not like this, we most assuredly do not need you here, and you are on your own. + +### Public Domain Protocol + +This leads to a vital distinction: The difference between the *idea* and the *implementation*. + +The protocol - the mathematical rules of how Reticulum works - is dedicated to the Public Domain. It belongs to humanity. **No one can own it**. Anyone can implement it, improve it, or adapt it. This is the core idea of free communication, which itself must be forever free. + +But the functional, deployed *reference implementation* - the Python code, the maintenance, the years of labor - has a conscience. This distinction is the engine of sustainability. It allows the protocol to be universal, while ensuring that the specific labor of the builders is not hijacked to undermine the foundational intent of the project itself. From this document, it should be very clear what this intent is. + +If you want to build a system with Reticulum that manipulates and damages users for profits or targets missiles, you can use the public domain protocol, and start from scratch. But you cannot take our work. You must do your own. This serves as a pillar of accountability. If you want to build a weapon, *you* go and forge the steel yourself, while the world observes. And when the blood is drawn - it is on **your** hands. + +### Preserving Human Agency + +We live in an era of predatory extraction. The open-source commons is being scraped, ingested, and regurgitated by machine learning algorithms, whose corporate owners seek to replace the very humans who built those commons. Our code, our words, and our creativity is being used to train systems that are specifically designed to make us obsolete, without offering anything else in return than serfdom and leashes. + +Reticulum stands against this. + +The license protects the software from being used to feed the beast. It draws a hard line: This tool is for *people*. It is for human-to-human connection. It is not a dataset to be strip-mined for the purpose of building a synthetic overlord, puppeteered by a miniscule conglomerate of controllers. + +This is a radical act of preservation. By protecting the code from AI appropriation, we are protecting space for human agency. We are ensuring that there remains a digital realm where the actors are flesh, blood and soul, where decisions are made by minds, not overlords hiding behind models. + +When you use Reticulum, you are using a tool that respects you. It does not see you as a product to be tracked. It does not see your data as fuel for an algorithm. It sees you as a sovereign, equal peer. + +This changes the foundational premise of using the technology. It restores dignity to the interaction. You are not the user of a service; you are a participant in a mutual covenant. The tool aligns with your autonomy, rather than eroding it. + +In this way, ethics is not a restriction, but a foundation. It is the foundation that helps ensure the network will still belong to you tomorrow. + + +## VII: Design Patterns For Post-IP Systems +**Practical Philosophy for Developers** + +The philosophy is useless if it cannot be hammered into code. The metaphors we have explored - nomadism, scarcity, trust - are not just poetry, but real-world engineering constraints. When you sit down to write software for Reticulum, these concepts must shape the very structure of your application. + +We are now moving from the *why* to the *how*. This is where the abstract becomes concrete, and where you will see the true depth of the patterns we have been weaving. + +### Store & Forward + +The web has trained us to be impatient. We write synchronous code. We fire a request and we wait, blocking the UI, holding our breath. If the response doesn't come in 250 milliseconds, we show a spinner. If it doesn't come in five seconds, we show an error. We treat network connectivity as a binary state: either we are "online" or we are "broken". + +This is brittle. It is a rejection of reality. + +In Reticulum, connectivity is a spectrum, and presence is asynchronous. If at all applicable to your intent, you must design your applications to embrace **Store & Forward**. + +Instead of demanding an immediate answer, your application should act as a patient participant. You create a message for someone or something in the mesh. The network holds it. It carries it from node to node, perhaps over hours or days, waiting for the recipient to appear. When they finally surface, the message is delivered. This requires a shift from "request/response" to "event/handler". How exactly you do this is a challenge for you to solve intelligently within your problem domain, but Reticulum-based systems already exist that does this extremely well, and you can use them for inspiration. + +**Consider:** + +- **The Old Way:** `Connect() -> Send() -> Wait() -> Crash if timeout.` +- **The Zen Way:** `Send() -> Continue living. -> Receive() when it arrives.` + +This changes the user experience profoundly. It removes the anxiety of the loading bar. It creates a sense of continuity. The user is not "waiting for the network"; they are interacting with a persistent log of communication that lives in the network itself. + +### Naming Is Power + +In the IP world, we are slaves to the Domain Name System. We rely on a hierarchy of registrars to map human-readable names to machine-readable addresses. This hierarchy is a choke point. If the registrar revokes your domain, or if the DNS server goes down, you vanish. + +Reticulum dissolves this hierarchy with **Hash-based Identity**. + +In this design pattern, a name is not a string you look up; it is a cryptographic destination you verify. When you design for Reticulum, you stop asking the user for a URL and start asking for a Destination or Identity Hash. + +This feels strange at first. A hash like `<83b7328926fed0d2e6a10a7671f9e237>` looks alien compared to `myfriend.com`. But that alienness is the armor. It **cannot** be spoofed. It **cannot** be censored by a registrar. It is **absolute**. + +Designing for this means shifting your UI metaphors. You are no longer browsing a web of pages; you are managing a ledger of keys. You are building an "Address Book" that is actually a keyring. The names are given by the user, and the power stays with them. That hashes look complex is directly analogous to the strengths of the bonds formed by their use. It forces the user to engage in a moment of verification, an out-of-band handshake, which restores the human element of trust that SSL certificates stripped away. + +### The Interface Is The Medium + +One of the most liberating patterns in Reticulum is **Transport Agnosticism**. + +In traditional networking, your code is often littered with transport logic. "Am I on WiFi? Check bandwidth. Am I on Cellular? Check data plan. Am I on Ethernet?". You are constantly micromanaging the pipe. + +In Reticulum, you write to the API, and the API writes to the medium. You send a packet to a Destination. You do not care if that packet travels over a TCP tunnel, a LoRa radio wave, or a serial wire interface. That is the stack's concern. + +This allows you to write **Universal Applications**. +Imagine a messaging app. You write it once. It works on a laptop connected to fiber. It works on a phone in the city using WiFi. And, without a single line of code changed, it works on a device in the wilderness, talking only to other devices via radio. + +The pattern is simple: **Never code to the hardware. Code to the intent.** + +**Consider:** + +- **The Old Way:** `socket.connect(ip, port)` +- **The Zen Way:** `RNS.Packet(destination, data).send()` + +By abstracting the medium, you make your software immortal to changes in infrastructure. The user might switch from a 4G hotspot to a HF modem tomorrow. Your software doesn't need to know. It simply continues the conversation. + +### Emergent Patterns + +When you combine these patterns - *Store & Forward*, *Hash-based Identity*, and *Transport Agnosticism* - you create software that feels fundamentally different. + +It feels *grounded*. It doesn't flicker when the signal drops. It doesn't panic when the server is down. It has weight. It has persistence. It has *relevance*. + +You are no longer building a "client" that begs a "server" for attention. You are building an autonomous agent that exists within the mesh. It speaks when it needs to, listens when it can, and carries its identity with it wherever it goes. + +This is the culmination of the Zen. The code is not just a set of instructions: It is a behavioral envelope. It is a way of *being* in the network. + + +## VIII: Fabric Of The Independent + +We have stripped away the illusions. We have seen that the center is empty, that trust *must* be hard, that resources are finite, and that we must own our infrastructure. We have seen that tools have ethics and that our identity can move fluidly. + +This is a reclaiming of the commons. For too long, we have allowed the most vital substrate of human society - *our ability to speak to one another* - to be colonized by entities that do not share our interests. We have allowed the architecture of our communication to be designed by accountants rather than architects. + +We are taking it back. Not by petitioning the masters, but by building the new world within, over, under and around the shell of the old. + +### The Work Is Finished + +The heavy lifting is done. + +The protocol is in the public domain, a gift to humanity that can never be taken away. The software is written, tested, and running on devices scattered across the globe. The manual lies open before you. The source code for the reference implementation is now distributed on hundreds of thousands of devices across the planet. No one can delete or destroy it. The hardware is accessible and abundant. + +It was a hard road to get here, but we got here. Now, there is no roadmap committee waiting for approval. There is no venture capital dictating the user experience. There is no CEO to sign off on the next feature release. + +There is only you. + +The barrier to entry is no longer complexity: It is the mere habit of dependency. You were conditioned to wait. Wait for the app update. Wait for the ISP to fix the line. Wait for the platform to allow the post. Wait for the government to change the policies. Wait for the likes. Wait for the revolution to be televised. + +The revolution never was televised. + +It is packetized. + +### Open Sky + +The future of this technology is a construction project. + +It looks like a single node on a windowsill, listening to the static. It looks like a message sent to a neighbor, bypassing the noise of the commercial web. It looks like a community mesh that grows, link by link, hop by hop, carried by hands that care more about connection than profit. + +You have the blueprints. You have the tools. You have the philosophy. The noise of the old world has fallen away, leaving you with the quiet clarity of the open spectrum. + +*Mark, early 2026* \ No newline at end of file From 75f927d340ff920530e011f42c6c7834a0c4ea3e Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 10 Jan 2026 21:57:14 +0100 Subject: [PATCH 229/271] Updated readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7c5392a..51edec3 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ Sideband =1.1.2", + "rns>=1.1.3", "lxmf>=0.9.4", "lxst>=0.4.6", "kivy>=2.3.0", From e7bef4d1fc8ff93a69fa62824125425aeb424950 Mon Sep 17 00:00:00 2001 From: matthieu Texier Date: Mon, 19 Jan 2026 10:08:43 +0100 Subject: [PATCH 231/271] make links clicable in sideband --- sbapp/ui/messages.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index af26f2d..9b1f408 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -14,6 +14,7 @@ from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.utils import escape_markup +from kivy.app import App from kivymd.uix.button import MDRectangleFlatButton, MDRectangleFlatIconButton from kivymd.uix.dialog import MDDialog @@ -48,18 +49,48 @@ if RNS.vendor.platformutils.is_darwin(): from kivy.lang.builder import Builder from kivymd.uix.list import OneLineIconListItem, IconLeftWidget +import re +import webbrowser MSG_RENDER_LIMIT = 11000 +# Match URLs starting with http(s):// or www. +_url_pattern = re.compile(r"(https?://[^\s\]]+|www\.[^\s\]]+)") + + +def _add_url_refs(text: str) -> str: + """Wrap plain URLs in Kivy [ref] markup. + + - Supports links like: + * http://example.com + * https://example.com + * www.example.com + - If the text already contains [ref=...] markup, leave it untouched to + avoid double-wrapping existing references. + """ + if "[ref=" in text: + return text + return _url_pattern.sub(r"[ref=\1]\1[/ref]", text) + + class DialogItem(OneLineIconListItem): divider = None icon = StringProperty() + class ListLXMessageCard(MDCard): # class ListLXMessageCard(MDCard, FakeRectangularElevationBehavior): text = StringProperty() heading = StringProperty() + def on_ref_press(self, instance, ref): + try: + if isinstance(ref, str) and (ref.startswith("http://") or ref.startswith("https://")): + webbrowser.open(ref) + except Exception as e: + RNS.log(f"Error opening URL reference {ref}: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + class Messages(): def __init__(self, app, context_dest): self.app = app @@ -535,7 +566,10 @@ class Messages(): if not ("lxm" in m and m["lxm"] != None and m["lxm"].fields != None and LXMF.FIELD_COMMANDS in m["lxm"].fields): message_input = "[i]This message contains no text content[/i]".encode("utf-8") - message_markup = multilingual_markup(message_input) + # Add clickable URL refs before multilingual font markup is applied + message_text_for_markup = message_input.decode("utf-8") + message_text_for_markup = _add_url_refs(message_text_for_markup) + message_markup = multilingual_markup(message_text_for_markup.encode("utf-8")) txstr = time.strftime(ts_format, time.localtime(m["sent"])) rxstr = time.strftime(ts_format, time.localtime(m["received"])) @@ -1489,6 +1523,7 @@ Builder.load_string(""" id: content_text text: root.text markup: True + on_ref_press: root.on_ref_press(*args) size_hint_y: None text_size: self.width, None height: self.texture_size[1] From 6053063720ad76df852d4ebda939070e4dd1cdff Mon Sep 17 00:00:00 2001 From: Antonio Galea Date: Tue, 27 Jan 2026 16:03:23 +0100 Subject: [PATCH 232/271] Trap and log errors when loading plugins --- sbapp/sideband/core.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index fe8bcbf..0e6c958 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -849,7 +849,11 @@ class SidebandCore(): plugin_globals["SidebandTelemetryPlugin"] = SidebandTelemetryPlugin RNS.log("Loading plugin \""+str(file)+"\"", RNS.LOG_NOTICE) plugin_path = os.path.join(plugins_path, file) - exec(open(plugin_path).read(), plugin_globals) + try: + exec(open(plugin_path).read(), plugin_globals) + except Exception as e: + RNS.log("Error loading plugin \""+str(file)+"\": "+str(e), RNS.LOG_ERROR) + continue plugin_class = plugin_globals["plugin_class"] if plugin_class != None: From 1cf0b567fa151569a09e6b3cf06b5ed799453087 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 12 Apr 2026 20:03:01 +0200 Subject: [PATCH 233/271] Updated versions --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index be778f7..d17ed01 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.3", + "rns>=1.1.5", "lxmf>=0.9.4", "lxst>=0.4.6", "kivy>=2.3.0", From 5c37c5f1470f8e08020acd34f3ebb2a1e595aa46 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 12 Apr 2026 20:34:52 +0200 Subject: [PATCH 234/271] Updated version --- sbapp/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e11465a..61e6f82 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.8.3" +__version__ = "1.9.0" __variant__ = "" import sys @@ -3195,7 +3195,7 @@ class SidebandApp(MDApp): str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)" str_comps += "\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)\n - [b]Able[/b] (MIT 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" + str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright © 2026 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+"\nRunning on RNS v"+RNS.__version__+", LXMF v"+LXMF.__version__+" and LXST v"+lxst_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) @@ -5727,4 +5727,4 @@ if __name__ == "__main__": run() if __name__ == "sbapp.main": - run() \ No newline at end of file + run() From aead89262f332882b9eea930c1cbe0ef7e64cb2a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 01:52:59 +0200 Subject: [PATCH 235/271] Cleanup --- sbapp/sideband/core.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 0e6c958..e2b978c 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -849,10 +849,9 @@ class SidebandCore(): plugin_globals["SidebandTelemetryPlugin"] = SidebandTelemetryPlugin RNS.log("Loading plugin \""+str(file)+"\"", RNS.LOG_NOTICE) plugin_path = os.path.join(plugins_path, file) - try: - exec(open(plugin_path).read(), plugin_globals) + try: exec(open(plugin_path).read(), plugin_globals) except Exception as e: - RNS.log("Error loading plugin \""+str(file)+"\": "+str(e), RNS.LOG_ERROR) + RNS.log(f"Error loading plugin \"{file}\": {e}", RNS.LOG_ERROR) continue plugin_class = plugin_globals["plugin_class"] From bd747cadce20ffdc064e04ccbba2c2d2cadf238a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 01:59:21 +0200 Subject: [PATCH 236/271] Formatting --- sbapp/ui/messages.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 9b1f408..38a3edc 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -70,7 +70,7 @@ def _add_url_refs(text: str) -> str: """ if "[ref=" in text: return text - return _url_pattern.sub(r"[ref=\1]\1[/ref]", text) + return _url_pattern.sub(r"[u][ref=\1]\1[/ref][/u]", text) class DialogItem(OneLineIconListItem): From b40e83b9b69f10c10ab0755316482bd6bd59c200 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 02:00:24 +0200 Subject: [PATCH 237/271] Cleanup --- sbapp/ui/messages.py | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 38a3edc..8c9e896 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -59,20 +59,9 @@ _url_pattern = re.compile(r"(https?://[^\s\]]+|www\.[^\s\]]+)") def _add_url_refs(text: str) -> str: - """Wrap plain URLs in Kivy [ref] markup. - - - Supports links like: - * http://example.com - * https://example.com - * www.example.com - - If the text already contains [ref=...] markup, leave it untouched to - avoid double-wrapping existing references. - """ - if "[ref=" in text: - return text + if "[ref=" in text: return text return _url_pattern.sub(r"[u][ref=\1]\1[/ref][/u]", text) - class DialogItem(OneLineIconListItem): divider = None icon = StringProperty() From 606272571a657def9bf61099acefdd361a19a80d Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 12:55:32 +0200 Subject: [PATCH 238/271] Updated readme --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 51edec3..b2dd190 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,11 @@ pamac install python-pyaudio opusfile codec2 xclip xsel # For Arch and derivatives sudo pacman -Sy python-pyaudio opusfile codec2 xclip xsel +# Clipboard support on Wayland: If the clipboard is not +# working correctly on Wayland with xclip and xsel, you +# can install wl-clipboard and wl-clipboard-x11 instead. +pamac remove xclip xsel +pamac install wl-clipboard wl-clipboard-x11 ``` Once those are installed, install the Sideband application itself: From 1fe28ae702737c2ba37c89db0caadeb0cad738ed Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 13:56:55 +0200 Subject: [PATCH 239/271] Implemented runtime patch to fix broken Kivy on Python 3.14+ --- sbapp/compat.py | 43 +++++++++++++++++++++++++++++++++++++++++++ sbapp/main.py | 10 +++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 sbapp/compat.py diff --git a/sbapp/compat.py b/sbapp/compat.py new file mode 100644 index 0000000..d9e2252 --- /dev/null +++ b/sbapp/compat.py @@ -0,0 +1,43 @@ +def python314_kivy_patch(): + print("Running Kivy on Python 3.14+ detected, checking compatibility patch...") + import os + import importlib.util + from pathlib import Path + + def fail_patch(): + print("Error: Failed to open Kivy's lang/parser.py file for patching.") + print("Kivy currently has bugs that prevents it from running on Python 3.14") + print("and above, and this file needs to be patched to run Sideband.") + print("\nYou can patch this manually by locating the lang/parser.py file") + print(f"and replacing:\n\n{kivy_target_1}\n\nWith:\n\n{kivy_patch_1}\n") + os._exit(0) + + kivy_target_1 = """ if isinstance(node, (ast.JoinedStr, ast.BoolOp)): + for n in node.values: + if isinstance(n, ast.Str): + # NOTE: required for python3.6 + yield from cls.get_names_from_expression(n.s) + else: + yield from cls.get_names_from_expression(n.value)""" + + kivy_patch_1 = """ if isinstance(node, (ast.JoinedStr, ast.BoolOp)): + for n in node.values: + yield from cls.get_names_from_expression(n.value)""" + + spec = importlib.util.find_spec("kivy") + if spec is None or spec.origin is None or spec.submodule_search_locations is None: fail_patch() + contents = None + + target_path = f"{spec.submodule_search_locations[0]}/lang/parser.py" + with open(target_path, "rb") as fh: contents = fh.read().decode("utf-8") + if not contents: fail_patch() + contents = contents.replace("\r\n", "\n") + + if kivy_patch_1 in contents: print("Kivy already patched for Python 3.14 compatibility, continuing.") + if kivy_target_1 in contents: + print("Patching Kivy for Python 3.14 compatibility...") + contents = contents.replace(kivy_target_1, kivy_patch_1) + if not kivy_patch_1 in contents: fail_patch() + with open(target_path, "wb") as fh: + fh.write(contents.encode("utf-8")) + print("Kivy successfully patched for Python 3.14 compatibility") diff --git a/sbapp/main.py b/sbapp/main.py index 61e6f82..8fe040b 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -75,7 +75,6 @@ def get_display_res(): RNS.trace_exception(e) return None, None - def apply_ui_scale(): global app_ui_scaling_path global app_ui_wcfg_path @@ -149,6 +148,15 @@ def apply_ui_scale(): except Exception as e: RNS.log(f"Error while reading saved window configuration: {e}", RNS.LOG_ERROR) +################################################### +# Run-time patch to fix broken Kivy on Python 3.14 +# until a Kivy release is made that actually works. +# +if sys.version_info[0] >= 3 and sys.version_info[1] >= 14: + if RNS.vendor.platformutils.is_linux(): + from .compat import python314_kivy_patch + python314_kivy_patch() + ################################################### # Kivy/SDL2 run-time patch to fix horribly slow # window resize updates on Linux. For more info: From 41e9b1794036b34b9b627b673e5fb13f9b4c9304 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 14:16:57 +0200 Subject: [PATCH 240/271] Cleanup --- sbapp/compat.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sbapp/compat.py b/sbapp/compat.py index d9e2252..94864d3 100644 --- a/sbapp/compat.py +++ b/sbapp/compat.py @@ -38,6 +38,11 @@ def python314_kivy_patch(): print("Patching Kivy for Python 3.14 compatibility...") contents = contents.replace(kivy_target_1, kivy_patch_1) if not kivy_patch_1 in contents: fail_patch() - with open(target_path, "wb") as fh: - fh.write(contents.encode("utf-8")) - print("Kivy successfully patched for Python 3.14 compatibility") + try: + with open(target_path, "wb") as fh: + fh.write(contents.encode("utf-8")) + print("Kivy successfully patched for Python 3.14 compatibility") + + except Exception as e: + print(f"Error while patching Kivy: {e}") + fail_patch() From 3a658198ac1a9da14d200e1c90285b938bd8ef3a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 14:18:37 +0200 Subject: [PATCH 241/271] Cleanup --- sbapp/compat.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sbapp/compat.py b/sbapp/compat.py index 94864d3..b6e3624 100644 --- a/sbapp/compat.py +++ b/sbapp/compat.py @@ -29,7 +29,11 @@ def python314_kivy_patch(): contents = None target_path = f"{spec.submodule_search_locations[0]}/lang/parser.py" - with open(target_path, "rb") as fh: contents = fh.read().decode("utf-8") + try: + with open(target_path, "rb") as fh: contents = fh.read().decode("utf-8") + except Exception as e: + print(f"Error while reading Kivy's lang parser file: {e}") + if not contents: fail_patch() contents = contents.replace("\r\n", "\n") From aa05ee20d196536e8d94688f60c7339e8f23635c Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 14:51:10 +0200 Subject: [PATCH 242/271] Updated resources --- sbapp/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sbapp/Makefile b/sbapp/Makefile index d425806..c5097d2 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -69,10 +69,10 @@ endif fetchshare: -(rm ./share/pkg/*) -(rm ./share/mirrors/* -r) - cp ../../dist_archive/rns-1.0.4-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/rnspure-1.0.4-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/lxmf-0.9.3-py3-none-any.whl ./share/pkg/ - cp ../../dist_archive/nomadnet-0.9.1-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rns-1.1.5-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/rnspure-1.1.5-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/lxmf-0.9.4-py3-none-any.whl ./share/pkg/ + cp ../../dist_archive/nomadnet-0.9.9-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/rnsh-0.1.7-py3-none-any.whl ./share/pkg/ cp ../../dist_archive/RNode_Firmware_*_Source.zip ./share/pkg/ zip --junk-paths ./share/pkg/example_plugins.zip ../docs/example_plugins/*.py From 73b0f6d4b28f971b9b6ba5666060a5555ae17c23 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 16:55:25 +0200 Subject: [PATCH 243/271] Updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2dd190..4e7648b 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Sideband provides many useful and interesting functions, such as: - Remote **telemetry querying**, with strong, secure and cryptographically robust authentication and control. - **Plugin system** that allows you to easily **create your own commands**, services and telemetry sources. -Sideband is fully compatible with other LXMF clients, such as [MeshChat](https://github.com/liamcottle/reticulum-meshchat), and [Nomad Network](https://github.com/markqvist/nomadnet). The Nomad Network client also allows you to easily host Propagation Nodes for your LXMF network, and more. +Sideband is fully compatible with other LXMF clients, such as [MeshChatX](https://git.quad4.io/RNS-Things/MeshChatX), and [Nomad Network](https://github.com/markqvist/nomadnet). The Nomad Network client also allows you to easily host Propagation Nodes for your LXMF network, and more. # Installation From 75373f3aa0a51374fe6fbc140fb6d8ec3308a922 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 18:28:15 +0200 Subject: [PATCH 244/271] Fixed button navigation on keys screen --- sbapp/ui/keys.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sbapp/ui/keys.py b/sbapp/ui/keys.py index 5b5e8aa..cd62b9c 100644 --- a/sbapp/ui/keys.py +++ b/sbapp/ui/keys.py @@ -37,6 +37,10 @@ class Keys(): self.keys_screen.ids.keys_info.text = info1 self.keys_screen.ids.backup_info.text = info2 + def test_a(self, sender): + RNS.log("TEST ACTION"); + RNS.log(self) + RNS.log(self.app) def _profile_backup_job(self): import tarfile @@ -160,10 +164,10 @@ MDScreen: anchor_title: "left" elevation: 0 left_action_items: - [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + [['menu', lambda x: root.app.app.nav_drawer.set_state("open")]] right_action_items: [ - ['close', lambda x: root.app.close_keys_action(self)], + ['close', lambda x: root.app.app.close_keys_action(self)], ] ScrollView: From 2529a70339dbebcf3051d93600767f6d00d76758 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 13 Apr 2026 19:15:33 +0200 Subject: [PATCH 245/271] Updated makefile --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index 204a51a..c012aa7 100644 --- a/Makefile +++ b/Makefile @@ -79,6 +79,7 @@ prepare_win_pkg: clean build_spkg rm build/winpkg/sbapp/buildozer.spec cp winbuild.bat build/ mv build/winpkg build/sideband_sources + chmod -R a+rw build/sideband_sources cd build; zip -r winbuild.zip sideband_sources winbuild.bat mv build/winbuild.zip dist/winbuild.zip From e798bac4c7f7f6a3f93ee5b2c8682771aef26222 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sat, 18 Apr 2026 16:37:33 +0200 Subject: [PATCH 246/271] Updated versions --- sbapp/main.py | 3 ++- setup.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 8fe040b..e87c802 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.9.0" +__version__ = "1.9.1" __variant__ = "" import sys @@ -483,6 +483,7 @@ else: from .ui.hardware import Hardware from .ui.objectdetails import ObjectDetails from .ui.messages import Messages, ts_format, messages_screen_kv + # from .ui.messages_recycle import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem from .ui.helpers import multilingual_markup, mdc, dark_theme_text_color diff --git a/setup.py b/setup.py index d17ed01..725e6a3 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.5", + "rns>=1.1.6", "lxmf>=0.9.4", "lxst>=0.4.6", "kivy>=2.3.0", From cd323c9ca841d08a19c0831c0437ebe4ea9682fd Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 19 Apr 2026 01:31:04 +0200 Subject: [PATCH 247/271] Background data persist on app pause on Android --- sbapp/main.py | 2 +- sbapp/sideband/core.py | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e87c802..9e8be46 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1063,7 +1063,7 @@ class SidebandApp(MDApp): self.sideband.setstate("app.running", True) self.sideband.setstate("app.foreground", False) self.app_state = SidebandApp.PAUSED - self.sideband.should_persist_data() + self.sideband.should_persist_data(background=True) RNS.log("App paused", RNS.LOG_DEBUG) return True diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index e2b978c..367ba9b 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -580,10 +580,8 @@ class SidebandCore(): total += entry.stat(follow_symlinks=False).st_size return total - def should_persist_data(self): - if self.reticulum != None: - self.reticulum._should_persist_data() - + def should_persist_data(self, background=False): + if self.reticulum != None: self.reticulum._should_persist_data(background=background) self.save_configuration() def __load_telemetry_collector_excluded(self): From 6f8f4351f654dd0445e25ca6c0fb59bdcc19723a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 21 Apr 2026 10:24:07 +0200 Subject: [PATCH 248/271] Fixed message loading performance --- sbapp/main.py | 1 + sbapp/sideband/core.py | 42 +++++++++++++++++++++++++++--------------- sbapp/ui/messages.py | 3 +-- 3 files changed, 29 insertions(+), 17 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 9e8be46..e98400b 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -449,6 +449,7 @@ else: from ui.objectdetails import ObjectDetails from ui.announces import Announces from ui.messages import Messages, ts_format, messages_screen_kv + # from ui.messages_recycle import Messages, ts_format, messages_screen_kv from ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem from ui.helpers import multilingual_markup, mdc, dark_theme_text_color from kivymd.toast import toast diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 367ba9b..0b7d4db 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -2999,19 +2999,32 @@ class SidebandCore(): with self.db_lock: db = self.__db_connect() dbc = db.cursor() - + + base_condition = "(dest=:context_dest or source=:context_dest)" if after != None and before == None: - query = "select * from lxm where (dest=:context_dest or source=:context_dest) and rx_ts>:after_ts" - dbc.execute(query, {"context_dest": context_dest, "after_ts": after}) + query = f"select * from lxm where {base_condition} and rx_ts>:after_ts ORDER BY rx_ts DESC" + params = {"context_dest": context_dest, "after_ts": after} + if limit is not None: + query += f" LIMIT :limit_val"; params["limit_val"] = int(limit) + dbc.execute(query, params) elif after == None and before != None: - query = "select * from lxm where (dest=:context_dest or source=:context_dest) and rx_ts<:before_ts" - dbc.execute(query, {"context_dest": context_dest, "before_ts": before}) + query = f"select * from lxm where {base_condition} and rx_ts<:before_ts ORDER BY rx_ts DESC" + params = {"context_dest": context_dest, "before_ts": before} + if limit is not None: + query += f" LIMIT :limit_val"; params["limit_val"] = int(limit) + dbc.execute(query, params) elif after != None and before != None: - query = "select * from lxm where (dest=:context_dest or source=:context_dest) and rx_ts<:before_ts and rx_ts>:after_ts" - dbc.execute(query, {"context_dest": context_dest, "before_ts": before, "after_ts": after}) + query = f"select * from lxm where {base_condition} and rx_ts<:before_ts and rx_ts>:after_ts ORDER BY rx_ts DESC" + params = {"context_dest": context_dest, "before_ts": before, "after_ts": after} + if limit is not None: + query += f" LIMIT :limit_val"; params["limit_val"] = int(limit) + dbc.execute(query, params) else: - query = "select * from lxm where dest=:context_dest or source=:context_dest" - dbc.execute(query, {"context_dest": context_dest}) + query = f"select * from lxm where {base_condition} ORDER BY rx_ts DESC" + params = {"context_dest": context_dest} + if limit is not None: + query += f" LIMIT :limit_val"; params["limit_val"] = int(limit) + dbc.execute(query, params) result = dbc.fetchall() @@ -3034,10 +3047,8 @@ class SidebandCore(): lxm.paper_packed = paper_packed_lxm extras = None - try: - extras = msgpack.unpackb(entry[11]) - except: - pass + try: extras = msgpack.unpackb(entry[11]) + except: pass message = { "hash": lxm.hash, @@ -3054,8 +3065,9 @@ class SidebandCore(): } messages.append(message) - if len(messages) > limit: - messages = messages[-limit:] + + messages.reverse() + if len(messages) > limit: messages = messages[-limit:] return messages def _db_save_lxm(self, lxm, context_dest, originator = False, own_command = False, is_retry = False): diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index 8c9e896..5e2026b 100644 --- a/sbapp/ui/messages.py +++ b/sbapp/ui/messages.py @@ -271,8 +271,7 @@ class Messages(): else: self.hide_widget(self.ids.message_ptt, True) c_ts = time.time() - if len(self.new_messages) > 0: - self.update_widget() + if len(self.new_messages) > 0: self.update_widget() if (len(self.added_item_hashes) < self.db_message_count) and not self.load_more_button in self.list.children: self.list.add_widget(self.load_more_button, len(self.list.children)) From 73b9bd032fdfbf829b74adf48b30e01ccabef876 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 21 Apr 2026 10:51:25 +0200 Subject: [PATCH 249/271] Updated versions --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 725e6a3..4db951e 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.6", - "lxmf>=0.9.4", + "rns>=1.1.7", + "lxmf>=0.9.5", "lxst>=0.4.6", "kivy>=2.3.0", "numpy>=2.0.0", From 04908eb45b2da76b5045cfad6ca267fd23def87f Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Tue, 21 Apr 2026 19:17:14 +0200 Subject: [PATCH 250/271] Versions --- sbapp/main.py | 2 +- sbapp/sideband/core.py | 16 +++++----------- setup.py | 2 +- 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index e98400b..4b8871f 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -2872,7 +2872,7 @@ class SidebandApp(MDApp): else: self.messages_view.ids.messages_scrollview.dest_known = False if self.messages_view.ids.nokeys_text.text == "": - keys_str = "The crytographic keys for the destination address are unknown at this time. You can wait for an announce to arrive, or query the network for the necessary keys." + keys_str = "The cryptographic keys for the destination address are unknown at this time. You can wait for an announce to arrive, or query the network for the necessary keys." self.messages_view.ids.nokeys_text.text = keys_str self.widget_hide(self.messages_view.ids.message_input_part, True) self.widget_hide(self.messages_view.ids.message_ptt, True) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 0b7d4db..c0d8bbc 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -957,10 +957,8 @@ class SidebandCore(): def log_announce(self, dest, app_data, dest_type, stamp_cost=None, link_stats=None): try: - if app_data == None: - app_data = b"" - if type(app_data) != bytes: - app_data = msgpack.packb([app_data, stamp_cost]) + if app_data == None: 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), RNS.LOG_DEBUG) self._db_save_announce(dest, app_data, dest_type, link_stats) self.setstate("app.flags.new_announces", True) @@ -3418,14 +3416,10 @@ class SidebandCore(): def is_known(self, dest_hash): try: source_identity = RNS.Identity.recall(dest_hash) + if source_identity: return True + else: return False - if source_identity: - return True - else: - return False - - except Exception as e: - return False + except Exception as e: return False def request_key(self, dest_hash): try: diff --git a/setup.py b/setup.py index 4db951e..69e6022 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.7", + "rns>=1.1.8", "lxmf>=0.9.5", "lxst>=0.4.6", "kivy>=2.3.0", From fcc0341fe95b2b5dd9e695a62bbca9895b42b935 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Wed, 22 Apr 2026 13:42:08 +0200 Subject: [PATCH 251/271] Updated versions --- sbapp/main.py | 2 +- setup.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index 4b8871f..c47928d 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,6 +1,6 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "1.9.1" +__version__ = "1.9.2" __variant__ = "" import sys diff --git a/setup.py b/setup.py index 69e6022..d166bf3 100644 --- a/setup.py +++ b/setup.py @@ -114,8 +114,8 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.8", - "lxmf>=0.9.5", + "rns>=1.1.9", + "lxmf>=0.9.6", "lxst>=0.4.6", "kivy>=2.3.0", "numpy>=2.0.0", From 39f00554a80727ae202fdff46b1d207505ed1606 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Thu, 23 Apr 2026 01:19:55 +0200 Subject: [PATCH 252/271] Improved announce logging handling --- sbapp/main.py | 2 +- sbapp/sideband/core.py | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sbapp/main.py b/sbapp/main.py index c47928d..f7e9032 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1064,7 +1064,7 @@ class SidebandApp(MDApp): self.sideband.setstate("app.running", True) self.sideband.setstate("app.foreground", False) self.app_state = SidebandApp.PAUSED - self.sideband.should_persist_data(background=True) + self.sideband.should_persist_data(background=False) RNS.log("App paused", RNS.LOG_DEBUG) return True diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index c0d8bbc..5ddead3 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -90,10 +90,10 @@ class PropagationNodeDetector(): pass else: - RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)} with data: {app_data}", RNS.LOG_EXTREME) + RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)}", RNS.LOG_EXTREME) else: - RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)} with data: {app_data}", RNS.LOG_EXTREME) + RNS.log(f"Received malformed propagation node announce from {RNS.prettyhexrep(destination_hash)}", RNS.LOG_EXTREME) except Exception as e: RNS.log("Error while processing received propagation node announce: "+str(e)) @@ -371,8 +371,9 @@ class SidebandCore(): self.active_propagation_node = None self.propagation_detector = PropagationNodeDetector(self) - RNS.Transport.register_announce_handler(self) - RNS.Transport.register_announce_handler(self.propagation_detector) + if self.is_service or self.is_standalone: + RNS.Transport.register_announce_handler(self) + RNS.Transport.register_announce_handler(self.propagation_detector) self.active_command_plugins = {} self.active_service_plugins = {} @@ -806,8 +807,7 @@ class SidebandCore(): def __save_config(self, no_thread=False): RNS.log("Saving Sideband configuration...", RNS.LOG_DEBUG) def save_function(): - while self.saving_configuration: - time.sleep(0.15) + while self.saving_configuration: time.sleep(0.15) try: self.saving_configuration = True with open(self.config_path, "wb") as config_file: config_file.write(msgpack.packb(self.config)) @@ -826,8 +826,8 @@ class SidebandCore(): if no_thread: save_function() else: threading.Thread(target=save_function, daemon=True).start() - if self.is_client: - self.setstate("wants.settings_reload", True) + if self.is_client: self.setstate("wants.settings_reload", True) + RNS.log("Sideband configuration saved", RNS.LOG_DEBUG) def __load_plugins(self): plugins_path = self.config["command_plugins_path"] From 5705e24dde6df8db7981203daf1c68efa635c719 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Apr 2026 16:19:45 +0200 Subject: [PATCH 253/271] Added basic server telemetry plugin example --- docs/example_plugins/server_telemetry.py | 119 +++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 docs/example_plugins/server_telemetry.py diff --git a/docs/example_plugins/server_telemetry.py b/docs/example_plugins/server_telemetry.py new file mode 100644 index 0000000..b6fd63f --- /dev/null +++ b/docs/example_plugins/server_telemetry.py @@ -0,0 +1,119 @@ +# This is a basic server telemetry plugin +# example that you can build upon to +# implement your own telemetry plugins. + +import RNS +import time +import psutil +import shutil +from threading import Thread +import urllib.request, json + +class ServerTelemetryPlugin(SidebandTelemetryPlugin): + plugin_name = "server_telemetry" + + def start(self): + # Do any initialisation work here + RNS.log("Server Telemetry plugin starting...") + self.initialise_values() + + self.power_stats = False + self.storage_stats = True + self.target_disk = {"blkid": "mmcblk0p2", "label": "SD Card"} + self.should_run = True + + self.update_thread = Thread(target=self.update_job, daemon=True) + self.update_thread.start() + + # And finally call start on superclass + super().start() + + def stop(self): + # Do any teardown work here + self.should_run = False + + # And finally call stop on superclass + super().stop() + + def initialise_values(self): + self.battery_percent = None + self.power_production = None + self.power_consumption = None + self.battery_charging = None + self.battery_temperature = None + self.uptime = None + + def update_job(self): + while self.should_run: + try: + # Update uptime + self.uptime = RNS.prettytime(time.time()-psutil.boot_time()) + + # Update power values if enabled + if self.power_stats: + with urllib.request.urlopen("http://some_host/status.json") as url: + data = json.loads(url.read().decode()) + self.power_production = data["solar_yield"] + self.power_consumption = data["inverter_load"]+data["dc_consumption"] + self.battery_charging = data["battery_current"] >= 0.0 + self.battery_charge = data["battery_charge"] + self.battery_temperature = data["battery_temperature"] + + except Exception as e: + RNS.log("Error while updating plugin telemetry: "+str(e), RNS.LOG_ERROR) + + time.sleep(15) + + def update_telemetry(self, telemeter): + if telemeter != None: + + if self.power_stats: + # Create power consumption sensor + telemeter.synthesize("power_consumption") + telemeter.sensors["power_consumption"].update_consumer(self.power_consumption, type_label="Power consumption") + + # Create power production sensor + telemeter.synthesize("power_production") + telemeter.sensors["power_production"].update_producer(self.power_production, type_label="Solar production", custom_icon="solar-power-variant") + + # Create battery sensor + telemeter.synthesize("battery") + telemeter.sensors["battery"].data = {"charge_percent": round(self.battery_charge, 1), "charging": self.battery_charging} + + + # Create NVM sensor if enabled + if self.storage_stats: + mount_point = None + for partition in psutil.disk_partitions(all=False): + if self.target_disk["blkid"] in partition.device: + mount_point = partition.mountpoint + break + + if mount_point: + st = shutil.disk_usage(mount_point) + telemeter.synthesize("nvm") + telemeter.sensors["nvm"].update_entry(capacity=st.total, used=st.used, type_label=self.target_disk["label"]) + + # Create RAM sensors + ms = psutil.virtual_memory() + telemeter.synthesize("ram") + telemeter.sensors["ram"].update_entry(capacity=ms.total, used=ms.used, type_label="RAM") + + # Create CPU sensor + a = psutil.getloadavg() + cps = 0; cpms = 5 + for m in range(cpms): + cps += psutil.cpu_percent()/100.0 + time.sleep(0.05) + cp = cps/cpms + + telemeter.synthesize("processor") + telemeter.sensors["processor"].update_entry(current_load=cp, clock=round(psutil.cpu_freq().current*1e6, 0), load_avgs=[a[0], a[1], a[2]], type_label="CPU") + + # Create custom sensor for uptime + telemeter.synthesize("custom") + telemeter.sensors["custom"].update_entry(self.uptime, type_label="Uptime is", custom_icon="timer-refresh-outline") + +# Finally, tell Sideband what class in this +# file is the actual plugin class. +plugin_class = ServerTelemetryPlugin \ No newline at end of file From 9f0d776e3fded4fd9200f8cb419364d5b39a2d84 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Apr 2026 16:19:55 +0200 Subject: [PATCH 254/271] Added basic Raspberry Pi telemetry plugin example --- docs/example_plugins/raspi_telemetry.py | 152 ++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 docs/example_plugins/raspi_telemetry.py diff --git a/docs/example_plugins/raspi_telemetry.py b/docs/example_plugins/raspi_telemetry.py new file mode 100644 index 0000000..f32f260 --- /dev/null +++ b/docs/example_plugins/raspi_telemetry.py @@ -0,0 +1,152 @@ +# This is a basic Raspberry Pi telemetry plugin +# example that you can build upon to +# implement your own telemetry plugins. + +import os +import RNS +import time +import psutil +import shutil +from threading import Thread +import urllib.request, json + +class RasPiTelemetryPlugin(SidebandTelemetryPlugin): + plugin_name = "raspi_telemetry" + + def start(self): + # Do any initialisation work here + RNS.log("Raspberry Pi Telemetry plugin starting...") + self.initialise_values() + + self.power_stats = False + self.storage_stats = True + self.target_disk = {"blkid": "mmcblk0p2", "label": "SD Card"} + self.should_run = True + + self.update_thread = Thread(target=self.update_job, daemon=True) + self.update_thread.start() + + # And finally call start on superclass + super().start() + + def stop(self): + # Do any teardown work here + self.should_run = False + + # And finally call stop on superclass + super().stop() + + def initialise_values(self): + self.battery_percent = None + self.power_production = None + self.power_consumption = None + self.battery_charging = None + self.battery_temperature = None + self.uptime = None + + def update_job(self): + while self.should_run: + try: + # Update uptime + self.uptime = RNS.prettytime(time.time()-psutil.boot_time()) + + # Update power values if enabled + if self.power_stats: + with urllib.request.urlopen("http://some_host/status.json") as url: + data = json.loads(url.read().decode()) + self.power_production = data["solar_yield"] + self.power_consumption = data["inverter_load"]+data["dc_consumption"] + self.battery_charging = data["battery_current"] >= 0.0 + self.battery_charge = data["battery_charge"] + self.battery_temperature = data["battery_temperature"] + + except Exception as e: + RNS.log("Error while updating plugin telemetry: "+str(e), RNS.LOG_ERROR) + + time.sleep(15) + + def update_telemetry(self, telemeter): + if telemeter != None: + + if self.power_stats: + # Create power consumption sensor + telemeter.synthesize("power_consumption") + telemeter.sensors["power_consumption"].update_consumer(self.power_consumption, type_label="Power consumption") + + # Create power production sensor + telemeter.synthesize("power_production") + telemeter.sensors["power_production"].update_producer(self.power_production, type_label="Solar production", custom_icon="solar-power-variant") + + # Create battery sensor + telemeter.synthesize("battery") + telemeter.sensors["battery"].data = {"charge_percent": round(self.battery_charge, 1), "charging": self.battery_charging} + + + # Create NVM sensor if enabled + if self.storage_stats: + mount_point = None + for partition in psutil.disk_partitions(all=False): + if self.target_disk["blkid"] in partition.device: + mount_point = partition.mountpoint + break + + if mount_point: + st = shutil.disk_usage(mount_point) + telemeter.synthesize("nvm") + telemeter.sensors["nvm"].update_entry(capacity=st.total, used=st.used, type_label=self.target_disk["label"]) + + # Create RAM sensors + ms = psutil.virtual_memory() + telemeter.synthesize("ram") + telemeter.sensors["ram"].update_entry(capacity=ms.total, used=ms.used, type_label="RAM") + + # Create CPU sensor + a = psutil.getloadavg() + cps = 0; cpms = 5 + for m in range(cpms): + cps += psutil.cpu_percent()/100.0 + time.sleep(0.05) + cp = cps/cpms + + telemeter.synthesize("processor") + telemeter.sensors["processor"].update_entry(current_load=cp, clock=round(psutil.cpu_freq().current*1e6, 0), load_avgs=[a[0], a[1], a[2]], type_label="CPU") + + # Create custom sensor for uptime + telemeter.synthesize("custom") + telemeter.sensors["custom"].update_entry(self.uptime, type_label="Uptime is", custom_icon="timer-refresh-outline") + + # Read temperature using built-in sensor + try: + cpu_temp_path = '/sys/class/thermal/thermal_zone0/temp' + with open(cpu_temp_path) as f: temp = int(f.read().strip()) / 1000.0 + + telemeter.synthesize("temperature") + telemeter.sensors["temperature"].data = {"c": round(temp, 2)} + + except Exception as e: RNS.log(f"Getting temperature reading failed: {e}", RNS.LOG_ERROR) + + # Network Interfaces + try: + for iface in os.listdir('/sys/class/net'): + carrier = None + speed = None + + try: + with open(f'/sys/class/net/{iface}/carrier') as f: carrier = int(f.read().strip()) == 1 + except FileNotFoundError: pass + + if iface.startswith('eth') or iface.startswith('wlan'): + try: + with open(f'/sys/class/net/{iface}/speed') as f: speed = int(f.read().strip()) + except (FileNotFoundError, ValueError): pass + + telemeter.synthesize("custom") + speed_str = f" at {RNS.prettyspeed(speed*1e6)}" if speed else "" + sensors_str = f"carrier{speed_str}" if carrier else "has no carrier" + telemeter.sensors["custom"].update_entry(value=f"{sensors_str}", type_label=f"{iface}", custom_icon="lan" if carrier else "lan-disconnect") + + except Exception as e: RNS.log(f"Getting network stats failed: {e}", RNS.LOG_DEBUG) + +# Finally, tell Sideband what class in this +# file is the actual plugin class. +plugin_class = RasPiTelemetryPlugin From cba08b6999928bc6446ddfc10cf7ebaec99fae0a Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Mon, 27 Apr 2026 16:20:08 +0200 Subject: [PATCH 255/271] Cleanup --- sbapp/sideband/core.py | 33 ++++++++++----------------------- setup.py | 2 +- 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/sbapp/sideband/core.py b/sbapp/sideband/core.py index 5ddead3..baef83b 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -3279,42 +3279,31 @@ class SidebandCore(): def update_telemetry(self): try: - try: - latest_telemetry = deepcopy(self.latest_telemetry) - except: - latest_telemetry = None + try: latest_telemetry = deepcopy(self.latest_telemetry) + except: latest_telemetry = None telemetry = self.get_telemetry() packed_telemetry = self.get_packed_telemetry() telemetry_changed = False if telemetry != None and packed_telemetry != None: - if latest_telemetry == None or len(telemetry) != len(latest_telemetry): - telemetry_changed = True + if latest_telemetry == None or len(telemetry) != len(latest_telemetry): telemetry_changed = True if latest_telemetry != None: - if not telemetry_changed: for sn in telemetry: - if telemetry_changed: - break + if telemetry_changed: break if sn != "time": if sn in latest_telemetry: - if telemetry[sn] != latest_telemetry[sn]: - telemetry_changed = True - else: - telemetry_changed = True + if telemetry[sn] != latest_telemetry[sn]: telemetry_changed = True + else: telemetry_changed = True if not telemetry_changed: for sn in latest_telemetry: - - if telemetry_changed: - break - + if telemetry_changed: break if sn != "time": - if not sn in telemetry: - telemetry_changed = True + if not sn in telemetry: telemetry_changed = True if telemetry_changed: self.telemetry_changes += 1 @@ -3323,10 +3312,8 @@ class SidebandCore(): self.setstate("app.flags.last_telemetry", time.time()) if self.is_client: - try: - self.service_set_latest_telemetry(self.latest_telemetry, self.latest_packed_telemetry) - except Exception as e: - RNS.log("Error while sending latest telemetry to service: "+str(e), RNS.LOG_ERROR) + try: self.service_set_latest_telemetry(self.latest_telemetry, self.latest_packed_telemetry) + except Exception as e: RNS.log("Error while sending latest telemetry to service: "+str(e), RNS.LOG_ERROR) except Exception as e: import traceback diff --git a/setup.py b/setup.py index d166bf3..cd8e2e8 100644 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setuptools.setup( ] }, install_requires=[ - "rns>=1.1.9", + "rns>=1.2.0", "lxmf>=0.9.6", "lxst>=0.4.6", "kivy>=2.3.0", From cae7152070ac6001596b13b36b6ff428b0dac45d Mon Sep 17 00:00:00 2001 From: markqvist Date: Fri, 29 May 2026 11:04:33 +0200 Subject: [PATCH 256/271] Added release manifest --- sideband_1.9.5.rsm | Bin 0 -> 1455 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 sideband_1.9.5.rsm diff --git a/sideband_1.9.5.rsm b/sideband_1.9.5.rsm new file mode 100644 index 0000000000000000000000000000000000000000..373843f2a3f8286f40b62a4cb695c370793e9969 GIT binary patch literal 1455 zcmdPf^ZMEaks}kf*CsCCcDsB2;-=!O5?6bSx30PSY%a^HTWLo$8$54lwfvZ0%Bi3jXt1x z_Q~b17q>M8PP=lBC(B{4ckSfN|G6#c%F^4GQ?)nYpROC5gEO=dvV2d6wlD zWu|B59T6z=T*}*$$YgZUG28J{XV(8E1&JjYn~G9PGLuVlN^|vLb}dWJ&&|y&xv62C zXk=t)lxC4^WMOEOlxAU+Y+z|_l4N3RWN2Vyk!qT1kd&5el$yLUv8W_7Eit*Icybfi z*?WqU5(^4+!EV(ps5I8i%g;;IP0Xv*E6>PTTvVKX&A2-$akJy4^r)ofgnxDSH5Tov3OQ!VjVn~%1yokp<@nnFUVrGw+#9_% ziHm>TRo-Km@$hl^iNJsZ$a*@PM@dWi+ukkB}x&hy~HhaVdqn=g8lZFEc!uT(jp zGV@K(yoe-;sTEH}Hq3vlCHZ8@VFTH78ogIU8hH=gwtRUdDOqc(?b;Jl&++044W>6u zKfC>4Ld3;)gzKA6zTF*yY9mg~oDVt}RYXPd#!uBqOs}AvZBI zuOu}uF)uk)0h-?xGV_viN>fsc6-qKv6><_wfZ1FDS~3(X Date: Mon, 1 Jun 2026 14:38:40 +0200 Subject: [PATCH 257/271] Added manifest --- sideband_1.9.6.rsm | Bin 0 -> 1611 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 sideband_1.9.6.rsm diff --git a/sideband_1.9.6.rsm b/sideband_1.9.6.rsm new file mode 100644 index 0000000000000000000000000000000000000000..440a7249d050a1f5f1b09acca558b59e7d8c7aa2 GIT binary patch literal 1611 zcmc(feNa?Y7{;q{l2#NUb)2E5Lm=tmF8jgm0#UK?F+(~{1`Ze*oW1w#-oxI#cf05A zF3Xn<9|Q=OpIYen1tJ8<*KMOVFr>PM5GpjCQi(D0d1yc=)cC9bN)DI z-t(Mie$Tw`G?lmFqWAu$s*s|-v1cbgztI1C{jDw;+c32%=E&*RZ&GsnD9LL2Gc@y_ zA65rG&No{4_-b3vxjnCL56N?HT2kJ|K*ES_JMs_)YIOSM*|Qfkc4mEcdBiuRiS<`} zXEKJ2-zt$ccp`J(NGR`oeoMuPW*ZV=wTEB}hXn8PUSZefsIivU^(!B3ScF!+=&?IY zR^;|3CS5)gxTdBkb#2^Z;d{#RLk=FUtjMVvt@*klE3>`pr{}g#T*~fS=ev0N`at(9 zo9fOS56nwEw4t~b`)%cx@X+pN4%$!~!89^Kj&5}#fnc6%Q7hw=`ZfWv2ogje(5N(e zg-TlL47Da+tBcpgz0fXV8zLgK*^lQvT-52|1#H2bceyjIWobFQPcvY&8c$W_`J3%f zWV!?-V#>ifY|(fA@=(0ZhQ*<^Dzye_O_U0$4dxg_tk!_kNJVK4P!*>^YMs`sL9qsH zOl&(8L~MqXNNP*xZ1)lqwA&SPUKMt?R>AQcQb5kFbTRB+fmpoPdc&A=OOfvF(p~S$ z4j0H38K2gi{YpQv?*m2U*vE-i%El|#Y#i1k3~w9HY~TN2N6&6UP|(zkWR)-hXDFX2 zD_bDGcdn(4QV{`1oBBEzX9cZ$y0Pv0WH4}kAFd3Z+2D>jFc)9h{~zDKLYU{$lYTqS zoH;Z(nV6$_7f}{q`#hC^_^?Ht9j_H0CI0E0q4aIb&i*!jQTwxc>R8cRf!~gf{PD|J zfo^|wIIC}WTF+;{|48xR;1?Z7hJCBk$rYw)$wE~4L;aCAUP|9`ss6nY>dBkMz_la! z;3q3e0%}U4W~h_L?kbh8e^OCGyLFz%fGJ_;)xz4~^7G#Al~)J*ce;vBOz&0J-;DaO z@qv#rdWRNIv#wLovAT#Fd3ID?RI@eG|5VV%AGiBT-wX?lT(%GmU)?jIE%sk`Cp=LR zG}4_EaI$cEU(x!mh{=)lDGyzsx85Zhty0$#XhC1z%VjW_fZI(DD4r7`<_Lfsz&1NC zh>#P38Rr8tFMwR5L*&yq5eZTUqFg|DX+X^m0APlg#he9*yd Date: Tue, 9 Jun 2026 22:52:21 +0200 Subject: [PATCH 258/271] Update README.md --- README.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e7648b..3b5cd95 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,31 @@ This also means that Sideband is designed to be fully compatible with custom (an ## On Linux -On all Linux-based operating systems, Sideband is available as a `pip`/`pipx` package. You can either pull and install Sideband directly from the `pip` repository, or download and install locally using `whl` package from the [latest release page](https://github.com/markqvist/Sideband/releases/latest). +On most Linux-based operating systems, you can simply download the pre-compiled AppImage from the [latest release page](https://github.com/markqvist/Sideband/releases/latest) and run it. + +Depending on your Linux distribution, you may need to install a few other packages for full voice call, audio messaging and clipboard functionality. Make sure you have `opusfile`, and a clipboard manager like `xclip` or `wl-clipboard` installed: + +```bash +# For Debian 13+, Ubuntu 24.04+ and derivatives +sudo apt install libopusfile0 xclip xsel + +# For Debian 12+, Ubuntu 22.04+ and derivatives +sudo apt install libopusfile0 xclip xsel + +# For Manjaro and derivatives +pamac install opusfile xclip xsel + +# For Arch and derivatives +sudo pacman -Sy opusfile xclip xsel + +# Clipboard support on Wayland: If the clipboard is not +# working correctly on Wayland with xclip and xsel, you +# can install wl-clipboard and wl-clipboard-x11 instead. +pamac remove xclip xsel +pamac install wl-clipboard wl-clipboard-x11 +``` + +You can also install Sideband as a `pip`/`pipx` package. You can either pull and install Sideband directly from the `pip` repository, or download and install locally using `whl` package from the [latest release page](https://github.com/markqvist/Sideband/releases/latest). This installation method **includes desktop integration**, so that Sideband will show up in your applications menu and launchers. Below are install steps for the most common recent Linux distros. For Debian 11, see the end of this section. From d1b108035a263c8ae46eeb1c36d0ced155b365e0 Mon Sep 17 00:00:00 2001 From: markqvist Date: Wed, 10 Jun 2026 20:21:59 +0200 Subject: [PATCH 259/271] Update README.md --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 3b5cd95..15cd0e1 100644 --- a/README.md +++ b/README.md @@ -69,9 +69,6 @@ On most Linux-based operating systems, you can simply download the pre-compiled Depending on your Linux distribution, you may need to install a few other packages for full voice call, audio messaging and clipboard functionality. Make sure you have `opusfile`, and a clipboard manager like `xclip` or `wl-clipboard` installed: ```bash -# For Debian 13+, Ubuntu 24.04+ and derivatives -sudo apt install libopusfile0 xclip xsel - # For Debian 12+, Ubuntu 22.04+ and derivatives sudo apt install libopusfile0 xclip xsel From 863b925011473e7e906ef7c93ed14dc8d8f76d70 Mon Sep 17 00:00:00 2001 From: markqvist Date: Wed, 10 Jun 2026 20:27:23 +0200 Subject: [PATCH 260/271] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 15cd0e1..ef9599a 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,9 @@ python3 -m sbapp.main ## On Raspberry Pi -You can install Sideband on all Raspberry Pi models that support 64-bit operating systems, and can run at least Python version 3.11. +The easiest way to install Sideband on Raspberry Pi is to simply download and run the `aarch64` AppImage. On some versions of Raspberry Pi OS, you may also need to install additional libraries for full voice and clipboard functionality with `sudo apt install libopusfile0 xclip xsel`. + +You can also install Sideband using `pip` on all Raspberry Pi models that support 64-bit operating systems, and can run at least Python version 3.11. The install instructions below assume that you are installing Sideband on 64-bit Raspberry Pi OS (based on Debian 13 "Trixie" or later). If you're running something else on your Pi, you might need to modify some commands slightly. From 8601d84580341f2c499041615d772610edb9eaab Mon Sep 17 00:00:00 2001 From: markqvist Date: Fri, 3 Jul 2026 13:51:23 +0200 Subject: [PATCH 261/271] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ef9599a..780531b 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ This also means that Sideband is designed to be fully compatible with custom (an On most Linux-based operating systems, you can simply download the pre-compiled AppImage from the [latest release page](https://github.com/markqvist/Sideband/releases/latest) and run it. -Depending on your Linux distribution, you may need to install a few other packages for full voice call, audio messaging and clipboard functionality. Make sure you have `opusfile`, and a clipboard manager like `xclip` or `wl-clipboard` installed: +Depending on your Linux distribution, you *may* need to install a few other packages for full voice call, audio messaging and clipboard functionality. If any of those features do not work, make sure you have `opusfile`, and a clipboard manager like `xclip` or `wl-clipboard` installed: ```bash # For Debian 12+, Ubuntu 22.04+ and derivatives @@ -181,7 +181,7 @@ python3 -m sbapp.main ## On Raspberry Pi -The easiest way to install Sideband on Raspberry Pi is to simply download and run the `aarch64` AppImage. On some versions of Raspberry Pi OS, you may also need to install additional libraries for full voice and clipboard functionality with `sudo apt install libopusfile0 xclip xsel`. +The easiest way to install Sideband on Raspberry Pi is to simply download and run the `aarch64` AppImage. On some versions of Raspberry Pi OS, you *may* also need to install additional libraries for full voice and clipboard functionality with `sudo apt install libopusfile0 xclip xsel`. You can also install Sideband using `pip` on all Raspberry Pi models that support 64-bit operating systems, and can run at least Python version 3.11. From fa55fb9fae77b49cdf8f69c8388436533873d7c3 Mon Sep 17 00:00:00 2001 From: markqvist Date: Tue, 21 Jul 2026 23:27:34 +0200 Subject: [PATCH 262/271] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 780531b..0ebf24e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Sideband ========= -*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere.* +*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere. While new releases are posted here, the latest source code is only available over Reticulum.* To understand the foundational philosophy and goals of this system, read the [Zen of Reticulum](Zen%20of%20Reticulum.md). From 5c2fad812614a024c01ef31d0729cf90f6633ee7 Mon Sep 17 00:00:00 2001 From: markqvist Date: Tue, 21 Jul 2026 23:27:53 +0200 Subject: [PATCH 263/271] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0ebf24e..a4cfca0 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ Sideband ========= -*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere. While new releases are posted here, the latest source code is only available over Reticulum.* +*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere.* +*While new releases are posted here, the latest source code is only available over Reticulum.* To understand the foundational philosophy and goals of this system, read the [Zen of Reticulum](Zen%20of%20Reticulum.md). From 1dd47f53cc41e1d6d6def0291f7db2a84902fe04 Mon Sep 17 00:00:00 2001 From: markqvist Date: Tue, 21 Jul 2026 23:28:15 +0200 Subject: [PATCH 264/271] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a4cfca0..1af833f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ Sideband ========= -*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere.* -*While new releases are posted here, the latest source code is only available over Reticulum.* +*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere. While new releases are posted here, the latest source code is only available over Reticulum itself.* To understand the foundational philosophy and goals of this system, read the [Zen of Reticulum](Zen%20of%20Reticulum.md). From 7db7c067d50b0de05e3bcda7a05f409f11dd155c Mon Sep 17 00:00:00 2001 From: markqvist Date: Sat, 26 Sep 2026 22:04:36 +0200 Subject: [PATCH 267/271] Update README.md --- README.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1af833f..18aba11 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,24 @@ Sideband ========= -*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere. While new releases are posted here, the latest source code is only available over Reticulum itself.* +> [!WARNING] +> Several hastily launched, incorrect, and in most cases entirely LLM-generated fakes of Sideband and associated tools are currently being circulated and marketed. Most of these "projects" violate the license that Sideband was published under, but claim independent ownership and license grants. +> +> Such claims or grants are **not legally valid**, and **not** recognized by the Sideband author and copyright holder. +> +> Any claimed assertion of copyright or grant of license that such projects are making are [void grants](https://reticulum.network/manual/brandolinis.html#void-grants-legal-foundations-of-machine-generated-code). +> +> Both the violators themselves, and **all** downstream projects using the infringing derivatives, are **directly** and **personally** liable for the legal consequences. +> +> For more detailed information, see the relevant sections of the [Brandolini's Reference](https://reticulum.network/manual/brandolinis.html) chapter of the Reticulum Manual. For software and projects recognized by the Reticulum community, see the [Programs Using Reticulum](https://reticulum.network/manual/software.html) chapter. +> +> Do **not** use these "projects", they are a hazard to the entire ecosystem we have been carefully building over the last ten years. + +*Due to the blatant copyright infringement, LLM-laundering and disrespect for open-source developers, the source code in this repository is no longer updated. All development is happening over Reticulum, where the latest source is always available.* + +*Packages and updates continue to ship on PyPI and over `rngit`. Compiled APKs, AppImages, wheels and portable exe bundles will continue to be published here as well.* + +--- To understand the foundational philosophy and goals of this system, read the [Zen of Reticulum](Zen%20of%20Reticulum.md). From ccf1b082080f175324c63581579083ac81362297 Mon Sep 17 00:00:00 2001 From: markqvist Date: Sun, 27 Sep 2026 11:32:57 +0200 Subject: [PATCH 268/271] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 18aba11..d9ff57c 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ Sideband