diff --git a/.github/ISSUE_TEMPLATE/ЁЯРЫ-bug-report.md b/.github/ISSUE_TEMPLATE/ЁЯРЫ-bug-report.md index 77ad6c2..82a4968 100644 --- a/.github/ISSUE_TEMPLATE/ЁЯРЫ-bug-report.md +++ b/.github/ISSUE_TEMPLATE/ЁЯРЫ-bug-report.md @@ -12,10 +12,14 @@ 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** -A clear and concise description of what the bug is. +First of all: Is this really a bug? Is it reproducible? + +If this is a request for help because something is not working as you expected, stop right here, and go to the [discussions](https://github.com/markqvist/Reticulum/discussions) instead, where you can post your questions and get help from other users. + +If this really is a bug or issue with the software, remove this section of the template, and provide **a clear and concise description of what the bug is**. **To Reproduce** Describe in detail how to reproduce the bug. @@ -24,7 +28,7 @@ Describe in detail how to reproduce the bug. A clear and concise description of what you expected to happen. **Logs & Screenshots** -Please include any relevant log output. If applicable, also add screenshots to help explain your problem. +Please include any relevant log output. If applicable, also add screenshots to help explain your problem. In most cases, without any relevant log output, we will not be able to determine the cause of the bug, or reproduce it. **System Information** - OS and version diff --git a/.gitignore b/.gitignore index d7d285d..69ecdf7 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 @@ -32,3 +33,7 @@ dist docs/build sideband*.egg-info sbapp*.egg-info +LXST +environment +archived_build_tools +.gradle diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a895acc..38372f7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,31 +1,67 @@ -# Contribution Guidelines +# Contributing to Reticulum -Welcome, and thank you for your interest in contributing to this project! +Welcome, and thank you for your interest in contributing to Reticulum! -Apart from writing code, there are many ways in which you can contribute. Before interacting with this community, read these short and simple guidelines. +Before interacting with this community, read these short and simple guidelines. + +If you didn't shit your pants after reading this document, you may well find that we are all really quite cuddly and nice to be around. Mostly. ## Expected Conduct -First and foremost, there is one simple requirement for taking part in this community: While we primarily interact virtually, your actions matter and have real consequences. Therefore: **Act like a responsible, civilized person** - also in the face of disputes and heated disagreements. Speak your mind here, discussions are welcome. Just do so in the spirit of being face-to-face with everyone else. Thank you. +First and foremost, there is one simple requirement for taking part in the development of this technology: While we primarily interact virtually, your actions matter and have real consequences. Therefore: **Act like a responsible, civilized person** - especially in the face of disputes and heated disagreements. Speak your mind here; discussions are welcome. Just do so in the spirit of being face-to-face with everyone else. Thank you. -## Asking Questions +In order to keep the discourse navigable and useful, the following types of posts and inquiries will be deleted and ignored: -If you want to ask a question, **do not open an issue**. The issue tracker is used by people *working on Sideband* to track bugs, issues and improvements. +- Spam. +- Questions that have already been adequately answered elsewhere. Utilize search functions. +- Low-effort posts or comments that contain no actual information or useful substance. [This is not a tea-house](./This%20Is%20Not%20a%20Teahouse.md). +- Post or comments solely containing personal opinions or beliefs without adding anything to the discussion. Facebook and X exists. +- Content that simply waste the developer's / maintainer's time with completely obvious "ideas", "insights" or "recommendations". Yes, we have *at least* 8 neurons ourselves. +- Posts that fail to understand that developing a highly complex software project with a very small amount of resources and people takes time. Imagining perfection on our behalf is useless. -Instead, ask away on the [discussions](https://github.com/markqvist/Reticulum/discussions) or on the [Reticulum Matrix channel](https://matrix.to/#/#reticulum:matrix.org) at `#reticulum:matrix.org` +If you're new to the community and start out your engagement with any of the above transgressions, you will simply be banned permanently without notice or explanation, and any further communication from you will be ignored. -## Providing Feedback & Ideas +Except for the case of real, well-grounded, clearly documented, human-written security advisories, technical investigations or bug reports, if your inquiry or communication is not attached to a Reticulum Identity, expect it to be ignored. -Likewise, feedback, ideas and feature requests are a very welcome way to contribute, and should also be posted on the [discussions](https://github.com/markqvist/Reticulum/discussions), or on the [Reticulum Matrix channel](https://matrix.to/#/#reticulum:matrix.org) at `#reticulum:matrix.org`. +If you find this "harsh", "unfair" or "unwelcoming", go somewhere else. This is not social club, but a work environment for the people contributing to the project. -Please do not post feature requests or general ideas on the issue tracker, or in direct messages to the primary developers. You are much more likely to get a response and start a constructive discussion by posting your ideas in the public channels created for these purposes. +## Reporting Bugs -## Reporting Issues - -If you have found a bug or issue in this project, please report it using the issue tracker. If at all possible, be sure to include details on how to reproduce the bug. - -Anything submitted to the issue tracker that does not follow these guidelines will be closed and removed without comments or explanation. +If you have found a bug or issue in this project, please report it to the maintainer over LXMF, or if strictly not possible, over email. Detailed and serious bug reports can also be posted in the various on-network forums and RRC channels that the developers frequent. Due to the realities described in [This Is Not a Teahouse](./This%20Is%20Not%20a%20Teahouse.md), there is no way to report issues or request features over the internet. ## Writing Code -If you are interested in contributing code, fixing open issues or adding features, please coordinate the effort with the maintainer or one of the main developers first, to ensure your efforts are in alignment with the [Roadmap](./Roadmap.md) and current development focus. +Patches and code contributions are *generally* only welcomed from developers already known to the community, with a proven track-record of competence, skill, careful and considerate design and responsible conduct. If we do not know you yet, but you have created something that you believe lives up to such standards, we are eager to hear from you. + +Current development priorities and work documents are not publicly available on the internet, but shared and coordinated directly between the developers over Reticulum itself, following the principles outlined in [Distributed Development](https://reticulum.network/manual/distributed.html). + +## Commit Signing + +All commits in Reticulum and related projects **must** be signed with a Reticulum identity. If you want your author credentials to be included directly in the commit log, ensure that you have [configured commit signing](https://reticulum.network/manual/git.html#commit-signing). Bare patches submitted manually or fetched remote commits without signatures are still very welcome, but we will review, squash merge and sign with the key of the maintainer that approved the changes. Attribution will be provided in the commit message instead (unless you wish to remain anonymous). + +## Machine Assistance & LLMs + +For a highly complex, critical piece of cryptographically based networking infrastructure, we should not need to state the following, but alas, experience has proven otherwise. Therefore: + +**Including material generated using LLMs or other "AI" programs in Reticulum is, almost without exception, prohibited.** + +Before even *thinking* about using a generative software system to "create" something for Reticulum, read [Brandolini's Reference](https://reticulum.network/manual/brandolinis.html), in full. If you do not have the capacity for that, you have failed the first requirement for contributing: Basic literacy. + +*If* you are not already a known contributor with a proven record of being able to responsibly handle these tools, a **full** audit trail of all ML-utilizing workflows, including prompts, LLM reasoning traces, tool calls and outputs (that is, the *entire*, unaltered session log) will need to be provided with any proposed contribution. Without that, we will not even *consider* looking at it. + +This applies to all Reticulum-related projects and documentation, as well as all submitted issues, reports and discussion, **except** of course in cases where language translation, speech recogntion, or other assistive technologies are required. + +In **all** circumstances, clear disclosure is **mandatory**. Any piece of material, file, code snippet, method, function or similar that was generated with machine assistance must be prepended with a disclosure header or comment that states the framework, exact model used and reviewer, such as: + +```python +# Generated with lc/deepseek_v4_flash_q8_k_xl +# Reviewed and corrected by Mark Qvist +``` + +Additionally, any explanatory comments or doc-strings generated by software must be manually re-written in clear, concise language by the reviewer stated in the disclosure header. + +## Contributor License Agreement + +By contributing code to this project, you agree that copyright for the code is transferred to the Reticulum maintainers and that the code is irrevocably placed under the [Reticulum License](./LICENSE). + +For a more in-depth elaboration on the current CLA position, see [this post](https://rns.recipes/forum/general/brandolinis-reference-or-alternatively-agentsmd?page=1#post-3002). 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" diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..d436adb --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +prune sbapp/patches +prune sbapp/dist +prune recipes +prune docs +prune libs +prune .github \ No newline at end of file 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/Makefile b/Makefile index 5b8cd31..c012aa7 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,5 @@ +include environment + devapk: make -C sbapp devapk @@ -24,12 +26,65 @@ 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 -build_wheel: - python3 setup.py sdist bdist_wheel +compile_wheel: + python3 setup.py bdist_wheel + +compile_sourcepkg: + python3 setup.py sdist + +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 + rm build/winpkg/sbapp/Makefile + 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 + +build_winexe: prepare_win_pkg + cp dist/winbuild.zip $(WINDOWS_BUILD_TARGET) release: build_wheel apk fetchapk @@ -37,4 +92,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/README.md b/README.md index 3cce901..d9ff57c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,30 @@ 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. +> [!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). + +For an Android-specific quickstart guide for new users, see the community-provided [Sideband Quick-start by RNS Moscow](https://docs.rns.moscow/sideband-quickstart/). + +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) @@ -9,84 +32,352 @@ Sideband is completely free, end-to-end encrypted, permission-less, anonymous an 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. Please read the Guide section included in the program, to get an understanding of how Sideband differs from other messaging systems. +# Functionality & Features + Sideband provides many useful and interesting functions, such as: -- Secure and self-sovereign messaging using the LXMF protocol over Reticulum. -- Image and file transfers over all supported mediums. -- Secure and direct P2P telemetry and location sharing. No third parties or servers ever have your data. -- Situation display on both online and locally stored offline maps. +- **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](#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. -- Using Android devices as impromptu Reticulum routers (*Transport Instances*), for setting up or extending networks easily. -- Remote command execution and response engine, with built-in commands, such as `ping`, `signal` reports and `echo`. -- 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. +- Exchanging messages through **encrypted QR-codes on paper**, or through messages embedded directly in **lxm://** links. +- Using **Android devices as impromptu Reticulum routers** (*Transport Instances*), for setting up or extending networks easily. +- Remote **command execution and response engine**, with built-in commands, such as `ping`, `signal` reports and `echo`, and **full plugin expandability**. +- 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 [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. -Sideband works well with the terminal-based LXMF client [Nomad Network](https://github.com/markqvist/nomadnet), which allows you to easily host Propagation Nodes for your LXMF network, and more. +# Installation -## Installation On Linux, Android and MacOS +Sideband can run on most computing devices, but installation methods vary by device type and operating system. For installation instructions, please find the relevant section below. -For your Android devices, you can install Sideband through F-Droid, by adding the [Between the Borders Archive Repo](https://reticulum.betweentheborders.com/fdroid/repo/), or you can download an [APK on the latest release](https://github.com/markqvist/Sideband/releases/latest) page. Both sources are signed with the same release keys, and can be used interchangably. +- [Android](#on-android) +- [Linux](#on-linux) +- [Raspberry Pi](#on-raspberry-pi) +- [MacOS](#on-macos) +- [Windows](#on-windows) -A DMG file containing a macOS app bundle is also available on the [latest release](https://github.com/markqvist/Sideband/releases/latest) page. +## On Android -Aditionally, you can install Sideband with ``pip`` on Linux and macOS: +For your Android devices, you can download an [APK on the latest release page](https://github.com/markqvist/Sideband/releases/latest). -```bash -# Install Sideband and dependencies on Linux -pip install sbapp +After the application is installed on your Android device, it is also possible to pull updates directly through the **Repository** section of the application. -# Install Sideband and dependencies on macOS -pip install "sbapp[macos]" - -# Run it -sideband - -``` - -If you are using an operating system that blocks normal user package installation via `pip`, you can return `pip` to normal behaviour by editing the `~/.config/pip/pip.conf` file, and adding the following directive in the `[global]` section: +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 -[global] -break-system-packages = true +SHA-256 digest: 1c65f01f586a2b73ac4eb8bf48730b3899d046447185fd9d005685a4af20cdea +SHA-1 digest: 4ab9269c320c72f4e4057ec7ea5acade320c2a48 +MD5 digest: 09afff8c505089a544ad2bf371c29422 ``` -Alternatively, you can use the `pipx` tool to install Sideband in an isolated environment instead: +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 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 other custom ROMs. + +## On Linux + +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. If any of those features do not work, make sure you have `opusfile`, and a clipboard manager like `xclip` or `wl-clipboard` installed: ```bash -# Install Sideband on Linux -pipx install sbapp +# For Debian 12+, Ubuntu 22.04+ and derivatives +sudo apt install libopusfile0 xclip xsel -# Install Sideband on macOS -pip install "sbapp[macos]" +# For Manjaro and derivatives +pamac install opusfile xclip xsel -# Optionally install Reticulum utilities -pipx install rns +# For Arch and derivatives +sudo pacman -Sy opusfile xclip xsel -# Optionally install standalone LXMF utilities -pipx install lxmf +# 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 ``` -## Installation On Windows +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). -It is possible to install and run Sideband on Windows, although some features are not fully functional. If you don't already have Python installed, [download and install](https://www.python.org/downloads/) the latest version of Python. +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. -**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 the `sideband` command. +#### Basic Installation +You will first need to install a few dependencies for voice calls, audio messaging and Codec2 support to work: -When Python has been installed, you can open a command prompt and install sideband via `pip`: +```bash +# For Debian 13+, Ubuntu 24.04+ and derivatives +sudo apt install python3-pip python3-pyaudio libopusfile0 codec2 xclip xsel + +# For Debian 12+, Ubuntu 22.04+ and derivatives +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 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: + +```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 +# 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 +# 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 +# to your launcher or apps menu. You may need to log out +# of your session, and back in for the application to +# show up in your launcher, depending on your distro. + +# You can also run Sideband in headless daemon +# mode, for example as a telemetry collector: +sideband --daemon + +# You can also run Sideband with more verbose +# log output enabled: +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 +# Install Sideband via pipx instead of pip: +pipx install sbapp + +# Or, if you intend to run Sideband in headless +# 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 +# will still need to manually install the RNS +# 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 + +# On Debian 11, run Sideband manually via the +# terminal once to install desktop integration: +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`. + +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. + +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 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 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: +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 + +To install Sideband on macOS, you have two options available: + +1. An easy to install pre-built disk image package +2. A source package install for more advanced setups + +#### Prebuilt Executable + +You can download a disk image with Sideband for macOS (ARM and Intel) from the [latest release page](https://github.com/markqvist/Sideband/releases/latest). Simply mount the downloaded disk image, drag `Sideband` to your applications folder, and run it. + +**Please note!** If you have application install restrictions enabled on your macOS install, or have restricted your system to only allow installation of application from the Apple App Store, you will need to create an exception for Sideband. The Sideband application will *never* be distributed with an Apple-controlled digital signature, as this will allow Apple to simply disable Sideband from running on your system if they decide to do so, or are forced to by authorities or other circumstances. + +If you install Sideband from the DMG file, it is still recommended to install the `rns` package via the `pip` or `pipx` package manager, so you can use the RNS utility programs, like `rnstatus` to see interface and connectivity status from the terminal. If you already have Python and `pip` installed on your system, simply open a terminal window and use one of the following commands: + +```bash +# Install Reticulum and utilities with pip: +pip3 install rns --user + +# On some versions, you may need to use the +# flag --break-system-packages to install: +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. + +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. + +To install Sideband via `pip`, follow these instructions: + +```bash +# Install Sideband and dependencies on macOS using pip: +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 +# or +python3 -m sbapp.main + +# Enable debug logging: +################################# +sideband -v +# or +python3 -m sbapp.main -v + +# Start Sideband in daemon mode: +################################# +sideband -d +# or +python3 -m sbapp.main -d + +# If Python and pip was installed correctly, +# you can simply use the "sideband" command +# directly. Otherwise, you will manually +# need to add the pip binaries directory to +# your PATH environment variable, or start +# Sideband via the "python3 -m sbapp.main" +# syntax. + +``` + +## On Windows + +To install Sideband on Windows, you have two options available: + +1. An easy to install pre-built executable package +2. A source package install for more advanced setups + +#### Prebuilt Executable + +Simply download the packaged Windows ZIP file from the [latest release page](https://github.com/markqvist/Sideband/releases/latest), unzip the file, and run `Sideband.exe` from the unzipped directory. You can create desktop or start menu shortcuts from this executable if needed. + +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`: + +```bash +pip install rns +``` + +#### 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. + +In this case, you will need to [download and install the latest supported version of Python](https://www.python.org/downloads/release/python-3127/) (currently Python 3.12.7), since very latest Python release, Python 3.13 is currently **not** compatible with the Kivy framework, that Sideband uses to render its user interface. The binary package already includes a compatible Python version, so if you are running Sideband from that, there is no need to install a specific version of Python. + +When Python has been installed, you can open a command prompt and install Sideband via `pip`: ```bash pip install sbapp ``` -The Sideband application can now be launched by running the command `sideband` in the command prompt. +The Sideband application can now be launched by running the command `sideband` in the command prompt. If needed, you can create a shortcut for Sideband on your desktop or in the start menu. -**Most importantly**, the `AutoInterface` in Reticulum is not yet supported on Windows. This means that on the first run, Sideband will not be able to automatically find any peers or potential Reticulum Transport Nodes you have on your local network. +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. -When running Sideband for the first time, a default Reticulum configuration file will be created, if you don't already have one. You will have to edit this 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). +# Creating Plugins -## Example Paper Message +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) 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. + +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: @@ -102,46 +393,29 @@ You can also find the entire message in `. 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 diff --git a/docs/example_plugins/basic.py b/docs/example_plugins/basic.py index 03f0fc9..b80af0c 100644 --- a/docs/example_plugins/basic.py +++ b/docs/example_plugins/basic.py @@ -1,3 +1,7 @@ +# This is a bare-minimum command plugin +# example that you can build upon to +# implement your own command plugins. + import RNS class BasicCommandPlugin(SidebandCommandPlugin): 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 diff --git a/docs/example_plugins/comic.py b/docs/example_plugins/comic.py index f475ffa..3e5a3f4 100644 --- a/docs/example_plugins/comic.py +++ b/docs/example_plugins/comic.py @@ -1,3 +1,7 @@ +# This plugin example fetches an XKCD comic +# from an external URL and returns it as an +# embedded image in an LXMF message. + import io import RNS import requests diff --git a/docs/example_plugins/gpsd_location.py b/docs/example_plugins/gpsd_location.py index 33bb60d..06d47cd 100644 --- a/docs/example_plugins/gpsd_location.py +++ b/docs/example_plugins/gpsd_location.py @@ -1,10 +1,14 @@ -import RNS -import time -import threading +# This plugin allows using GPSd as a location +# telemetry provider on Linux systems. # This plugin requires the "gpsdclient" pip # package to be installed on your system. # Install it with: pip install gpsdclient + +import RNS +import time +import threading + from gpsdclient import GPSDClient class GpsdLocationPlugin(SidebandTelemetryPlugin): @@ -50,19 +54,28 @@ class GpsdLocationPlugin(SidebandTelemetryPlugin): RNS.log("Connected, streaming GPSd data", RNS.LOG_DEBUG) self.client_connected = True - self.last_update = time.time() - self.latitude = result.get("lat", None) - self.longitude = result.get("lon", None) - self.altitude = result.get("altHAE", None) - self.speed = result.get("speed", None) - self.bearing = result.get("track", None) - epx = result.get("epx", None); epy = result.get("epy", None) - epv = result.get("epv", None) - if epx != None and epy != None and epv != None: - self.accuracy = max(epx, epy, epv) - else: - self.accuracy = None + gpsd_latitude = result.get("lat", None) + gpsd_longitude = result.get("lon", None) + gpsd_altitude = result.get("altHAE", None) + gpsd_speed = result.get("speed", None) + gpsd_bearing = result.get("track", None) + gpsd_required = [gpsd_latitude, gpsd_longitude, gpsd_altitude, gpsd_speed, gpsd_bearing] + + if not None in gpsd_required: + self.last_update = time.time() + self.latitude = gpsd_latitude + self.longitude = gpsd_longitude + self.altitude = gpsd_altitude + self.speed = gpsd_speed*3.6 # Convert from m/s to km/h + self.bearing = gpsd_bearing + + epx = result.get("epx", None); epy = result.get("epy", None) + epv = result.get("epv", None) + if epx != None and epy != None and epv != None: + self.accuracy = max(epx, epy, epv) + else: + self.accuracy = None except Exception as e: RNS.log("Could not connect to local GPSd, retrying later", RNS.LOG_ERROR) 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/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 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 diff --git a/docs/example_plugins/service.py b/docs/example_plugins/service.py index e9c4250..085c265 100644 --- a/docs/example_plugins/service.py +++ b/docs/example_plugins/service.py @@ -1,3 +1,7 @@ +# This is a bare-minimum service plugin +# example that you can build upon to +# implement your own service plugins. + import RNS import time import threading diff --git a/docs/example_plugins/telemetry.py b/docs/example_plugins/telemetry.py index 97f90db..fc4f618 100644 --- a/docs/example_plugins/telemetry.py +++ b/docs/example_plugins/telemetry.py @@ -1,3 +1,7 @@ +# This is a basic telemetry plugin +# example that you can build upon to +# implement your own telemetry plugins. + import RNS class BasicTelemetryPlugin(SidebandTelemetryPlugin): @@ -19,16 +23,45 @@ class BasicTelemetryPlugin(SidebandTelemetryPlugin): def update_telemetry(self, telemeter): if telemeter != None: - RNS.log("Updating power sensors") + # Create power consumption sensors telemeter.synthesize("power_consumption") telemeter.sensors["power_consumption"].update_consumer(2163.15, type_label="Heater consumption") telemeter.sensors["power_consumption"].update_consumer(12.7/1e6, type_label="Receiver consumption") - telemeter.sensors["power_consumption"].update_consumer(0.055, type_label="LED consumption") + telemeter.sensors["power_consumption"].update_consumer(0.055, type_label="LED consumption", custom_icon="led-on") telemeter.sensors["power_consumption"].update_consumer(982.22*1e9, type_label="Smelter consumption") + # Create power production sensor telemeter.synthesize("power_production") - telemeter.sensors["power_production"].update_producer(5732.15, type_label="Solar production") + telemeter.sensors["power_production"].update_producer(5732.15, type_label="Solar production", custom_icon="solar-power-variant") + + # Create storage sensor + telemeter.synthesize("nvm") + telemeter.sensors["nvm"].update_entry(capacity=256e9, used=38.48e9, type_label="SSD") + + # Create RAM sensors + telemeter.synthesize("ram") + telemeter.sensors["ram"].update_entry(capacity=8e9, used=3.48e9, type_label="RAM") + telemeter.sensors["ram"].update_entry(capacity=16e9, used=0.72e9, type_label="Swap") + + # Create CPU sensor + telemeter.synthesize("processor") + telemeter.sensors["processor"].update_entry(current_load=0.42, clock=2.45e9, load_avgs=[0.27, 0.43, 0.49], type_label="CPU") + + # Create custom sensor + telemeter.synthesize("custom") + telemeter.sensors["custom"].update_entry("311 seconds", type_label="Specific impulse is", custom_icon="rocket-launch") + telemeter.sensors["custom"].update_entry("a lie", type_label="The cake is", custom_icon="cake-variant") + + # Create tank sensors + telemeter.synthesize("tank") + telemeter.sensors["tank"].update_entry(capacity=1500, level=728, type_label="Fresh water", custom_icon="cup-water") + telemeter.sensors["tank"].update_entry(capacity=2000, level=122, unit="L", type_label="Waste tank") + + # Create fuel sensor + telemeter.synthesize("fuel") + 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. -plugin_class = BasicTelemetryPlugin \ No newline at end of file +plugin_class = BasicTelemetryPlugin diff --git a/docs/example_plugins/view.py b/docs/example_plugins/view.py index f8e357c..5146ade 100644 --- a/docs/example_plugins/view.py +++ b/docs/example_plugins/view.py @@ -1,5 +1,7 @@ # This plugin lets you remotely query and view a -# number of different image sources in Sideband. +# number of different image sources in Sideband, +# including remote or local webcams, video sources +# or images stored in a filesystem. # # This plugin requires the "pillow" pip package. # @@ -308,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) 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 diff --git a/docs/utilities/pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl b/docs/utilities/pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl new file mode 100644 index 0000000..9d19846 Binary files /dev/null and b/docs/utilities/pycodec2-3.0.1-cp311-cp311-linux_aarch64.whl differ 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/sbapp/plyer/platforms/ios/__init__.py b/libs/able/able/android/__init__.py similarity index 100% rename from sbapp/plyer/platforms/ios/__init__.py rename to libs/able/able/android/__init__.py 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/sbapp/plyer/tests/__init__.py b/libs/able/recipes/__init__.py similarity index 100% rename from sbapp/plyer/tests/__init__.py rename to libs/able/recipes/__init__.py 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) diff --git a/libs/arm64/libcodec2.so b/libs/arm64/libcodec2.so new file mode 100755 index 0000000..b8481a5 Binary files /dev/null and b/libs/arm64/libcodec2.so differ diff --git a/libs/armeabi/libcodec2.so b/libs/armeabi/libcodec2.so new file mode 100755 index 0000000..e76ad7f Binary files /dev/null and b/libs/armeabi/libcodec2.so differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..8518858 --- /dev/null +++ b/main.py @@ -0,0 +1 @@ +import sbapp.main \ No newline at end of file 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 new file mode 100644 index 0000000..f8712df --- /dev/null +++ b/recipes/codec2/__init__.py @@ -0,0 +1,51 @@ +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 + +class Codec2Recipe(Recipe): + url = "https://github.com/markqvist/codec2/archive/00e01c9d72d3b1607e165c71c4c9c942d277dfac.tar.gz" + built_libraries = {'libcodec2.so': 'build_android/src'} + + def include_flags(self, arch): + '''Returns a string with the include folders''' + codec2_includes = join(self.get_build_dir(arch.arch), 'build_android') + return (' -I' + codec2_includes) + + def link_dirs_flags(self, arch): + '''Returns a string with the appropriate `-L` to link + with the libs. This string is usually added to the environment + variable `LDFLAGS`''' + return ' -L' + self.get_build_dir(arch.arch) + + # def link_libs_flags(self): + # '''Returns a string with the appropriate `-l` flags to link with + # the libs. This string is usually added to the environment + # variable `LIBS`''' + # return ' -lcodec2{version} -lssl{version}'.format(version=self.version) + + def build_arch(self, arch): + with current_directory(self.get_build_dir(arch.arch)): + env = self.get_recipe_env(arch) + flags = [ + "..", + "--log-level=TRACE", + "--fresh", + "-DCMAKE_BUILD_TYPE=Release", + ] + + mkdir = sh.mkdir("-p", "build_android") + # cd = sh.cd("build_android") + os.chdir("build_android") + cmake = sh.Command('cmake') + + shprint(cmake, *flags, _env=env) + shprint(sh.make, _env=env) + sh.cp("../src/codec2.h", "./codec2/") + + +recipe = Codec2Recipe() diff --git a/recipes/codec2/generate_codebook b/recipes/codec2/generate_codebook new file mode 100755 index 0000000..b4ed668 Binary files /dev/null and b/recipes/codec2/generate_codebook differ 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/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/libopus/__init__.py b/recipes/libopus/__init__.py new file mode 100644 index 0000000..1eb4977 --- /dev/null +++ b/recipes/libopus/__init__.py @@ -0,0 +1,22 @@ +from pythonforandroid.recipe import Recipe +from pythonforandroid.toolchain import current_directory, shprint +import sh + + +class OpusRecipe(Recipe): + version = '1.5.2' + url = "https://downloads.xiph.org/releases/opus/opus-{version}.tar.gz" + built_libraries = {'libopus.so': '.libs'} + + def build_arch(self, arch): + with current_directory(self.get_build_dir(arch.arch)): + env = self.get_recipe_env(arch) + flags = [ + '--host=' + arch.command_prefix, + ] + configure = sh.Command('./configure') + shprint(configure, *flags, _env=env) + shprint(sh.make, _env=env) + + +recipe = OpusRecipe() 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/recipes/opusfile/__init__.py b/recipes/opusfile/__init__.py new file mode 100644 index 0000000..27d0f29 --- /dev/null +++ b/recipes/opusfile/__init__.py @@ -0,0 +1,46 @@ +from pythonforandroid.recipe import Recipe +from pythonforandroid.toolchain import current_directory, shprint +import sh +import os +import time + + +class OpusFileRecipe(Recipe): + version = "0.12" + url = "https://downloads.xiph.org/releases/opus/opusfile-{version}.tar.gz" + depends = ['libogg'] + built_libraries = {'libopusfile.so': '.libs'} + + def build_arch(self, arch): + with current_directory(self.get_build_dir(arch.arch)): + env = self.get_recipe_env(arch) + flags = [ + "--host=" + arch.command_prefix, + "--disable-http", + "--disable-examples", + "--disable-doc", + "--disable-largefile", + ] + + cwd = os.getcwd() + ogg_include_path = cwd.replace("opusfile", "libogg") + env["CPPFLAGS"] += f" -I{ogg_include_path}/include" + + # libogg_recipe = Recipe.get_recipe('libogg', self.ctx) + # env['CFLAGS'] += libogg_recipe.include_flags(arch) + + # openssl_recipe = Recipe.get_recipe('openssl', self.ctx) + # env['CFLAGS'] += openssl_recipe.include_flags(arch) + # env['LDFLAGS'] += openssl_recipe.link_dirs_flags(arch) + # env['LIBS'] = openssl_recipe.link_libs_flags() + + from rich.pretty import pprint + pprint(env) + time.sleep(5) + + configure = sh.Command('./configure') + shprint(configure, *flags, _env=env) + shprint(sh.make, _env=env) + + +recipe = OpusFileRecipe() diff --git a/recipes/pycodec2/__init__.py b/recipes/pycodec2/__init__.py new file mode 100644 index 0000000..5b71a80 --- /dev/null +++ b/recipes/pycodec2/__init__.py @@ -0,0 +1,57 @@ +from pythonforandroid.recipe import CythonRecipe, IncludedFilesBehaviour +from pythonforandroid.toolchain import current_directory, shprint +from os.path import join +import sh + +# class PyCodec2Recipe(IncludedFilesBehaviour, CythonRecipe): +class PyCodec2Recipe(CythonRecipe): + url = "https://github.com/markqvist/pycodec2/archive/438ee4f2f3ee30635a34caddf520cfaccdbbc646.zip" + # src_filename = "../../../pycodec2" + depends = ["setuptools", "numpy", "Cython", "codec2"] + call_hostpython_via_targetpython = False + + def get_recipe_env(self, arch, with_flags_in_cc=True): + """ + Adds codec2 recipe to include and library path. + """ + env = super().get_recipe_env(arch, with_flags_in_cc) + + codec2_recipe = self.get_recipe('codec2', self.ctx) + env['CFLAGS'] += codec2_recipe.include_flags(arch) +" -l:libcodec2.so" + env['LDFLAGS'] += ' -L{}'.format(self.ctx.get_libs_dir(arch.arch)) + env['LDFLAGS'] += ' -L{}'.format(self.ctx.libs_dir) + env['LDFLAGS'] += codec2_recipe.link_dirs_flags(arch) + + return env + + def build_arch(self, arch): + super().build_arch(arch) + with current_directory(self.get_build_dir(arch.arch)): + pass + # print(arch.arch) + # print(arch) + # shprint(sh.Command("pwd")) + # shprint(sh.Command("ls")) + + # pe_args = ["--replace-needed", "libcodec2.so.1.2", "libcodec2.so", "build/lib.linux-x86_64-3.11/pycodec2/pycodec2.cpython-311-x86_64-linux-gnu.so"] + # shprint(sh.Command("patchelf"), *pe_args) + + # pe_args = ["--replace-needed", "libcodec2.so.1.2", "libcodec2.so", f"../../../../python-installs/sideband/{arch.arch}/pycodec2/pycodec2.cpython-311-x86_64-linux-gnu.so"] + # shprint(sh.Command("patchelf"), *pe_args) + + # ../../../../python-installs/sideband/armeabi-v7a/pycodec2/pycodec2.cpython-311-x86_64-linux-gnu.so + # sbapp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pycodec2/armeabi-v7a__ndk_target_24/pycodec2/build/lib.linux-x86_64-3.11/pycodec2/pycodec2.cpython-311-x86_64-linux-gnu.so + # sbapp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/sideband/armeabi-v7a/pycodec2/pycodec2.cpython-311-x86_64-linux-gnu.so + # print("=========================") + # input() + + + def postbuild_arch(self, arch): + super().postbuild_arch(arch) + +recipe = PyCodec2Recipe() + +# patchelf --replace-needed libcodec2.so.1.2 libcodec2.so sbapp/.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 sbapp/.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 sbapp/.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 sbapp/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/dists/sideband/_python_bundle__armeabi-v7a/_python_bundle/site-packages/pycodec2/pycodec2.so \ No newline at end of file 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 diff --git a/sbapp/Makefile b/sbapp/Makefile index 7341ef2..c5097d2 100644 --- a/sbapp/Makefile +++ b/sbapp/Makefile @@ -1,13 +1,13 @@ all: prepare debug -prepare: activate cleanrns getrns +prepare: cleanrns getrns clean: @echo Cleaning... -(rm ./__pycache__ -r) -(rm ./app_storage -r) -(rm ./share/pkg/* -r) - -(rm ./share/mirrors/* -r) + -(rm ./share/mirrors/* -rf) -(rm ./bin -r) cleanlibs: @@ -15,37 +15,48 @@ cleanlibs: cleanall: clean cleanlibs -activate: - (. venv/bin/activate) - -pacthfiles: patchsdl injectxml +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 + + # 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 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 +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 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...) @@ -58,44 +69,51 @@ 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/sbapp-*-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 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 + mkdir ./share/mirrors/rnode-flasher + cp ../../rnode-flasher/RNode_Flasher.html ./share/mirrors/rnode-flasher + -(rm ./share/mirrors/rnode-flasher/.git -rf) release: buildozer android 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)) 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") 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 -r ../../LXST/LXST ./) + -(rm ./LXST/Utilities/LXST) + -(rm ./LXST/__pycache__ -r) + -(rm ./LXST/Utilities/__pycache__ -r) cleanrns: -(rm ./RNS -r) -(rm ./LXMF -r) + -(rm ./LXST -r) diff --git a/sbapp/assets/audio/notifications/ringer.opus b/sbapp/assets/audio/notifications/ringer.opus new file mode 100644 index 0000000..36d0094 Binary files /dev/null and b/sbapp/assets/audio/notifications/ringer.opus differ diff --git a/sbapp/assets/audio/notifications/soft1.opus b/sbapp/assets/audio/notifications/soft1.opus new file mode 100644 index 0000000..6e3d792 Binary files /dev/null and b/sbapp/assets/audio/notifications/soft1.opus differ diff --git a/sbapp/assets/fonts/BigBlueTerm437NerdFont-Regular.ttf b/sbapp/assets/fonts/BigBlueTerm437NerdFont-Regular.ttf new file mode 100644 index 0000000..256563d Binary files /dev/null and b/sbapp/assets/fonts/BigBlueTerm437NerdFont-Regular.ttf differ diff --git a/sbapp/assets/fonts/DefaultInput.ttf b/sbapp/assets/fonts/DefaultInput.ttf new file mode 100644 index 0000000..6af80b7 Binary files /dev/null and b/sbapp/assets/fonts/DefaultInput.ttf differ diff --git a/sbapp/assets/fonts/EmojiScaled.ttf b/sbapp/assets/fonts/EmojiScaled.ttf new file mode 100644 index 0000000..7f4cb47 Binary files /dev/null and b/sbapp/assets/fonts/EmojiScaled.ttf differ diff --git a/sbapp/assets/fonts/NotoSans-Bold.ttf b/sbapp/assets/fonts/NotoSans-Bold.ttf index d84248e..1b9d109 100644 Binary files a/sbapp/assets/fonts/NotoSans-Bold.ttf and b/sbapp/assets/fonts/NotoSans-Bold.ttf differ diff --git a/sbapp/assets/fonts/NotoSans-BoldItalic.ttf b/sbapp/assets/fonts/NotoSans-BoldItalic.ttf index 3a34c4c..81ab4f6 100644 Binary files a/sbapp/assets/fonts/NotoSans-BoldItalic.ttf and b/sbapp/assets/fonts/NotoSans-BoldItalic.ttf differ diff --git a/sbapp/assets/fonts/NotoSans-Italic.ttf b/sbapp/assets/fonts/NotoSans-Italic.ttf index c40c356..d953762 100644 Binary files a/sbapp/assets/fonts/NotoSans-Italic.ttf and b/sbapp/assets/fonts/NotoSans-Italic.ttf differ diff --git a/sbapp/assets/fonts/NotoSans-Medium.ttf b/sbapp/assets/fonts/NotoSans-Medium.ttf index a799b74..9cfc357 100644 Binary files a/sbapp/assets/fonts/NotoSans-Medium.ttf and b/sbapp/assets/fonts/NotoSans-Medium.ttf differ diff --git a/sbapp/assets/fonts/NotoSans-Regular.ttf b/sbapp/assets/fonts/NotoSans-Regular.ttf index fa4cff5..6af80b7 100644 Binary files a/sbapp/assets/fonts/NotoSans-Regular.ttf and b/sbapp/assets/fonts/NotoSans-Regular.ttf differ diff --git a/sbapp/assets/fonts/NotoSansHebrew-Bold.ttf b/sbapp/assets/fonts/NotoSansHebrew-Bold.ttf index 04e5eb0..eb7b0d6 100644 Binary files a/sbapp/assets/fonts/NotoSansHebrew-Bold.ttf and b/sbapp/assets/fonts/NotoSansHebrew-Bold.ttf differ diff --git a/sbapp/assets/fonts/NotoSansHebrew-Medium.ttf b/sbapp/assets/fonts/NotoSansHebrew-Medium.ttf index a7a80a9..c21d600 100644 Binary files a/sbapp/assets/fonts/NotoSansHebrew-Medium.ttf and b/sbapp/assets/fonts/NotoSansHebrew-Medium.ttf differ diff --git a/sbapp/assets/fonts/NotoSansHebrew-Regular.ttf b/sbapp/assets/fonts/NotoSansHebrew-Regular.ttf index ca7a0fd..b353cb5 100644 Binary files a/sbapp/assets/fonts/NotoSansHebrew-Regular.ttf and b/sbapp/assets/fonts/NotoSansHebrew-Regular.ttf differ diff --git a/sbapp/assets/fonts/NotoSansJP-Regular.ttf b/sbapp/assets/fonts/NotoSansJP-Regular.ttf index 1583096..7c5dcac 100644 Binary files a/sbapp/assets/fonts/NotoSansJP-Regular.ttf and b/sbapp/assets/fonts/NotoSansJP-Regular.ttf differ diff --git a/sbapp/assets/fonts/NotoSansKR-Regular.ttf b/sbapp/assets/fonts/NotoSansKR-Regular.ttf index 1b14d32..9b4aa78 100644 Binary files a/sbapp/assets/fonts/NotoSansKR-Regular.ttf and b/sbapp/assets/fonts/NotoSansKR-Regular.ttf differ diff --git a/sbapp/assets/fonts/NotoSansSC-Regular.ttf b/sbapp/assets/fonts/NotoSansSC-Regular.ttf index 4d4cadb..91d4ad2 100644 Binary files a/sbapp/assets/fonts/NotoSansSC-Regular.ttf and b/sbapp/assets/fonts/NotoSansSC-Regular.ttf differ diff --git a/sbapp/assets/fonts/RobotoMonoNerdFont-Regular.ttf b/sbapp/assets/fonts/RobotoMonoNerdFont-Regular.ttf new file mode 100644 index 0000000..11b95d3 Binary files /dev/null and b/sbapp/assets/fonts/RobotoMonoNerdFont-Regular.ttf differ diff --git a/sbapp/assets/icon.ico b/sbapp/assets/icon.ico new file mode 100644 index 0000000..717bf73 Binary files /dev/null and b/sbapp/assets/icon.ico differ diff --git a/sbapp/assets/io.unsigned.sideband.desktop b/sbapp/assets/io.unsigned.sideband.desktop new file mode 100644 index 0000000..c2d8223 --- /dev/null +++ b/sbapp/assets/io.unsigned.sideband.desktop @@ -0,0 +1,21 @@ +# Entry version 20241128 +[Desktop Entry] +Comment[en_US]=Messaging, telemetry and remote control over LXMF +Comment=Messaging, telemetry and remote control over LXMF +Encoding=UTF-8 +Exec=sideband +GenericName[en_US]=LXMF client +GenericName=LXMF client +Icon=io.unsigned.sideband +Categories=Utility +MimeType= +Name[en_US]=Sideband +Name=Sideband +Path= +StartupNotify=true +Terminal=false +TerminalOptions= +Type=Application +Version=1.0 +X-KDE-SubstituteUID=false +X-KDE-Username= \ No newline at end of file diff --git a/sbapp/assets/io.unsigned.sideband.png b/sbapp/assets/io.unsigned.sideband.png new file mode 100644 index 0000000..f935d61 Binary files /dev/null and b/sbapp/assets/io.unsigned.sideband.png differ diff --git a/sbapp/buildozer.spec b/sbapp/buildozer.spec index 69531e9..83e9631 100644 --- a/sbapp/buildozer.spec +++ b/sbapp/buildozer.spec @@ -4,42 +4,49 @@ 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.exclude_patterns = app_storage/*,venv/*,Makefile,./Makefil*,requirements,precompiled/*,parked/*,./setup.py,Makef*,./Makefile,Makefile +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__/* version.regex = __version__ = ['"](.*)['"] version.filename = %(source.dir)s/main.py -android.numeric_version = 20240329 +android.numeric_version = 20251128 -# Cryptography recipe is currently broken, using RNS-internal crypto for now -requirements = kivy==2.3.0,libbz2,pillow==10.2.0,qrcode==7.3.1,usb4a,usbserial4a,libwebp +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 -p4a.local_recipes = ../Others/python-for-android/pythonforandroid/recipes +android.gradle_dependencies = com.android.support:support-compat:28.0.0 +#android.enable_androidx = True +#android.add_aars = patches/support-compat-28.0.0.aar + +p4a.local_recipes = ../recipes/ icon.filename = %(source.dir)s/assets/icon.png presplash.filename = %(source.dir)s/assets/presplash_small.png android.presplash_color = #00000000 -# TODO: Fix +# TODO: Fix inability to set "user" orientation from spec +# This is currently handled by patching the APK manifest orientation = portrait fullscreen = 0 -android.permissions = INTERNET,POST_NOTIFICATIONS,WAKE_LOCK,FOREGROUND_SERVICE,CHANGE_WIFI_MULTICAST_STATE,BLUETOOTH_CONNECT,ACCESS_NETWORK_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,MANAGE_EXTERNAL_STORAGE,ACCESS_BACKGROUND_LOCATION +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 = 30 +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 android.whitelist = lib-dynload/termios.so android.manifest.intent_filters = patches/intent-filter.xml -android.add_aars = patches/support-compat-28.0.0.aar + +# android.add_libs_armeabi_v7a = ../libs/armeabi/*.so* +# android.add_libs_arm64_v8a = ../libs/arm64/*.so* [buildozer] log_level = 2 diff --git a/sbapp/compat.py b/sbapp/compat.py new file mode 100644 index 0000000..b6e3624 --- /dev/null +++ b/sbapp/compat.py @@ -0,0 +1,52 @@ +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" + 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") + + 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() + 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() diff --git a/sbapp/freeze.py b/sbapp/freeze.py new file mode 100644 index 0000000..8a7c498 --- /dev/null +++ b/sbapp/freeze.py @@ -0,0 +1,98 @@ +import os +import re +import setuptools +import cx_Freeze +from pathlib import Path + +build_appimage = True + +def get_version() -> str: + version_file = os.path.join( + os.path.dirname(__file__), "main.py" + ) + + version_file_data = open(version_file, "rt", encoding="utf-8").read() + version_regex = r"(?<=^__version__ = ['\"])[^'\"]+(?=['\"]$)" + try: + version = re.findall(version_regex, version_file_data, re.M)[0] + return version + except IndexError: + raise ValueError(f"Unable to find version string in {version_file}.") + +def get_variant() -> str: + version_file = os.path.join( + os.path.dirname(__file__), "main.py" + ) + + version_file_data = open(version_file, "rt", encoding="utf-8").read() + version_regex = r"(?<=^__variant__ = ['\"])[^'\"]+(?=['\"]$)" + try: + version = re.findall(version_regex, version_file_data, re.M)[0] + return version + except IndexError: + return None + +__version__ = get_version() +__variant__ = get_variant() +variant_str = "" +if __variant__: + variant_str = " "+__variant__ + +def glob_paths(pattern): + out_files = [] + src_path = os.path.join(os.path.dirname(__file__), "kivymd") + + for root, dirs, files in os.walk(src_path): + for file in files: + if file.endswith(pattern): + filepath = os.path.join(str(Path(*Path(root).parts[1:])), file) + out_files.append(filepath.split(f"kivymd{os.sep}")[1]) + + return out_files + +package_data = { +"": [ + "assets/*", + "assets/fonts/*", + "assets/geoids/*", + "kivymd/fonts/*", + "kivymd/images/*", + "kivymd/*", + "mapview/icons/*", + *glob_paths(".kv") + ] +} + +print("Freezing Sideband "+__version__+" "+variant_str) + +if build_appimage: + global_excludes = [".buildozer", "build", "dist"] + # Dependencies are automatically detected, but they might need fine-tuning. + appimage_options = { + "target_name": "Sideband", + "target_version": __version__+" "+variant_str, + "include_files": [], + "excludes": [], + "packages": ["kivy"], + "zip_include_packages": [], + "bin_path_excludes": global_excludes, + } + + cx_Freeze.setup( + name="Sideband", + version=__version__, + author="Mark Qvist", + author_email="mark@unsigned.io", + url="https://unsigned.io/sideband", + executables=[ + cx_Freeze.Executable( + script="main.py", + base="console", + target_name="Sideband", + shortcut_name="Sideband", + icon="assets/icon.png", + copyright="Copyright (c) 2024 Mark Qvist", + ), + ], + options={"build_appimage": appimage_options}, + ) \ No newline at end of file diff --git a/sbapp/kivymd/images/folder.png b/sbapp/kivymd/images/folder.png index fe0ed5b..0e50084 100644 Binary files a/sbapp/kivymd/images/folder.png and b/sbapp/kivymd/images/folder.png differ diff --git a/sbapp/kivymd/images/folder_orange.png b/sbapp/kivymd/images/folder_orange.png new file mode 100644 index 0000000..fe0ed5b Binary files /dev/null and b/sbapp/kivymd/images/folder_orange.png differ 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 diff --git a/sbapp/kivymd/uix/dialog/dialog.py b/sbapp/kivymd/uix/dialog/dialog.py index 9f2db53..73a5675 100755 --- a/sbapp/kivymd/uix/dialog/dialog.py +++ b/sbapp/kivymd/uix/dialog/dialog.py @@ -413,7 +413,7 @@ class MDDialog(BaseDialog): and defaults to `[]`. """ - width_offset = NumericProperty(dp(48)) + width_offset = NumericProperty(dp(32)) """ Dialog offset from device width. @@ -601,7 +601,7 @@ class MDDialog(BaseDialog): self.width = min(dp(560), Window.width - self.width_offset) elif self.size_hint == [1, 1] and DEVICE_TYPE == "mobile": self.size_hint = (None, None) - self.width = min(dp(280), Window.width - self.width_offset) + self.width = min(dp(560), Window.width - self.width_offset) if not self.title: self._spacer_top = 0 @@ -634,7 +634,7 @@ class MDDialog(BaseDialog): self.width = max( self.height + self.width_offset, min( - dp(560) if DEVICE_TYPE != "mobile" else dp(280), + dp(560) if DEVICE_TYPE != "mobile" else dp(560), Window.width - self.width_offset, ), ) diff --git a/sbapp/kivymd/uix/filemanager/filemanager.py b/sbapp/kivymd/uix/filemanager/filemanager.py index 4073764..728c796 100755 --- a/sbapp/kivymd/uix/filemanager/filemanager.py +++ b/sbapp/kivymd/uix/filemanager/filemanager.py @@ -649,7 +649,8 @@ class MDFileManager(MDRelativeLayout): return dirs, files - except OSError: + except OSError as e: + print("Filemanager OSError: "+str(e)) return None, None def close(self) -> None: 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) diff --git a/sbapp/main.py b/sbapp/main.py index e936a15..f7e9032 100644 --- a/sbapp/main.py +++ b/sbapp/main.py @@ -1,13 +1,18 @@ __debug_build__ = False __disable_shaders__ = False -__version__ = "0.8.2" -__variant__ = "beta" +__version__ = "1.9.2" +__variant__ = "" import sys 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") +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__)) args = parser.parse_args() sys.argv = [sys.argv[0]] @@ -16,13 +21,250 @@ import RNS import LXMF import time import os +import re import pathlib import base64 import threading 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 + # 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() + 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 + except Exception as e: + RNS.log(f"Could not get display resolution: {e}", RNS.LOG_WARNING) + RNS.trace_exception(e) + return None, None + +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" + 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(): + import plyer + 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 = 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 = os.path.join(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) + + 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_NOTICE) + if os.path.isfile(ui_scale_path): + scale_factor = None + 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: + os.environ["KIVY_METRICS_DENSITY"] = str(scale_factor) + RNS.log("UI scaling factor set to "+str(os.environ["KIVY_METRICS_DENSITY"]), RNS.LOG_NOTICE) + elif scale_factor == 0.0: + RNS.log("Using default UI scaling factor", RNS.LOG_NOTICE) + + + 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: + 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) + +################################################### +# 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: +# 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 ########################## + +window_x_offset = 0 +window_y_offset = 0 + +if args.export_settings: + from .sideband.core import SidebandCore + sideband = SidebandCore( + None, + config_path=args.config, + is_client=False, + verbose=(args.verbose or __debug_build__), + is_daemon=True, + load_config_only=True, + ) + + sideband.version_str = "v"+__version__+" "+__variant__ + + import json + export = sideband.config.copy() + for k in export: + if isinstance(export[k], bytes): + export[k] = RNS.hexrep(export[k], delimit=False) + try: + export_path = os.path.expanduser(args.export_settings) + with open(export_path, "wb") as export_file: + export_file.write(json.dumps(export, indent=4).encode("utf-8")) + print(f"Application settings written to {export_path}") + exit(0) + + except Exception as e: + print(f"Could not write application settings to {export_path}. The contained exception was:\n{e}") + exit(1) + +elif args.import_settings: + from .sideband.core import SidebandCore + sideband = SidebandCore( + None, + config_path=args.config, + is_client=False, + verbose=(args.verbose or __debug_build__), + is_daemon=True, + load_config_only=True, + ) + + sideband.version_str = "v"+__version__+" "+__variant__ + + import json + addr_fields = ["lxmf_propagation_node", "last_lxmf_propagation_node", "nn_home_node", "telemetry_collector"] + try: + import_path = os.path.expanduser(args.import_settings) + imported = None + with open(import_path, "rb") as import_file: + json_data = import_file.read().decode("utf-8") + imported = json.loads(json_data) + for k in imported: + if k in addr_fields and imported[k] != None: + imported[k] = bytes.fromhex(imported[k]) + if len(imported[k]) != RNS.Reticulum.TRUNCATED_HASHLENGTH//8: + raise ValueError(f"Invalid hash length for {RNS.prettyhexrep(imported[k])}") + + if imported: + sideband.config = imported + sideband.save_configuration() + while sideband.saving_configuration: + time.sleep(0.1) + print(f"Application settings imported from {import_path}") + exit(0) + + except Exception as e: + print(f"Could not import application settings from {import_path}. The contained exception was:\n{e}") + exit(1) + if not args.daemon: - import plyer + 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 @@ -73,18 +315,108 @@ 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; mdconv = DaemonElement; else: + apply_ui_scale() + + if not RNS.vendor.platformutils.is_android(): + # 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 + + # 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: + # 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 + + # 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: + 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 + 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+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") + app_init_window_state = window_state + from kivymd.app import MDApp app_superclass = MDApp from kivy.core.window import Window from kivy.core.clipboard import Clipboard + from kivy.core.audio import SoundLoader from kivy.base import EventLoop from kivy.clock import Clock from kivy.lang.builder import Builder from kivy.effects.scroll import ScrollEffect from kivy.uix.screenmanager import ScreenManager from kivy.uix.screenmanager import FadeTransition, NoTransition, SlideTransition + from kivy.uix.boxlayout import BoxLayout from kivymd.uix.list import OneLineIconListItem, IconLeftWidget from kivy.properties import StringProperty from kivymd.uix.button import BaseButton, MDIconButton @@ -102,17 +434,24 @@ else: import kivy.core.image kivy.core.image.Logger = redirect_log() - if RNS.vendor.platformutils.get_platform() == "android": + if RNS.vendor.platformutils.is_android(): from sideband.core import SidebandCore + import plyer from ui.layouts import * from ui.conversations import Conversations, MsgSync, NewConv from ui.telemetry import Telemetry + from ui.utilities import Utilities + 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 + # from ui.messages_recycle import Messages, ts_format, messages_screen_kv from ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem - from ui.helpers import multilingual_markup + from ui.helpers import multilingual_markup, mdc, dark_theme_text_color from kivymd.toast import toast from jnius import cast @@ -121,30 +460,42 @@ else: from android.permissions import request_permissions, check_permission from android.storage import primary_external_storage_path, secondary_external_storage_path + 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 + from android.broadcast import BroadcastReceiver + BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter') + else: from .sideband.core import SidebandCore + import sbapp.plyer as plyer from .ui.layouts import * from .ui.conversations import Conversations, MsgSync, NewConv from .ui.announces import Announces from .ui.telemetry import Telemetry + from .ui.utilities import Utilities + 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.messages_recycle import Messages, ts_format, messages_screen_kv from .ui.helpers import ContentNavigationDrawer, DrawerList, IconListItem - from .ui.helpers import multilingual_markup + from .ui.helpers import multilingual_markup, mdc, dark_theme_text_color - class toast: - def __init__(self, *kwargs): - pass + import LXST.Codecs.libs.pyogg as pyogg + from LXST.Codecs.libs.pydub import AudioSegment + + from kivymd.toast import toast 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 @@ -182,10 +533,17 @@ class SidebandApp(MDApp): self.no_transition = NoTransition() self.slide_transition = SlideTransition() - if RNS.vendor.platformutils.get_platform() == "android": - self.sideband = SidebandCore(self, is_client=True, android_app_dir=self.app_dir, verbose=__debug_build__) + if args.config != None: + self.config_path = os.path.expanduser(args.config) else: - self.sideband = SidebandCore(self, is_client=False, verbose=(args.verbose or __debug_build__)) + self.config_path = None + + 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__),rns_config_path=args.rnsconfig) + + self.sideband.version_str = "v"+__version__+" "+__variant__ self.set_ui_theme() self.font_config() @@ -193,11 +551,14 @@ class SidebandApp(MDApp): self.dark_theme_text_color = dark_theme_text_color self.conversations_view = None + self.include_conversations = True + self.include_objects = False self.messages_view = None self.map = None 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 @@ -205,28 +566,46 @@ class SidebandApp(MDApp): self.sync_dialog = None 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 - 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 self.service_last_available = 0 + self.closing_app = False + self.file_manager = None self.attach_path = None self.attach_type = None + 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 + self.compat_error_dialog = None + self.rec_dialog_is_open = True + self.key_ptt_down = False Window.softinput_mode = "below_target" - self.icon = self.sideband.asset_dir+"/icon.png" - self.notification_icon = self.sideband.asset_dir+"/notification_icon.png" + self.window_state = app_init_window_state + 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 self.last_map_update = 0 self.last_telemetry_received = 0 - self.reposository_url = None + self.repository_url = None + self.rnode_flasher_url = None + self.bt_adapter = None + self.discovered_bt_devices = {} + self.bt_bonded_devices = [] ################################################# # Application Startup # @@ -280,6 +659,86 @@ 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 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() @@ -308,6 +767,20 @@ class SidebandApp(MDApp): else: self.open_conversations() + if RNS.vendor.platformutils.is_android(): + if self.sideband.getstate("android.power_restricted", allow_cache=False): + RNS.log("Android power restrictions detected, background connectivity will not work. Asking for permissions.", RNS.LOG_DEBUG) + def pm_job(dt): + Settings = autoclass("android.provider.Settings") + Intent = autoclass("android.content.Intent") + Uri = autoclass("android.net.Uri") + + requestIntent = Intent() + requestIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) + requestIntent.setData(Uri.parse("package:io.unsigned.sideband")) + mActivity.startActivity(requestIntent) + Clock.schedule_once(pm_job, 1.5) + if not self.root.ids.screen_manager.has_screen("messages_screen"): self.messages_screen = Builder.load_string(messages_screen_kv) self.messages_screen.app = self @@ -320,24 +793,30 @@ class SidebandApp(MDApp): def check_errors(dt): if self.sideband.getpersistent("startup.errors.rnode") != None: - description = self.sideband.getpersistent("startup.errors.rnode")["description"] - self.sideband.setpersistent("startup.errors.rnode", None) - yes_button = MDRectangleFlatButton( - text="OK", - font_size=dp(18), - ) - self.hw_error_dialog = MDDialog( - title="Hardware Error", - text="When starting a connected RNode, Reticulum reported the following error:\n\n[i]"+str(description)+"[/i]", - buttons=[ yes_button ], - # elevation=0, - ) - def dl_yes(s): - self.hw_error_dialog.dismiss() - yes_button.bind(on_release=dl_yes) - self.hw_error_dialog.open() + if self.hw_error_dialog == None or (self.hw_error_dialog != None and not self.hw_error_dialog.is_open): + description = self.sideband.getpersistent("startup.errors.rnode")["description"] + self.sideband.setpersistent("startup.errors.rnode", None) + yes_button = MDRectangleFlatButton( + text="OK", + font_size=dp(18), + ) + self.hw_error_dialog = MDDialog( + title="Hardware Error", + text="When starting a connected RNode, Reticulum reported the following error:\n\n[i]"+str(description)+"[/i]", + buttons=[ yes_button ], + # elevation=0, + ) + def dl_yes(s): + self.hw_error_dialog.is_open = False + self.hw_error_dialog.dismiss() + yes_button.bind(on_release=dl_yes) + 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) ################################################# @@ -363,38 +842,58 @@ 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=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=os.path.join(fb_path, "RobotoMonoNerdFont-Regular.ttf")) + + LabelBase.register(name="term", + fn_regular=os.path.join(fb_path, "BigBlueTerm437NerdFont-Regular.ttf")) + + LabelBase.register(name="nf", + fn_regular=os.path.join(fb_path, "RobotoMonoNerdFont-Regular.ttf")) def update_input_language(self): language = self.sideband.config["input_language"] if language == None: - self.input_font = "Roboto" - RNS.log("Setting input language to default set", RNS.LOG_DEBUG) + self.input_font = "defaultinput" else: self.input_font = language - RNS.log("Setting input language to "+str(language), RNS.LOG_DEBUG) + + RNS.log("Setting input language to "+str(self.input_font), RNS.LOG_DEBUG) + # def modify_input_font(self, ids): + # BIND_CLASSES = ["kivymd.uix.textfield.textfield.MDTextField",] + # for e in ids: + # te = ids[e] + # ts = str(te).split(" ")[0].replace("<", "") + # if ts in BIND_CLASSES: + # RNS.log("MODIFYING "+str(e)+" to "+self.input_font) + # te.font_name = self.input_font def update_ui_colors(self): if self.sideband.config["dark_ui"]: @@ -413,6 +912,19 @@ class SidebandApp(MDApp): self.color_hover = colors["Light"]["AppBar"] 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} {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: + 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"]: @@ -434,11 +946,54 @@ class SidebandApp(MDApp): def set_bars_colors(self): if RNS.vendor.platformutils.get_platform() == "android": - set_bars_colors( - self.theme_cls.primary_color, # status bar color - [0,0,0,0], # navigation bar color - "Light", # icons color of status bar - ) + + def set_navicons(set_dark_icons = False): + from android.runnable import run_on_ui_thread + from jnius import autoclass + WindowManager = autoclass("android.view.WindowManager$LayoutParams") + activity = autoclass("org.kivy.android.PythonActivity").mActivity + View = autoclass("android.view.View") + + def uit_exec(): + window = activity.getWindow() + window.clearFlags(WindowManager.FLAG_TRANSLUCENT_STATUS) + window.addFlags(WindowManager.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + + if set_dark_icons: + window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) + else: + window.getDecorView().setSystemUiVisibility(0) + + return run_on_ui_thread(uit_exec)() + + if self.sideband.config["dark_ui"]: + if self.sideband.config["eink_mode"] == True: + set_bars_colors( + self.theme_cls.primary_color, # status bar color + self.theme_cls.bg_light, # nav bar color + "Light", # icons color of status bar + ) + else: + set_bars_colors( + self.theme_cls.primary_color, + self.theme_cls.bg_darkest, + "Light") + else: + if self.sideband.config["eink_mode"] == True: + set_bars_colors( + self.theme_cls.primary_color, + self.theme_cls.bg_light, + "Light") + else: + set_bars_colors( + self.theme_cls.primary_color, + self.theme_cls.bg_darkest, + "Light") + + try: + set_navicons(set_dark_icons=True) + except Exception as e: + RNS.trace_exception(e) def close_any_action(self, sender=None): self.open_conversations(direction="right") @@ -458,7 +1013,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): @@ -501,16 +1056,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 - + self.sideband.should_persist_data(background=False) RNS.log("App paused", RNS.LOG_DEBUG) return True + else: return True @@ -521,12 +1078,12 @@ 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() + Clock.schedule_once(cb, 0.1) + threading.Thread(target=ui_update_job, daemon=True).start() RNS.log("App resumed", RNS.LOG_DEBUG) @@ -537,25 +1094,87 @@ 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 + # 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, + # probably due to an invalid GL draw context. By + # simply opening and immediately closing the nav + # drawer, we force the UI to do a frame redraw, which + # results in the UI actually being visible again. + if RNS.vendor.platformutils.is_android(): + RNS.log("Performing app wake UI update", RNS.LOG_DEBUG) + self.root.ids.nav_drawer.set_state("open") + def cb(dt): + 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(): + 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) - self.sideband.setpersistent("permissions.bluetooth", True) + + if android_api_version > 30: + if check_permission("android.permission.BLUETOOTH_SCAN"): + RNS.log("Have bluetooth scan permissions", RNS.LOG_DEBUG) + self.sideband.setpersistent("permissions.bluetooth", True) + + else: + RNS.log("Do not have bluetooth scan permissions") + self.sideband.setpersistent("permissions.bluetooth", False) + + else: + self.sideband.setpersistent("permissions.bluetooth", True) else: RNS.log("Do not have bluetooth connect permissions") self.sideband.setpersistent("permissions.bluetooth", False) @@ -592,6 +1211,12 @@ class SidebandApp(MDApp): self.check_permissions() + def request_microphone_permission(self): + if RNS.vendor.platformutils.get_platform() == "android": + if not check_permission("android.permission.RECORD_AUDIO"): + RNS.log("Requesting microphone permission", RNS.LOG_DEBUG) + request_permissions(["android.permission.RECORD_AUDIO"]) + def check_storage_permission(self): storage_permissions_ok = False if android_api_version < 30: @@ -640,49 +1265,200 @@ class SidebandApp(MDApp): def request_bluetooth_permissions(self): if RNS.vendor.platformutils.get_platform() == "android": - if not check_permission("android.permission.BLUETOOTH_CONNECT"): - RNS.log("Requesting bluetooth permission", RNS.LOG_DEBUG) - request_permissions(["android.permission.BLUETOOTH_CONNECT"]) + if not check_permission("android.permission.BLUETOOTH_CONNECT") or not check_permission("android.permission.BLUETOOTH_SCAN"): + RNS.log("Requesting Bluetooth permissions", RNS.LOG_DEBUG) + request_permissions(["android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH_SCAN"]) 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): + self.start_bluetooth_scan() + + def start_bluetooth_scan(self): + 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: + 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..." + + toast("Starting Bluetooth scan...") + RNS.log("Starting bluetooth scan", RNS.LOG_DEBUG) + self.discovered_bt_devices = {} + 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 + 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): + 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) + + 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): - RNS.log("Received intent", RNS.LOG_DEBUG) - intent_action = intent.getAction() - action = None - data = None + try: + intent_action = intent.getAction() + action = None + data = None - 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" + RNS.log(f"Received intent: {intent_action}", RNS.LOG_DEBUG) - 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.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) - if action != None: - self.handle_action(action, data) + 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: + 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 from Android intent", RNS.LOG_DEBUG) + def cb(dt): + try: + self.shared_attachment_action(data) + except Exception as e: + RNS.log("Error while handling external message attachment", RNS.LOG_ERROR) + RNS.trace_exception(e) + Clock.schedule_once(cb, 0.1) + def ingest_lxm_uri(self, lxm_uri): RNS.log("Ingesting LXMF paper message from URI: "+str(lxm_uri), RNS.LOG_DEBUG) 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 + self.guide_view = None + self.keys_view = None + self.hardware_view = None if RNS.vendor.platformutils.is_android(): ActivityInfo = autoclass('android.content.pm.ActivityInfo') @@ -714,9 +1490,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) @@ -731,6 +1506,54 @@ class SidebandApp(MDApp): else: self.service_last_available = time.time() + if RNS.vendor.platformutils.is_android(): + rnode_errors = self.sideband.getpersistent("runtime.errors.rnode") + if rnode_errors != None: + if self.hw_error_dialog == None or (self.hw_error_dialog != None and not self.hw_error_dialog.is_open): + description = rnode_errors["description"] + self.sideband.setpersistent("runtime.errors.rnode", None) + yes_button = MDRectangleFlatButton( + 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, 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 + + 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 + + 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() @@ -778,6 +1601,12 @@ class SidebandApp(MDApp): if self.conversations_view != None: self.conversations_view.update() + if self.sideband.getstate("app.flags.new_ticket", allow_cache=True): + def cb(d): + self.sideband.message_router.reload_available_tickets() + self.sideband.setstate("app.flags.new_ticket", False) + Clock.schedule_once(cb, 1.5) + if self.sideband.getstate("wants.viewupdate.conversations", allow_cache=True): if self.conversations_view != None: self.conversations_view.update() @@ -824,6 +1653,14 @@ class SidebandApp(MDApp): ok_button.bind(on_release=dl_ok) dialog.open() + def close_requested(self, *args): + if not self.closing_app: + self.quit_action(None) + return True + + def file_dropped(self, window, file_path, x, y, *args): + self.shared_attachment_action({"data_path": file_path.decode("utf-8")}) + def on_start(self): self.last_exit_event = time.time() self.root.ids.screen_manager.transition = self.slide_transition @@ -832,17 +1669,53 @@ class SidebandApp(MDApp): EventLoop.window.bind(on_keyboard=self.keyboard_event) EventLoop.window.bind(on_key_down=self.keydown_event) + EventLoop.window.bind(on_key_up=self.keyup_event) + Window.bind(on_request_close=self.close_requested) + Window.bind(on_drop_file=self.file_dropped) - if __variant__ != "": - variant_str = " "+__variant__ - else: - variant_str = "" + Window.bind(on_maximize=self.on_maximize) + 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: variant_str = "" self.root.ids.screen_manager.app = self self.root.ids.app_version_info.text = "Sideband v"+__version__+variant_str 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": + if not self.rec_dialog_is_open: + if not self.messages_view.ids.message_text.focus: + if self.messages_view.ptt_enabled and keycode == 44: + if self.key_ptt_down: + self.key_ptt_down = False + self.message_ptt_up_action() + + def keydown_event(self, instance, keyboard, keycode, text, modifiers): if self.keyboard_enabled: if self.root.ids.screen_manager.current == "map_screen": @@ -867,25 +1740,48 @@ class SidebandApp(MDApp): c_index = keycode-29 self.conversation_index_action(c_index) + if self.root.ids.screen_manager.current == "messages_screen": + if keycode == 43: + 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 + 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) + + 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() + + elif len(modifiers) > 1 and "shift" in modifiers and "ctrl" in modifiers: + def clear_att(): + if self.attach_path != None: + 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 == "v": + clear_att() + self.audio_msg_mode = LXMF.AM_OPUS_OGG + self.message_attach_action(attach_type="audio") + if text == "c": + clear_att() + self.audio_msg_mode = LXMF.AM_CODEC2_2400 + self.message_attach_action(attach_type="audio") + if len(modifiers) > 0: if modifiers[0] == "ctrl": if text == "q": self.quit_action(self) - if text == "w": - if self.root.ids.screen_manager.current == "conversations_screen": - self.quit_action(self) - 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() - 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() @@ -922,15 +1818,34 @@ class SidebandApp(MDApp): else: self.telemetry_action(self) - if text == "o": - # if self.root.ids.screen_manager.current == "telemetry_screen": + if text == "y": self.map_display_own_telemetry() + if text == "u": + self.utilities_action() + + 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": - self.lxmf_sync_action(self) + if self.include_objects: + self.conversations_action(self, direction="right") + else: + self.lxmf_sync_action(self) elif self.root.ids.screen_manager.current == "telemetry_screen": self.conversations_action(self, direction="right") + elif self.root.ids.screen_manager.current == "rnstatus_screen": + self.utilities_screen.update_rnstatus() elif self.root.ids.screen_manager.current == "object_details_screen": if not self.object_details_screen.object_hash == self.sideband.lxmf_destination.hash: self.converse_from_telemetry(self) @@ -952,29 +1867,12 @@ class SidebandApp(MDApp): # Handle escape/back if key == 27: if self.root.ids.screen_manager.current == "conversations_screen": - if time.time() - self.last_exit_event < 2: - self.quit_action(self) + if not self.include_conversations and self.include_objects: self.conversations_action(direction="right") 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() - 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): @@ -1013,6 +1911,7 @@ class SidebandApp(MDApp): self.root.ids.nav_drawer.set_state("closed") def quit_action(self, sender): + self.closing_app = True self.root.ids.nav_drawer.set_state("closed") self.sideband.should_persist_data() @@ -1048,6 +1947,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)) @@ -1070,6 +1970,58 @@ class SidebandApp(MDApp): ### Messages (conversation) screen ###################################### + + 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] + + return converted + + def process_bb_markup(self, text): + st = time.time() + ms = int(sp(14)) + h1s = int(sp(20)) + h2s = int(sp(18)) + h3s = int(sp(16)) + + if not hasattr(self, "pres"): + self.presz = re.compile(r"\[(?:size=\d*?)\]", re.IGNORECASE | re.MULTILINE ) + self.pres = [] + res = [ [r"\[(?:code|icode).*?\]", f"[font=mono][size={ms}]"], + [r"\[\/(?:code|icode).*?\]", "[/size][/font]"], + [r"\[(?:heading)\]", f"[b][size={h1s}]"], + [r"\[(?:heading=1)*?\]", f"[b][size={h1s}]"], + [r"\[(?:heading=2)*?\]", f"[b][size={h2s}]"], + [r"\[(?:heading=3)*?\]", f"[b][size={h3s}]"], + [r"\[(?:heading=).*?\]", f"[b][size={h3s}]"], # Match all remaining lower-level headings + [r"\[\/(?:heading).*?\]", "[/size][/b]"], + [r"\[(?:list).*?\]", ""], + [r"\[\/(?:list).*?\]", ""], + [r"\n\[(?:\*).*?\]", "\n - "], + [r"\[(?:url).*?\]", ""], # Strip URLs for now + [r"\[\/(?:url).*?\]", ""], + [r"\[(?:img).*?\].*\[\/(?:img).*?\]", ""] # Strip images for now + ] + + for r in res: + self.pres.append([re.compile(r[0], re.IGNORECASE | re.MULTILINE ), r[1]]) + + + size_matches = self.presz.findall(text) + for sm in size_matches: + text = text.replace(sm, f"{sm[:-1]}sp]") + + for pr in self.pres: + text = pr[0].sub(pr[1], text) + + return text + def conversation_from_announce_action(self, context_dest): if self.sideband.has_conversation(context_dest): pass @@ -1082,27 +2034,57 @@ 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) + 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): - 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 + 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: self.init_confirm_call_dialog(call_dialog_text) + 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 self.outbound_mode_paper = False self.outbound_mode_command = False - if self.sideband.config["propagation_by_default"]: - self.outbound_mode_propagation = True + self.outbound_mode_propagation = False + if self.include_objects and not self.include_conversations: + if self.sideband.config["propagation_by_default"]: + self.outbound_mode_propagation = True + else: + self.outbound_mode_command = True else: - self.outbound_mode_propagation = False + if self.sideband.config["propagation_by_default"]: + self.outbound_mode_propagation = True self.root.ids.screen_manager.transition.direction = direction self.messages_view = Messages(self, context_dest) @@ -1126,7 +2108,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) @@ -1138,18 +2119,26 @@ class SidebandApp(MDApp): Clock.schedule_once(scb, 0.33) def close_messages_action(self, sender=None): + self.rec_dialog_is_open = False self.open_conversations(direction="right") def message_send_action(self, sender=None): + self.rec_dialog_is_open = False if self.messages_view.ids.message_text.text == "": - return + if not (self.attach_type != None and self.attach_path != None): + return - def cb(dt): - self.message_send_dispatch(sender) + if self.outbound_mode_command: + return + + 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 + Clock.schedule_once(cb, 0.5) + if self.root.ids.screen_manager.current == "messages_screen": if self.outbound_mode_propagation and self.sideband.message_router.get_outbound_propagation_node() == None: self.messages_view.send_error_dialog = MDDialog( @@ -1168,10 +2157,14 @@ class SidebandApp(MDApp): else: msg_content = self.messages_view.ids.message_text.text + if msg_content == "": + msg_content = " " + context_dest = self.messages_view.ids.messages_scrollview.active_conversation attachment = None image = None + audio = None if not self.outbound_mode_command and not self.outbound_mode_paper: if self.attach_type != None and self.attach_path != None: try: @@ -1182,6 +2175,14 @@ class SidebandApp(MDApp): with open(self.attach_path, "rb") as af: attachment = [fbn, af.read()] + if self.attach_type == "audio": + if self.audio_msg_mode == LXMF.AM_OPUS_OGG: + with open(self.attach_path, "rb") as af: + audio = [self.audio_msg_mode, af.read()] + elif self.audio_msg_mode >= LXMF.AM_CODEC2_700C and self.audio_msg_mode <= LXMF.AM_CODEC2_3200: + with open(self.attach_path, "rb") as af: + audio = [self.audio_msg_mode, af.read()] + elif self.attach_type == "lbimg": max_size = 320, 320 with PilImage.open(self.attach_path) as im: @@ -1253,7 +2254,7 @@ class SidebandApp(MDApp): self.messages_view.ids.messages_scrollview.scroll_y = 0 self.jobs(0) - elif self.sideband.send_message(msg_content, context_dest, self.outbound_mode_propagation, attachment = attachment, image = image): + elif self.sideband.send_message(msg_content, context_dest, self.outbound_mode_propagation, attachment = attachment, image = image, audio = audio): self.messages_view.ids.message_text.text = "" self.messages_view.ids.messages_scrollview.scroll_y = 0 self.jobs(0) @@ -1271,10 +2272,6 @@ class SidebandApp(MDApp): ], ) self.messages_view.send_error_dialog.open() - - def cb(dt): - self.messages_view.ids.message_send_button.disabled = False - Clock.schedule_once(cb, 0.5) def peer_show_location_action(self, sender): if self.root.ids.screen_manager.current == "messages_screen": @@ -1288,6 +2285,11 @@ class SidebandApp(MDApp): if self.root.ids.screen_manager.current == "messages_screen": self.object_details_action(self.messages_view, from_conv=True) + def outbound_mode_reset(self, sender=None): + self.outbound_mode_paper = False + self.outbound_mode_propagation = False + self.outbound_mode_command = False + def message_propagation_action(self, sender): if self.outbound_mode_command: self.outbound_mode_paper = False @@ -1317,18 +2319,10 @@ class SidebandApp(MDApp): tf = open(path, "rb") tf.close() self.attach_path = path + if self.outbound_mode_command: + self.outbound_mode_reset() - if RNS.vendor.platformutils.is_android(): - toast("Attached \""+str(fbn)+"\"") - else: - ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - ate_dialog = MDDialog( - title="File Attached", - text="The file \""+str(fbn)+"\" was attached, and will be included with the next message sent.", - buttons=[ ok_button ], - ) - ok_button.bind(on_release=ate_dialog.dismiss) - ate_dialog.open() + toast("Attached \""+str(fbn)+"\"") except Exception as e: RNS.log(f"Error while attaching \"{fbn}\": "+str(e), RNS.LOG_ERROR) @@ -1349,7 +2343,8 @@ class SidebandApp(MDApp): def message_fm_exited(self, *args): self.manager_open = False - self.file_manager.close() + if self.file_manager != None: + self.file_manager.close() def message_select_file_action(self, sender=None): perm_ok = False @@ -1364,11 +2359,20 @@ class SidebandApp(MDApp): if perm_ok and path != None: try: - self.file_manager = MDFileManager( - exit_manager=self.message_fm_exited, - select_path=self.message_fm_got_path, - ) - # self.file_manager.ext = ["*"] + if self.attach_type in ["lbimg", "defimg", "hqimg"]: + self.file_manager = MDFileManager( + exit_manager=self.message_fm_exited, + select_path=self.message_fm_got_path, + # Current KivyMD preview implementation is too slow to be reliable on Android + preview=False) + else: + self.file_manager = MDFileManager( + exit_manager=self.message_fm_exited, + select_path=self.message_fm_got_path, + preview=False) + + # self.file_manager.ext = [] + # self.file_manager.search = "all" self.file_manager.show(path) except Exception as e: @@ -1385,8 +2389,6 @@ class SidebandApp(MDApp): ate_dialog.open() else: - self.sideband.config["map_storage_path"] = None - self.sideband.save_configuration() if RNS.vendor.platformutils.get_platform() == "android": toast("No file access, check permissions!") else: @@ -1399,64 +2401,432 @@ class SidebandApp(MDApp): ok_button.bind(on_release=ate_dialog.dismiss) ate_dialog.open() - def message_attach_action(self, attach_type=None): + def display_codec2_error(self): + if self.compat_error_dialog == None: + def cb(sender): + self.compat_error_dialog.dismiss() + self.compat_error_dialog = MDDialog( + title="Could not load Codec2", + text="The Codec2 library could not be loaded. This likely means that you do not have the [b]codec2[/b] package or shared library installed on your system.\n\nThis library is normally installed automatically when Sideband is installed, but on some systems, this is not possible.\n\nTry installing it with a command such as [b]pamac install codec2[/b] or [b]apt install codec2[/b], or by compiling it from source for this system.", + buttons=[ + MDRectangleFlatButton( + text="OK", + font_size=dp(18), + on_release=cb + ) + ], + ) + self.compat_error_dialog.open() + + def play_audio_field(self, audio_field): + 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 = 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 = os.path.join(self.sideband.rec_cache, "msg.ogg") + from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 + + 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 self.msg_sound == None: + self.msg_sound = FilePlayer() + + self.msg_sound.set_source(temp_path) + + 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) + + def message_ptt_down_action(self, sender=None): + 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 = 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)]) + + self.message_attach_action(attach_type="audio", nodialog=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" + el_button.text_color=mdc("Orange","400") + el_button.line_color=mdc("Orange","400") + el_icon.theme_text_color="Custom" + el_icon.text_color=mdc("Orange","400") + self.ptt_recorder.start() + + + def message_ptt_up_action(self, sender=None): + if not self.sideband.ui_recording: return + + 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" + el_button.text_color=mdc("BlueGray","500") + 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() + 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.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): + from sideband.audioproc import voice_processing + if self.audio_msg_mode == LXMF.AM_OPUS_OGG: + proc_path = voice_processing(input_path) + if proc_path: + self.attach_path = proc_path + os.unlink(input_path) + RNS.log("Using voice-processed OPUS data in OGG container", RNS.LOG_DEBUG) + else: + self.attach_path = input_path + RNS.log("Using unmodified OPUS data in OGG container", RNS.LOG_DEBUG) + else: + ap_start = time.time() + 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(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") + + audio = AudioSegment( + bytes(opus_file.as_array()), + frame_rate=opus_file.frequency, + sample_width=opus_file.bytes_per_sample, + channels=opus_file.channels, + ) + audio = audio.split_to_mono()[0] + audio = audio.apply_gain(-audio.max_dBFS) + + if self.audio_msg_mode >= LXMF.AM_CODEC2_700C and self.audio_msg_mode <= LXMF.AM_CODEC2_3200: + audio = audio.set_frame_rate(8000) + audio = audio.set_sample_width(2) + samples = audio.get_array_of_samples() + + from sideband.audioproc import encode_codec2, detect_codec2 + if detect_codec2(): + encoded = encode_codec2(samples, self.audio_msg_mode) + + ap_duration = time.time() - ap_start + RNS.log("Audio processing complete in "+RNS.prettytime(ap_duration), RNS.LOG_DEBUG) + + 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 + os.unlink(input_path) + else: + self.display_codec2_error() + return False + + return True + + def message_init_rec_dialog(self): + ss = int(dp(18)) + 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 and not self.rec_dialog.recorder: + self.sideband.ui_started_recording() + 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 + el.theme_text_color="Custom" + el.text_color=mdc("Red","400") + el.icon = "stop-circle" + self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Stop Recording[/size]" + self.rec_dialog.recorder.start() + + else: + RNS.log("Stopping recording...", RNS.LOG_DEBUG) # TODO: Remove + self.rec_dialog.recorder.stop() + self.rec_dialog.recorder = None + 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" + el.text_color = self.theme_cls._get_text_color() + self.rec_dialog.play_item.disabled = False + self.rec_dialog.save_item.disabled = False + 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 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.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.recording_player.stop() + + self.msg_rec_a_play = a_play + + def a_finished(sender): + RNS.log("Playback finished", 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.recording_player.finished_callback = a_finished + + def a_save(sender): + if self.rec_dialog.recording: a_rec_action(sender) + self.rec_dialog_is_open = False + self.rec_dialog.dismiss() + + try: + 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") + + except Exception as e: + RNS.trace_exception(e) + + self.msg_rec_a_save = a_save + + cancel_button = MDRectangleFlatButton(text="Cancel", font_size=dp(18)) + rec_item = DialogItem(IconLeftWidget(icon="record", on_release=a_rec_action), text="[size="+str(ss)+"]Start Recording[/size]", on_release=a_rec_action) + play_item = DialogItem(IconLeftWidget(icon="play", on_release=a_play), text="[size="+str(ss)+"]Play[/size]", on_release=a_play, disabled=True) + save_item = DialogItem(IconLeftWidget(icon="content-save-move-outline", on_release=a_save), text="[size="+str(ss)+"]Save to message[/size]", on_release=a_save, disabled=True) + self.rec_dialog = MDDialog( + title="Record Audio", + type="simple", + items=[ + rec_item, + play_item, + save_item, + ], + buttons=[ cancel_button ], + 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 = os.path.join(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() + + else: + self.rec_dialog.play_item.disabled = True + self.rec_dialog.save_item.disabled = True + self.rec_dialog.recording = False + self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Start Recording[/size]" + self.rec_dialog.rec_item.children[0].children[0].icon = "record" + + self.rec_dialog.open() + self.rec_dialog_is_open = True + + def message_attach_action(self, attach_type=None, nodialog=False): + file_attach_types = ["lbimg", "defimg", "hqimg", "file"] + rec_attach_types = ["audio"] + self.attach_path = None - self.attach_type = attach_type - self.message_select_file_action() + self.rec_dialog_is_open = False + if attach_type in file_attach_types: + self.attach_type = attach_type + if not nodialog: + self.message_select_file_action() + elif attach_type in rec_attach_types: + self.attach_type = attach_type + if not nodialog: + self.message_record_audio_action() def message_attachment_action(self, sender): + self.rec_dialog_is_open = False if self.attach_path == None: - attach_dialog = None def a_img_lb(sender): - attach_dialog.dismiss() + self.attach_dialog.dismiss() self.message_attach_action(attach_type="lbimg") def a_img_def(sender): - attach_dialog.dismiss() + self.attach_dialog.dismiss() self.message_attach_action(attach_type="defimg") def a_img_hq(sender): - attach_dialog.dismiss() + self.attach_dialog.dismiss() self.message_attach_action(attach_type="hqimg") def a_file(sender): - attach_dialog.dismiss() + self.attach_dialog.dismiss() self.message_attach_action(attach_type="file") + def a_audio_hq(sender): + self.attach_dialog.dismiss() + self.audio_msg_mode = LXMF.AM_OPUS_OGG + self.message_attach_action(attach_type="audio") + def a_audio_lb(sender): + self.attach_dialog.dismiss() + self.audio_msg_mode = LXMF.AM_CODEC2_2400 + self.message_attach_action(attach_type="audio") - ss = int(dp(18)) - cancel_button = MDRectangleFlatButton(text="Cancel", font_size=dp(18)) - attach_dialog = MDDialog( - title="Add Attachment", - type="simple", - text="Select the type of attachment you want to send with this message\n", - items=[ - DialogItem(IconLeftWidget(icon="message-image-outline"), text="[size="+str(ss)+"]Low-bandwidth Image[/size]", on_release=a_img_lb), - DialogItem(IconLeftWidget(icon="file-image"), text="[size="+str(ss)+"]Medium Image[/size]", on_release=a_img_def), - DialogItem(IconLeftWidget(icon="image-outline"), text="[size="+str(ss)+"]High-res Image[/size]", on_release=a_img_hq), - DialogItem(IconLeftWidget(icon="file-outline"), text="[size="+str(ss)+"]File Attachment[/size]", on_release=a_file), - ], - buttons=[ cancel_button ], - width_offset=dp(12), - ) + if self.attach_dialog == None: + ss = int(dp(18)) + cancel_button = MDRectangleFlatButton(text="Cancel", font_size=dp(18)) + ad_items = [ + DialogItem(IconLeftWidget(icon="message-image-outline", on_release=a_img_lb), text="[size="+str(ss)+"]Low-bandwidth Image[/size]", on_release=a_img_lb), + DialogItem(IconLeftWidget(icon="file-image", on_release=a_img_def), text="[size="+str(ss)+"]Medium Image[/size]", on_release=a_img_def), + DialogItem(IconLeftWidget(icon="image-outline", on_release=a_img_hq), text="[size="+str(ss)+"]High-res Image[/size]", on_release=a_img_hq), + 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)] - cancel_button.bind(on_release=attach_dialog.dismiss) - attach_dialog.open() - attach_dialog.update_width() + if RNS.vendor.platformutils.is_android() and android_api_version < 29: + ad_items.pop(3) + ad_items.pop(3) + + self.attach_dialog = MDDialog( + title="Add Attachment", + type="simple", + text="Select the type of attachment you want to send with this message\n", + items=ad_items, + buttons=[ cancel_button ], + width_offset=dp(32), + ) + + cancel_button.bind(on_release=self.attach_dialog.dismiss) + + self.attach_dialog.open() else: self.attach_path = None self.attach_type = None self.update_message_widgets() - if RNS.vendor.platformutils.get_platform() == "android": - toast("Attachment removed") + toast("Attachment removed") + + def shared_attachment_action(self, attachment_data): + if not self.root.ids.screen_manager.current == "messages_screen": + if RNS.vendor.platformutils.is_android(): + toast("Please select a conversation first") else: ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) ate_dialog = MDDialog( - title="Attachment Removed", - text="The attached resource was removed from the message", + title="No active conversation", + text="To drop files as attachments, please open a conversation first", buttons=[ ok_button ], ) ok_button.bind(on_release=ate_dialog.dismiss) ate_dialog.open() + else: + self.rec_dialog_is_open = False + def a_img_lb(sender): + self.attach_type="lbimg" + self.shared_attach_dialog.dismiss() + self.shared_attach_dialog.att_exc() + def a_img_def(sender): + self.attach_type="defimg" + self.shared_attach_dialog.dismiss() + self.shared_attach_dialog.att_exc() + def a_img_hq(sender): + self.attach_type="hqimg" + self.shared_attach_dialog.dismiss() + self.shared_attach_dialog.att_exc() + def a_file(sender): + self.attach_type="file" + self.shared_attach_dialog.dismiss() + self.shared_attach_dialog.att_exc() + + if self.shared_attach_dialog == None: + ss = int(dp(18)) + cancel_button = MDRectangleFlatButton(text="Cancel", font_size=dp(18)) + ad_items = [ + DialogItem(IconLeftWidget(icon="message-image-outline", on_release=a_img_lb), text="[size="+str(ss)+"]Low-bandwidth Image[/size]", on_release=a_img_lb), + DialogItem(IconLeftWidget(icon="file-image", on_release=a_img_def), text="[size="+str(ss)+"]Medium Image[/size]", on_release=a_img_def), + DialogItem(IconLeftWidget(icon="image-outline", on_release=a_img_hq), text="[size="+str(ss)+"]High-res Image[/size]", on_release=a_img_hq), + DialogItem(IconLeftWidget(icon="file-outline", on_release=a_file), text="[size="+str(ss)+"]File Attachment[/size]", on_release=a_file)] + + self.shared_attach_dialog = MDDialog( + title="Add Attachment", + type="simple", + text="Select how you want to attach this data to the next message sent\n", + items=ad_items, + buttons=[ cancel_button ], + width_offset=dp(32), + ) + + cancel_button.bind(on_release=self.shared_attach_dialog.dismiss) + + def att_exc(): + self.message_fm_got_path(attachment_data["data_path"]) + + self.shared_attach_dialog.att_exc = att_exc + self.shared_attach_dialog.open() def update_message_widgets(self): toolbar_items = self.messages_view.ids.messages_toolbar.ids.right_actions.children @@ -1502,15 +2872,39 @@ 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) self.widget_hide(self.messages_view.ids.no_keys_part, False) ### Conversations screen ###################################### def conversations_action(self, sender=None, direction="left", no_transition=False): + self.rec_dialog_is_open = False + if self.include_objects: + self.include_conversations = True + self.include_objects = False + self.conversations_view.update() + + 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.open_conversations(direction=direction) + + if no_transition: + self.root.ids.screen_manager.transition = self.slide_transition + + def objects_action(self, sender=None, direction="left", no_transition=False): + if self.include_conversations: + self.include_conversations = False + self.include_objects = True + self.conversations_view.update() + if no_transition: self.root.ids.screen_manager.transition = self.no_transition else: @@ -1529,12 +2923,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 @@ -1562,30 +2950,40 @@ class SidebandApp(MDApp): return "Could not retrieve connectivity status" def connectivity_status(self, sender): - hs = dp(22) + 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=[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() + + def cb_rns(sender): + dialog.dismiss() + 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) + dialog.open() - yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) - dialog = MDDialog( - title="Connectivity Status", - text=str(self.get_connectivity_text()), - buttons=[ 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() - yes_button.bind(on_release=dl_yes) - dialog.open() + self.connectivity_updater = Clock.schedule_interval(cs_updater, 2.0) - if self.connectivity_updater != None: - self.connectivity_updater.cancel() + else: + self.rnstatus_action(from_conversations=True) - self.connectivity_updater = Clock.schedule_interval(cs_updater, 2.0) + 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): @@ -1659,13 +3057,14 @@ class SidebandApp(MDApp): else: sl = None + sync_title = "LXMF Sync" if not hasattr(self, "message_sync_dialog") or self.message_sync_dialog == None: close_button = MDRectangleFlatButton(text="Close",font_size=dp(18)) stop_button = MDRectangleFlatButton(text="Stop",font_size=dp(18), theme_text_color="Custom", line_color=self.color_reject, text_color=self.color_reject) dialog_content = MsgSync() dialog = MDDialog( - title="LXMF Sync via "+RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node()), + title=sync_title, type="custom", content_cls=dialog_content, buttons=[ stop_button, close_button ], @@ -1677,12 +3076,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) @@ -1702,7 +3099,8 @@ class SidebandApp(MDApp): dsp = 0 self.sideband.setstate("app.flags.lxmf_sync_dialog_open", True) - self.message_sync_dialog.title = f"LXMF Sync via "+RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node()) + self.message_sync_dialog.title = sync_title + self.message_sync_dialog.d_content.ids.node_info.text = f"Via {RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node())}\n" self.message_sync_dialog.d_content.ids.sync_status.text = self.sideband.get_sync_status() self.message_sync_dialog.d_content.ids.sync_progress.value = dsp self.message_sync_dialog.d_content.ids.sync_progress.start() @@ -1740,17 +3138,22 @@ 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) if new_result: + dialog.d_content.ids["n_address_field"].helper_text = "" + dialog.d_content.ids["n_address_field"].helper_text_mode = "on_focus" dialog.d_content.ids["n_address_field"].error = False dialog.dismiss() if self.conversations_view != None: self.conversations_view.update() else: + dialog.d_content.ids["n_address_field"].helper_text = "Invalid address, check your input" + dialog.d_content.ids["n_address_field"].helper_text_mode = "persistent" dialog.d_content.ids["n_address_field"].error = True # dialog.d_content.ids["n_error_field"].text = "Could not create conversation. Check your input." @@ -1796,9 +3199,14 @@ 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") - 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 - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)\n - [b]Kivy[/b] (MIT License)\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Python[/b] (PSF License)"+"\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright (c) 2024 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of Sideband v"+__version__+" "+__variant__+", 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 = " - [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 ┬й 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) @@ -1839,6 +3247,72 @@ class SidebandApp(MDApp): if no_transition: self.root.ids.screen_manager.transition = self.slide_transition + def configure_ui_scaling_action(self, sender=None): + global app_ui_scaling_path + try: + cancel_button = MDRectangleFlatButton(text="Cancel",font_size=dp(18)) + set_button = MDRectangleFlatButton(text="Set",font_size=dp(18), theme_text_color="Custom", line_color=self.color_accept, text_color=self.color_accept) + + dialog_content = UIScaling() + dialog = MDDialog( + title="UI Scaling", + type="custom", + content_cls=dialog_content, + buttons=[ set_button, cancel_button ], + # elevation=0, + ) + dialog.d_content = dialog_content + dialog.d_content.ids["scaling_factor"].text = os.environ["KIVY_METRICS_DENSITY"] if "KIVY_METRICS_DENSITY" in os.environ else "0.0" + def dl_yes(s): + new_sf = 1.0 + scaling_ok = False + try: + si = dialog.d_content.ids["scaling_factor"].text + sf = float(si) + if (sf >= 0.3 and sf <= 5.0) or sf == 0.0: + new_sf = sf + scaling_ok = True + + except Exception as e: + RNS.log("Error while getting scaling factor from user: "+str(e), RNS.LOG_ERROR) + + if scaling_ok: + dialog.d_content.ids["scaling_factor"].helper_text = "" + dialog.d_content.ids["scaling_factor"].helper_text_mode = "on_focus" + dialog.d_content.ids["scaling_factor"].error = False + dialog.dismiss() + if app_ui_scaling_path == None: + RNS.log("No path to UI scaling factor file could be found, cannot save scaling factor", RNS.LOG_ERROR) + else: + try: + with open(app_ui_scaling_path, "w") as sfile: + sfile.write(str(new_sf)) + RNS.log(f"Saved configured scaling factor {new_sf} to {app_ui_scaling_path}", RNS.LOG_DEBUG) + except Exception as e: + RNS.log(f"Error while saving scaling factor {new_sf} to {app_ui_scaling_path}: {e}", RNS.LOG_ERROR) + + else: + dialog.d_content.ids["scaling_factor"].helper_text = "Invalid scale factor, check your input" + dialog.d_content.ids["scaling_factor"].helper_text_mode = "persistent" + dialog.d_content.ids["scaling_factor"].error = True + + def dl_no(s): + dialog.dismiss() + + def dl_ds(s): + self.dialog_open = False + + set_button.bind(on_release=dl_yes) + cancel_button.bind(on_release=dl_no) + + dialog.bind(on_dismiss=dl_ds) + dialog.open() + self.dialog_open = True + + except Exception as e: + RNS.log("Error while creating UI scaling dialog: "+str(e), RNS.LOG_ERROR) + + def settings_action(self, sender=None, direction="left"): if self.settings_ready: self.settings_open(direction=direction) @@ -1957,11 +3431,9 @@ class SidebandApp(MDApp): if sender != self.settings_screen.ids.settings_lang_hebrew: self.settings_screen.ids.settings_lang_hebrew.active = False - RNS.log("Sender: "+str(sender)) - if self.settings_screen.ids.settings_lang_default.active: self.sideband.config["input_language"] = None - self.settings_screen.ids.settings_display_name.font_name = "" + self.settings_screen.ids.settings_display_name.font_name = "defaultinput" elif self.settings_screen.ids.settings_lang_chinese.active: self.sideband.config["input_language"] = "chinese" self.settings_screen.ids.settings_display_name.font_name = "chinese" @@ -1979,7 +3451,7 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_display_name.font_name = "hebrew" else: self.sideband.config["input_language"] = None - self.settings_screen.ids.settings_display_name.font_name = "" + self.settings_screen.ids.settings_display_name.font_name = "defaultinput" self.sideband.save_configuration() @@ -1995,11 +3467,29 @@ class SidebandApp(MDApp): self.sideband.save_configuration() self.update_ui_theme() + def save_classic_message_colors(sender=None, event=None): + self.sideband.config["classic_message_colors"] = self.settings_screen.ids.settings_classic_message_colors.active + self.sideband.save_configuration() + self.update_ui_theme() + def save_display_style_in_contact_list(sender=None, event=None): self.sideband.config["display_style_in_contact_list"] = self.settings_screen.ids.display_style_in_contact_list.active self.sideband.save_configuration() self.sideband.setstate("wants.viewupdate.conversations", True) + def save_display_style_from_trusted_only(sender=None, event=None): + self.sideband.config["display_style_from_all"] = not self.settings_screen.ids.display_style_from_trusted_only.active + self.sideband.save_configuration() + self.sideband.setstate("wants.viewupdate.conversations", True) + + def save_trusted_markup_only(sender=None, event=None): + self.sideband.config["trusted_markup_only"] = self.settings_screen.ids.settings_trusted_markup_only.active + self.sideband.save_configuration() + + def save_compose_in_markdown(sender=None, event=None): + self.sideband.config["compose_in_markdown"] = self.settings_screen.ids.settings_compose_in_markdown.active + self.sideband.save_configuration() + def save_advanced_stats(sender=None, event=None): self.sideband.config["advanced_stats"] = self.settings_screen.ids.settings_advanced_statistics.active self.sideband.save_configuration() @@ -2024,6 +3514,11 @@ class SidebandApp(MDApp): self.sideband.config["lxmf_ignore_unknown"] = self.settings_screen.ids.settings_lxmf_ignore_unknown.active self.sideband.save_configuration() + def save_lxmf_ignore_invalid_stamps(sender=None, event=None): + self.sideband.config["lxmf_ignore_invalid_stamps"] = self.settings_screen.ids.settings_ignore_invalid_stamps.active + self.sideband.save_configuration() + self.sideband.update_ignore_invalid_stamps() + def save_lxmf_sync_limit(sender=None, event=None): self.sideband.config["lxmf_sync_limit"] = self.settings_screen.ids.settings_lxmf_sync_limit.active self.sideband.save_configuration() @@ -2037,6 +3532,27 @@ class SidebandApp(MDApp): self.sideband.save_configuration() self.sideband._reticulum_log_debug(self.sideband.config["debug"]) + def save_block_predictive_text(sender=None, event=None): + self.sideband.config["block_predictive_text"] = self.settings_screen.ids.settings_block_predictive_text.active + self.sideband.save_configuration() + + def save_hq_ptt(sender=None, event=None): + 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.request_microphone_permission() + 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 @@ -2049,6 +3565,16 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_print_command.text = self.sideband.config["print_command"] self.sideband.save_configuration() + def save_lxmf_stamp_cost(sender=None, event=None, save=True): + if self.settings_screen.ids.settings_lxmf_require_stamps.active: + self.widget_hide(self.settings_screen.ids.lxmf_costslider_container, False) + else: + self.widget_hide(self.settings_screen.ids.lxmf_costslider_container, True) + + if save: + self.sideband.config["lxmf_require_stamps"] = self.settings_screen.ids.settings_lxmf_require_stamps.active + self.sideband.save_configuration() + def save_lxmf_periodic_sync(sender=None, event=None, save=True): if self.settings_screen.ids.settings_lxmf_periodic_sync.active: self.widget_hide(self.settings_screen.ids.lxmf_syncslider_container, False) @@ -2076,8 +3602,23 @@ class SidebandApp(MDApp): pre = self.settings_screen.ids.settings_lxmf_sync_periodic.text self.settings_screen.ids.settings_lxmf_sync_periodic.text = "Auto sync every "+interval_text if save: - self.sideband.config["lxmf_sync_interval"] = interval - self.sideband.save_configuration() + if (event == None or not hasattr(event, "button") or not event.button) or not "scroll" in event.button: + self.sideband.config["lxmf_sync_interval"] = interval + self.sideband.save_configuration() + + def stamp_cost_change(sender=None, event=None, save=True): + slider_val = int(self.settings_screen.ids.settings_lxmf_require_stamps_cost.value) + cost_text = str(slider_val) + + self.settings_screen.ids.settings_lxmf_require_stamps_label.text = f"Require stamp cost {cost_text} for incoming messages" + if save: + if slider_val > 32: + slider_val = 32 + if slider_val < 1: + slider_val = 1 + self.sideband.config["lxmf_inbound_stamp_cost"] = slider_val + if (event == None or not hasattr(event, "button") or not event.button) or not "scroll" in event.button: + self.sideband.save_configuration() self.settings_screen.ids.settings_lxmf_address.text = RNS.hexrep(self.sideband.lxmf_destination.hash, delimit=False) self.settings_screen.ids.settings_identity_hash.text = RNS.hexrep(self.sideband.lxmf_destination.identity.hash, delimit=False) @@ -2091,11 +3632,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) @@ -2113,12 +3653,21 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_eink_mode.active = self.sideband.config["eink_mode"] self.settings_screen.ids.settings_eink_mode.bind(active=save_eink_mode) + self.settings_screen.ids.settings_classic_message_colors.active = self.sideband.config["classic_message_colors"] + self.settings_screen.ids.settings_classic_message_colors.bind(active=save_classic_message_colors) + self.settings_screen.ids.display_style_in_contact_list.active = self.sideband.config["display_style_in_contact_list"] self.settings_screen.ids.display_style_in_contact_list.bind(active=save_display_style_in_contact_list) + self.settings_screen.ids.display_style_from_trusted_only.active = not self.sideband.config["display_style_from_all"] + self.settings_screen.ids.display_style_from_trusted_only.bind(active=save_display_style_from_trusted_only) + 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) @@ -2131,6 +3680,15 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_lxmf_ignore_unknown.active = self.sideband.config["lxmf_ignore_unknown"] self.settings_screen.ids.settings_lxmf_ignore_unknown.bind(active=save_lxmf_ignore_unknown) + self.settings_screen.ids.settings_trusted_markup_only.active = self.sideband.config["trusted_markup_only"] + self.settings_screen.ids.settings_trusted_markup_only.bind(active=save_trusted_markup_only) + + self.settings_screen.ids.settings_compose_in_markdown.active = self.sideband.config["compose_in_markdown"] + self.settings_screen.ids.settings_compose_in_markdown.bind(active=save_compose_in_markdown) + + self.settings_screen.ids.settings_ignore_invalid_stamps.active = self.sideband.config["lxmf_ignore_invalid_stamps"] + self.settings_screen.ids.settings_ignore_invalid_stamps.bind(active=save_lxmf_ignore_invalid_stamps) + self.settings_screen.ids.settings_lxmf_periodic_sync.active = self.sideband.config["lxmf_periodic_sync"] self.settings_screen.ids.settings_lxmf_periodic_sync.bind(active=save_lxmf_periodic_sync) save_lxmf_periodic_sync(save=False) @@ -2142,6 +3700,22 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_lxmf_sync_interval.value = self.interval_to_slider_val(self.sideband.config["lxmf_sync_interval"]) sync_interval_change(save=False) + self.settings_screen.ids.settings_lxmf_require_stamps.active = self.sideband.config["lxmf_require_stamps"] + self.settings_screen.ids.settings_lxmf_require_stamps.bind(active=save_lxmf_stamp_cost) + save_lxmf_stamp_cost(save=False) + + def stamp_cost_change_cb(sender=None, event=None): + stamp_cost_change(sender=sender, event=event, save=False) + self.settings_screen.ids.settings_lxmf_require_stamps_cost.bind(value=stamp_cost_change_cb) + self.settings_screen.ids.settings_lxmf_require_stamps_cost.bind(on_touch_up=stamp_cost_change) + cost_val = self.sideband.config["lxmf_inbound_stamp_cost"] + if cost_val == None or cost_val < 1: + cost_val = 1 + if cost_val > 32: + cost_val = 32 + self.settings_screen.ids.settings_lxmf_require_stamps_cost.value = cost_val + stamp_cost_change(save=False) + if self.sideband.config["lxmf_sync_limit"] == None or self.sideband.config["lxmf_sync_limit"] == False: sync_limit = False else: @@ -2153,9 +3727,18 @@ class SidebandApp(MDApp): self.settings_screen.ids.settings_lxm_limit_1mb.active = self.sideband.config["lxm_limit_1mb"] self.settings_screen.ids.settings_lxm_limit_1mb.bind(active=save_lxm_limit_1mb) + 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) + self.settings_screen.ids.settings_block_predictive_text.active = self.sideband.config["block_predictive_text"] + self.settings_screen.ids.settings_block_predictive_text.bind(active=save_block_predictive_text) + self.settings_screen.ids.settings_lang_default.active = False self.settings_screen.ids.settings_lang_chinese.active = False self.settings_screen.ids.settings_lang_japanese.active = False @@ -2180,7 +3763,7 @@ class SidebandApp(MDApp): elif input_lang == "korean": self.settings_screen.ids.settings_lang_korean.active = True self.settings_screen.ids.settings_display_name.font_name = "korean" - elif input_lang == "devangari": + elif input_lang == "combined": self.settings_screen.ids.settings_lang_devangari.active = True self.settings_screen.ids.settings_display_name.font_name = "combined" elif input_lang == "hebrew": @@ -2262,7 +3845,9 @@ 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) self.widget_hide(self.connectivity_screen.ids.connectivity_shared_access_label) self.widget_hide(self.connectivity_screen.ids.connectivity_shared_access_fields) @@ -2270,41 +3855,47 @@ 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.root.ids.connectivity_local_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_local_fields, collapse) pass def con_collapse_tcp(collapse=True): - # self.widget_hide(self.root.ids.connectivity_tcp_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_tcp_fields, collapse) pass def con_collapse_i2p(collapse=True): - # self.widget_hide(self.root.ids.connectivity_i2p_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_i2p_fields, collapse) pass def con_collapse_bluetooth(collapse=True): - # self.widget_hide(self.root.ids.connectivity_bluetooth_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_bluetooth_fields, collapse) pass def con_collapse_rnode(collapse=True): - # self.widget_hide(self.root.ids.connectivity_rnode_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_rnode_fields, collapse) pass def con_collapse_modem(collapse=True): - # self.widget_hide(self.root.ids.connectivity_modem_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_modem_fields, collapse) pass def con_collapse_serial(collapse=True): - # self.widget_hide(self.root.ids.connectivity_serial_fields, collapse) + # 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.root.ids.connectivity_transport_fields, collapse) + # self.widget_hide(self.connectivity_screen.ids.connectivity_transport_fields, collapse) pass 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 @@ -2326,6 +3917,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 @@ -2343,6 +3938,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() @@ -2368,13 +3964,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): @@ -2422,7 +4021,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"] @@ -2459,9 +4058,18 @@ 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) + + 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() @@ -2497,6 +4105,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) @@ -2511,12 +4123,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 @@ -2541,7 +4155,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() @@ -2554,6 +4169,7 @@ class SidebandApp(MDApp): ###################################### def repository_action(self, sender=None, direction="left"): if self.repository_ready: + self.repository_update_info() self.repository_open(direction=direction) else: self.loader_action(direction=direction) @@ -2580,9 +4196,9 @@ class SidebandApp(MDApp): self.root.ids.screen_manager.transition = self.slide_transition def repository_link_action(self, sender=None, event=None): - if self.reposository_url != None: + if self.repository_url != None: def lj(): - webbrowser.open(self.reposository_url) + webbrowser.open(self.repository_url) threading.Thread(target=lj, daemon=True).start() def repository_update_info(self, sender=None): @@ -2590,9 +4206,9 @@ class SidebandApp(MDApp): info += "If you want to share the Sideband application itself via the repository server, you must first download it into the local repository, using the \"Update Content\" button below.\n\n" info += "To make the repository available on your local network, simply start it below, and it will become browsable on a local IP address for anyone connected to the same WiFi or wired network.\n\n" if self.sideband.webshare_server != None: - if RNS.vendor.platformutils.is_android(): - def getIP(): - adrs = [] + def getIP(): + adrs = [] + if RNS.vendor.platformutils.is_android(): try: from jnius import autoclass import ipaddress @@ -2615,30 +4231,47 @@ class SidebandApp(MDApp): RNS.log("Error while getting repository IP address: "+str(e), RNS.LOG_ERROR) return None - return adrs - - ips = getIP() - if ips == None or len(ips) == 0: - info += "The repository server is running, but the local device IP address could not be determined.\n\nYou can access the repository by pointing a browser to: http://DEVICE_IP:4444/" - self.reposository_url = None else: - ipstr = "" - for ip in ips: - ipstr += "http://"+str(ip)+":4444/\n" - self.reposository_url = ipstr + import socket + adrs.append(socket.gethostbyname(socket.gethostname())) - ms = "" if len(ips) == 1 else "es" - info += "The repository server is running at the following address"+ms+":\n [u][ref=link]"+ipstr+"[/ref][u]" - self.repository_screen.ids.repository_info.bind(on_ref_press=self.repository_link_action) + return adrs - self.repository_screen.ids.repository_enable_button.disabled = True - self.repository_screen.ids.repository_disable_button.disabled = False + ips = getIP() + if ips == None or len(ips) == 0: + info += "The repository server is running, but the local device IP address could not be determined.\n\nYou can access the repository by pointing a browser to: https://DEVICE_IP:4444/" + self.repository_url = None + else: + ipstr = "" + self.repository_url = None + for ip in ips: + ipurl = "https://" + str(ip) + ":4444/" + ipstr += "[u][ref=link]"+ipurl+"[/ref][u]\n" + if self.repository_url == None: + self.repository_url = ipurl + self.rnode_flasher_url = ipurl+"mirrors/rnode-flasher/RNode_Flasher.html" + + ms = "" if len(ips) == 1 else "es" + info += "The repository server is running at the following address" + ms +":\n\n"+ipstr + self.repository_screen.ids.repository_info.bind(on_ref_press=self.repository_link_action) + + def cb(dt): + self.repository_screen.ids.repository_enable_button.disabled = True + self.repository_screen.ids.repository_disable_button.disabled = False + if hasattr(self, "wants_flasher_launch") and self.wants_flasher_launch == True: + self.wants_flasher_launch = False + if self.rnode_flasher_url != None: + def lj(): + webbrowser.open(self.rnode_flasher_url) + threading.Thread(target=lj, daemon=True).start() + + Clock.schedule_once(cb, 0.1) else: self.repository_screen.ids.repository_enable_button.disabled = False self.repository_screen.ids.repository_disable_button.disabled = True - info += "\n" + info += "" self.repository_screen.ids.repository_info.text = info def repository_start_action(self, sender=None): @@ -2646,7 +4279,7 @@ class SidebandApp(MDApp): Clock.schedule_once(self.repository_update_info, 1.0) def repository_stop_action(self, sender=None): - self.reposository_url = None + self.repository_url = None self.sideband.stop_webshare() Clock.schedule_once(self.repository_update_info, 0.75) @@ -2654,39 +4287,85 @@ class SidebandApp(MDApp): def update_job(sender=None): try: import requests + ### RNode Firmwares ########### + if True: + downloads = [] + try: + release_url = "https://api.github.com/repos/markqvist/rnode_firmware/releases" + with requests.get(release_url) as response: + releases = response.json() + release = releases[0] + assets = release["assets"] + for asset in assets: + if asset["name"].lower().startswith("rnode_firmware"): + fw_url = asset["browser_download_url"] + pkgname = asset["name"] + fw_version = release["tag_name"] + RNS.log(f"Found version {fw_version} artefact {pkgname} at {fw_url}", RNS.LOG_DEBUG) + downloads.append([fw_url, pkgname, fw_version]) - # Get release info - apk_version = None - apk_url = None - pkgname = None - try: - release_url = "https://api.github.com/repos/markqvist/sideband/releases" - with requests.get(release_url) as response: - releases = response.json() - release = releases[0] - assets = release["assets"] - for asset in assets: - if asset["name"].lower().endswith(".apk"): - apk_url = asset["browser_download_url"] - pkgname = asset["name"] - apk_version = release["tag_name"] - RNS.log(f"Found version {apk_version} artefact {pkgname} at {apk_url}") - except Exception as e: - self.repository_screen.ids.repository_update.text = f"Downloading release info failed with the error:\n"+str(e) - return + except Exception as e: + self.repository_screen.ids.repository_update.text = f"Downloading RNode firmware release info failed with the error:\n"+str(e) + return - self.repository_screen.ids.repository_update.text = "Downloading: "+str(apk_url) - with requests.get(apk_url, stream=True) as response: - with open("./dl_tmp", "wb") as tmp_file: - cs = 32*1024 - tds = 0 - for chunk in response.iter_content(chunk_size=cs): - tmp_file.write(chunk) - tds += cs - self.repository_screen.ids.repository_update.text = "Downloaded "+RNS.prettysize(tds)+" of "+str(pkgname) + try: + for download in downloads: + fw_url = download[0] + pkgname = download[1] + self.repository_screen.ids.repository_update.text = "Downloading: "+str(pkgname) + with requests.get(fw_url, stream=True) as response: + with open("./dl_tmp", "wb") as tmp_file: + cs = 32*1024 + tds = 0 + for chunk in response.iter_content(chunk_size=cs): + tmp_file.write(chunk) + tds += cs + self.repository_screen.ids.repository_update.text = "Downloaded "+RNS.prettysize(tds)+" of "+str(pkgname) + + os.rename("./dl_tmp", f"{self.sideband.webshare_dir}/pkg/{pkgname}") + self.repository_screen.ids.repository_update.text = f"Added {pkgname} to the repository!" + + except Exception as e: + self.repository_screen.ids.repository_update.text = f"Downloading RNode firmware failed with the error:\n"+str(e) + return + + ### Sideband APK File ######### + if True: + # Get release info + apk_version = None + apk_url = None + pkgname = None + try: + release_url = "https://api.github.com/repos/markqvist/sideband/releases" + with requests.get(release_url) as response: + releases = response.json() + release = releases[0] + assets = release["assets"] + for asset in assets: + if asset["name"].lower().endswith(".apk"): + apk_url = asset["browser_download_url"] + pkgname = asset["name"] + apk_version = release["tag_name"] + RNS.log(f"Found version {apk_version} artefact {pkgname} at {apk_url}", RNS.LOG_DEBUG) + except Exception as e: + self.repository_screen.ids.repository_update.text = f"Downloading Sideband APK release info failed with the error:\n"+str(e) + return + + self.repository_screen.ids.repository_update.text = "Downloading: "+str(pkgname) + with requests.get(apk_url, stream=True) as response: + with open("./dl_tmp", "wb") as tmp_file: + cs = 32*1024 + tds = 0 + for chunk in response.iter_content(chunk_size=cs): + tmp_file.write(chunk) + tds += cs + self.repository_screen.ids.repository_update.text = "Downloaded "+RNS.prettysize(tds)+" of "+str(pkgname) + + os.rename("./dl_tmp", f"{self.sideband.webshare_dir}/pkg/{pkgname}") + self.repository_screen.ids.repository_update.text = f"Added {pkgname} to the repository!" + + self.repository_screen.ids.repository_update.text = f"Repository contents updated successfully!" - os.rename("./dl_tmp", f"./share/pkg/{pkgname}") - self.repository_screen.ids.repository_update.text = f"Added {pkgname} to the repository!" except Exception as e: self.repository_screen.ids.repository_update.text = f"Downloading contents failed with the error:\n"+str(e) @@ -2703,15 +4382,7 @@ class SidebandApp(MDApp): self.root.ids.screen_manager.add_widget(self.repository_screen) self.repository_screen.ids.repository_scrollview.effect_cls = ScrollEffect - self.repository_update_info() - - if not RNS.vendor.platformutils.is_android(): - self.widget_hide(self.repository_screen.ids.repository_enable_button) - self.widget_hide(self.repository_screen.ids.repository_disable_button) - self.widget_hide(self.repository_screen.ids.repository_download_button) - self.repository_screen.ids.repository_info.text = "\nThe [b]Repository Webserver[/b] feature is currently only available on mobile devices." - self.repository_ready = True def close_repository_action(self, sender=None): @@ -2720,900 +4391,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" - info += str(RNS.Reticulum.configpath) - 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) - - 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 - - self.sideband.save_configuration() - - 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_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_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_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_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_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_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_framebuffer.bind(active=self.hardware_rnode_framebuffer_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] - 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 ###################################### @@ -3621,90 +4425,59 @@ 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 ###################################### 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 - info = "Your primary encryption keys are stored in a Reticulum Identity within the Sideband app. If you want to backup this Identity for later use on this or another device, you can export it as a plain text blob, with the key data encoded in Base32 format. This will allow you to restore your address in Sideband or other LXMF clients at a later point.\n\n[b]Warning![/b] Anyone that gets access to the key data will be able to control your LXMF address, impersonate you, and read your messages. In is [b]extremely important[/b] that you keep the Identity data secure if you export it.\n\nBefore displaying or exporting your Identity data, make sure that no machine or person in your vicinity is able to see, copy or record your device screen or similar." - - 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 + 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 @@ -3713,91 +4486,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 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 ###################################### @@ -3915,6 +4607,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( @@ -3956,6 +4652,103 @@ class SidebandApp(MDApp): ate_dialog.open() + ### Utilities Screen + ###################################### + + def utilities_init(self): + if not self.utilities_ready: + self.utilities_screen = Utilities(self) + self.utilities_ready = True + + def utilities_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 = "utilities_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 utilities_action(self, sender=None, direction="left"): + if self.utilities_ready: + self.utilities_open(direction=direction) + else: + self.loader_action(direction=direction) + def final(dt): + self.utilities_init() + def o(dt): + self.utilities_open(no_transition=True) + Clock.schedule_once(o, ll_ot) + Clock.schedule_once(final, ll_ft) + + def close_sub_utilities_action(self, sender=None): + 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, dial_on_complete=None): + 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 + + 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) + + 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) + else: + self.loader_action(direction=direction) + def final(dt): + self.voice_init() + def o(dt): + 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) + + def voice_answer_action(self, sender=None): + if self.sideband.voice_running: + 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: + if self.sideband.telephone.is_ringing or self.sideband.telephone.is_in_call: + self.sideband.telephone.hangup() + ### Telemetry Screen ###################################### @@ -4068,7 +4861,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" @@ -4078,10 +4871,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." @@ -4560,8 +5353,23 @@ class SidebandApp(MDApp): self.map_action() self.map_show(location) - def map_display_telemetry(self, sender=None): - self.object_details_action(sender) + def map_display_telemetry(self, sender=None, event=None): + alt_event = False + if sender != None: + if hasattr(sender, "last_touch"): + if hasattr(sender.last_touch, "button"): + if sender.last_touch.button == "right": + alt_event = True + + if alt_event: + try: + if hasattr(sender, "source_dest"): + self.sideband.request_latest_telemetry(from_addr=sender.source_dest) + toast("Telemetry request sent") + except Exception as e: + RNS.log(f"Could not request telemetry update: {e}", RNS.LOG_ERROR) + else: + self.object_details_action(sender) def map_display_own_telemetry(self, sender=None): self.sideband.update_telemetry() @@ -4570,22 +5378,22 @@ class SidebandApp(MDApp): def close_sub_map_action(self, sender=None): self.map_action(direction="right") - def object_details_action(self, sender=None, from_conv=False, from_telemetry=False, source_dest=None, direction="left"): + def object_details_action(self, sender=None, from_conv=False, from_objects=False, from_telemetry=False, source_dest=None, direction="left"): if self.root.ids.screen_manager.has_screen("object_details_screen"): - self.object_details_open(sender=sender, from_conv=from_conv, from_telemetry=from_telemetry, source_dest=source_dest, direction=direction) + self.object_details_open(sender=sender, from_conv=from_conv, from_objects=from_objects, from_telemetry=from_telemetry, source_dest=source_dest, direction=direction) else: self.loader_action(direction=direction) def final(dt): self.object_details_init() def o(dt): - self.object_details_open(sender=sender, from_conv=from_conv, from_telemetry=from_telemetry, source_dest=source_dest, no_transition=True) + self.object_details_open(sender=sender, from_conv=from_conv, from_objects=from_objects, from_telemetry=from_telemetry, source_dest=source_dest, no_transition=True) Clock.schedule_once(o, ll_ot) Clock.schedule_once(final, ll_ft) def object_details_init(self): self.object_details_screen = ObjectDetails(self) - def object_details_open(self, sender=None, from_conv=False, from_telemetry=False, source_dest=None, direction="left", no_transition=False): + def object_details_open(self, sender=None, from_conv=False, from_objects=False, from_telemetry=False, source_dest=None, direction="left", no_transition=False): if no_transition: self.root.ids.screen_manager.transition = self.no_transition else: @@ -4606,10 +5414,13 @@ class SidebandApp(MDApp): self.root.ids.nav_drawer.set_state("closed") if telemetry_source == None: - self.conversations_action(direction="right") + if self.include_objects and not self.include_conversations: + self.objects_action(direction="right") + else: + self.conversations_action(direction="right") else: - Clock.schedule_once(lambda dt: self.object_details_screen.set_source(telemetry_source, from_conv=from_conv, from_telemetry=from_telemetry), 0.0) + Clock.schedule_once(lambda dt: self.object_details_screen.set_source(telemetry_source, from_conv=from_conv, from_objects=from_objects, from_telemetry=from_telemetry), 0.0) def vj(dt): self.root.ids.screen_manager.current = "object_details_screen" @@ -4742,7 +5553,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) @@ -4751,6 +5562,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"] @@ -4798,104 +5613,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 and macOS. 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 set of cryptographic keys. These keys are then used to create an LXMF address for your use. Any other endpoint in [i]any[/i] Reticulum network will be able to send data to this 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. The 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.""" - - guide_text4 = """ -[size=18dp][b]Becoming Reachable[/b][/size][size=5dp]\n \n[/size]To establish reachability for any Reticulum address on a network, an [i]announce[/i] must be sent. Sideband does not do this automatically by default, but can be configured to do so every time the program starts. To 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. Reticulum 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. In most cases it will not be possible to know what path data takes in a Reticulum network, and no transmitted packets carries any identifying characteristics, apart from a destination address. There is no source addresses in Reticulum. As 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. If 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 anonymous communication system with Reticulum and LXMF clients.""" - - guide_text8 = """ -[size=18dp][b]Keyboard Shortcuts[/b][/size][size=5dp]\n \n[/size] - Ctrl+Q or Ctrl-W Shut down Sideband - - Ctrl-D or Ctrl-S Send message - - Ctrl-R Show Conversations - - Ctrl-L Show Announce Stream - - Ctrl-M Show Situation Map - - Ctrl-T Show Telemetry Setup - - Ctrl-N New conversation - - Ctrl-G Show guide""" - - guide_text9 = """ -[size=18dp][b]Sow Seeds Of Freedom[/b][/size][size=5dp]\n \n[/size]It took me more than seven years to design and built 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_text2 - info3 = guide_text3 - info4 = guide_text4 - info5 = guide_text5 - info6 = guide_text6 - info7 = guide_text7 - info8 = guide_text8 - 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]" - 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_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) ################################################# @@ -4920,7 +5648,7 @@ Thank you very much for using Free Communications Systems. self.root.ids.screen_manager.transition = self.slide_transition self.root.ids.screen_manager.transition.direction = direction - info = "The [b]Local Broadcasts[/b] feature will allow you to send and listen for local broadcast transmissions on connected radio, LoRa and WiFi interfaces.\n\n[b]Local Broadcasts[/b] makes it easy to establish public information exchange with anyone in direct radio range, or even with large areas far away using the [i]Remote Broadcast Repeater[/i] feature.\n\nThese features are not yet implemented in Sideband.\n\nWant it faster? Go to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project." + info = "The [b]Local Broadcasts[/b] feature will allow you to send and listen for local broadcast transmissions on all connected interfaces.\n\n[b]Local Broadcasts[/b] makes it easy to establish public information exchange with anyone in direct radio range, or even with large areas far away using the [i]Remote Broadcast Repeater[/i] feature.\n\nThese features are not yet implemented in Sideband.\n\nWant it faster? Go to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project." if self.theme_cls.theme_style == "Dark": info = "[color=#"+dark_theme_text_color+"]"+info+"[/color]" self.broadcasts_screen.ids.broadcasts_info.text = info @@ -4951,10 +5679,14 @@ class CustomOneLineIconListItem(OneLineIconListItem): class DialogItem(OneLineIconListItem): divider = None + icon = StringProperty() class MDMapIconButton(MDIconButton): pass +class UIScaling(BoxLayout): + pass + if not args.daemon: from kivy.base import ExceptionManager, ExceptionHandler class SidebandExceptionHandler(ExceptionHandler): @@ -4972,13 +5704,37 @@ if not args.daemon: def run(): if args.daemon: RNS.log("Starting Sideband in daemon mode") - sideband = SidebandCore(None, is_client=False, verbose=(args.verbose or __debug_build__), is_daemon=True) + sideband = SidebandCore( + None, + config_path=args.config, + is_client=False, + verbose=(args.verbose or __debug_build__), + quiet=(args.interactive and not args.verbose), + is_daemon=True, + rns_config_path=args.rnsconfig, + ) + + sideband.version_str = "v"+__version__+" "+__variant__ sideband.start() - while True: - time.sleep(5) + + if args.interactive: + while not sideband.getstate("core.started") == True: time.sleep(0.1) + 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) else: ExceptionManager.add_handler(SidebandExceptionHandler()) SidebandApp().run() if __name__ == "__main__": run() + +if __name__ == "sbapp.main": + run() 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 diff --git a/sbapp/patches/AndroidManifest.tmpl.xml b/sbapp/patches/AndroidManifest.tmpl.xml index 140814c..9ff83ec 100644 --- a/sbapp/patches/AndroidManifest.tmpl.xml +++ b/sbapp/patches/AndroidManifest.tmpl.xml @@ -3,7 +3,6 @@ com.gamemaker.game --> @@ -46,16 +45,7 @@ {{ args.extra_manifest_xml }} - - + {% for l in args.android_used_libs %} @@ -83,19 +74,22 @@ {% endif %} > - {% if args.launcher %} + {% if args.launcher %} - {% else %} - - {% endif %} + {% if args.home_app %} + + + {% endif %} + + {%- if args.intent_filters -%} {{- args.intent_filters -}} {%- endif -%} @@ -127,6 +121,12 @@ {% endfor %} + + + + + + {% if args.billing_pubkey %} diff --git a/sbapp/patches/PythonActivity.java b/sbapp/patches/PythonActivity.java new file mode 100644 index 0000000..41b9460 --- /dev/null +++ b/sbapp/patches/PythonActivity.java @@ -0,0 +1,651 @@ +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 Intent startIntent = null; + + public String getAppRoot() { + String app_root = getFilesDir().getAbsolutePath() + "/app"; + return app_root; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + try { this.startIntent = getIntent(); } + catch (Exception e) { Log.e(TAG, "Failed to get pending intent on activity create"); } + + 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/patches/PythonService.java b/sbapp/patches/PythonService.java index d59fe1c..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; @@ -113,7 +137,7 @@ public class PythonService extends Service implements Runnable { Context context = getApplicationContext(); Intent contextIntent = new Intent(context, PythonActivity.class); PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent, - PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { notification = new Notification( @@ -142,13 +166,13 @@ public class PythonService extends Service implements Runnable { manager.createNotificationChannel(chan); Notification.Builder builder = new Notification.Builder(context, NOTIFICATION_CHANNEL_ID); - builder.setContentTitle("Sideband Active"); - // builder.setContentText("Reticulum Active"); + builder.setContentTitle("Reticulum available"); + // builder.setContentText("Reticulum available"); builder.setContentIntent(pIntent); // builder.setOngoing(true); String files_path = context.getFilesDir().getPath(); - Bitmap icon_bitmap = BitmapFactory.decodeFile(files_path+"/app/assets/notification_icon.png"); + Bitmap icon_bitmap = BitmapFactory.decodeFile(files_path+"/app/assets/notification_icon_black.png"); Icon service_icon = Icon.createWithBitmap(icon_bitmap); // builder.setSmallIcon(context.getApplicationInfo().icon); builder.setSmallIcon(service_icon); diff --git a/sbapp/patches/device_filter.xml b/sbapp/patches/device_filter.xml index b003690..ea67a38 100644 --- a/sbapp/patches/device_filter.xml +++ b/sbapp/patches/device_filter.xml @@ -39,4 +39,7 @@ + + + \ No newline at end of file diff --git a/sbapp/patches/intent-filter.xml b/sbapp/patches/intent-filter.xml index 48850af..37c4df6 100644 --- a/sbapp/patches/intent-filter.xml +++ b/sbapp/patches/intent-filter.xml @@ -13,11 +13,26 @@ - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sbapp/plyer/__init__.py b/sbapp/plyer/__init__.py index ab87901..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', @@ -13,11 +13,15 @@ __all__ = ( 'stt', 'temperature', 'tts', 'uniqueid', 'vibrator', 'wifi', 'devicename' ) -__version__ = '2.1.0.dev0' +__version__ = '2.2.0.dev0' - -from plyer import facades -from plyer.utils import Proxy +import RNS +if RNS.vendor.platformutils.is_android(): + from plyer import facades + from plyer.utils import Proxy +else: + from sbapp.plyer import facades + from sbapp.plyer.utils import Proxy #: Accelerometer proxy to :class:`plyer.facades.Accelerometer` accelerometer = Proxy('accelerometer', facades.Accelerometer) @@ -25,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 c1e2560..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', @@ -14,38 +14,74 @@ __all__ = ('Accelerometer', 'Audio', 'Barometer', 'Battery', 'Call', 'Camera', 'Processors', 'StoragePath', 'Keystore', 'Bluetooth', 'Screenshot', 'STT', 'DeviceName') -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 -from plyer.facades.camera import Camera -from plyer.facades.compass import Compass -from plyer.facades.email import Email -from plyer.facades.filechooser import FileChooser -from plyer.facades.flash import Flash -from plyer.facades.gps import GPS -from plyer.facades.gravity import Gravity -from plyer.facades.gyroscope import Gyroscope -from plyer.facades.irblaster import IrBlaster -from plyer.facades.light import Light -from plyer.facades.proximity import Proximity -from plyer.facades.orientation import Orientation -from plyer.facades.notification import Notification -from plyer.facades.sms import Sms -from plyer.facades.stt import STT -from plyer.facades.tts import TTS -from plyer.facades.uniqueid import UniqueID -from plyer.facades.vibrator import Vibrator -from plyer.facades.wifi import Wifi -from plyer.facades.temperature import Temperature -from plyer.facades.humidity import Humidity -from plyer.facades.spatialorientation import SpatialOrientation -from plyer.facades.brightness import Brightness -from plyer.facades.keystore import Keystore -from plyer.facades.storagepath import StoragePath -from plyer.facades.bluetooth import Bluetooth -from plyer.facades.processors import Processors -from plyer.facades.cpu import CPU -from plyer.facades.screenshot import Screenshot -from plyer.facades.devicename import DeviceName +import RNS +if RNS.vendor.platformutils.is_android(): + from plyer.facades.accelerometer import Accelerometer + from plyer.facades.barometer import Barometer + from plyer.facades.battery import Battery + from plyer.facades.call import Call + from plyer.facades.camera import Camera + from plyer.facades.compass import Compass + from plyer.facades.email import Email + from plyer.facades.filechooser import FileChooser + from plyer.facades.flash import Flash + from plyer.facades.gps import GPS + from plyer.facades.gravity import Gravity + from plyer.facades.gyroscope import Gyroscope + from plyer.facades.irblaster import IrBlaster + from plyer.facades.light import Light + from plyer.facades.proximity import Proximity + from plyer.facades.orientation import Orientation + from plyer.facades.notification import Notification + from plyer.facades.sms import Sms + from plyer.facades.stt import STT + from plyer.facades.tts import TTS + from plyer.facades.uniqueid import UniqueID + from plyer.facades.vibrator import Vibrator + from plyer.facades.wifi import Wifi + from plyer.facades.temperature import Temperature + from plyer.facades.humidity import Humidity + from plyer.facades.spatialorientation import SpatialOrientation + from plyer.facades.brightness import Brightness + from plyer.facades.keystore import Keystore + from plyer.facades.storagepath import StoragePath + from plyer.facades.bluetooth import Bluetooth + from plyer.facades.processors import Processors + from plyer.facades.cpu import CPU + from plyer.facades.screenshot import Screenshot + from plyer.facades.devicename import DeviceName +else: + from sbapp.plyer.facades.accelerometer import Accelerometer + from sbapp.plyer.facades.barometer import Barometer + from sbapp.plyer.facades.battery import Battery + from sbapp.plyer.facades.call import Call + from sbapp.plyer.facades.camera import Camera + from sbapp.plyer.facades.compass import Compass + from sbapp.plyer.facades.email import Email + from sbapp.plyer.facades.filechooser import FileChooser + from sbapp.plyer.facades.flash import Flash + from sbapp.plyer.facades.gps import GPS + from sbapp.plyer.facades.gravity import Gravity + from sbapp.plyer.facades.gyroscope import Gyroscope + from sbapp.plyer.facades.irblaster import IrBlaster + from sbapp.plyer.facades.light import Light + from sbapp.plyer.facades.proximity import Proximity + from sbapp.plyer.facades.orientation import Orientation + from sbapp.plyer.facades.notification import Notification + from sbapp.plyer.facades.sms import Sms + from sbapp.plyer.facades.stt import STT + from sbapp.plyer.facades.tts import TTS + from sbapp.plyer.facades.uniqueid import UniqueID + from sbapp.plyer.facades.vibrator import Vibrator + from sbapp.plyer.facades.wifi import Wifi + from sbapp.plyer.facades.temperature import Temperature + from sbapp.plyer.facades.humidity import Humidity + from sbapp.plyer.facades.spatialorientation import SpatialOrientation + from sbapp.plyer.facades.brightness import Brightness + from sbapp.plyer.facades.keystore import Keystore + from sbapp.plyer.facades.storagepath import StoragePath + from sbapp.plyer.facades.bluetooth import Bluetooth + from sbapp.plyer.facades.processors import Processors + from sbapp.plyer.facades.cpu import CPU + from sbapp.plyer.facades.screenshot import Screenshot + from sbapp.plyer.facades.devicename import DeviceName diff --git a/sbapp/plyer/facades/audio.py b/sbapp/plyer/facades/audio.py deleted file mode 100644 index c5e1db5..0000000 --- a/sbapp/plyer/facades/audio.py +++ /dev/null @@ -1,103 +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 NotImplementedError() - - def _stop(self): - raise NotImplementedError() - - def _play(self): - raise NotImplementedError() diff --git a/sbapp/plyer/facades/humidity.py b/sbapp/plyer/facades/humidity.py index ac63333..8d72239 100644 --- a/sbapp/plyer/facades/humidity.py +++ b/sbapp/plyer/facades/humidity.py @@ -4,7 +4,7 @@ class Humidity: With method `enable` you can turn on Humidity sensor and 'disable' method stops the sensor. Use property `tell` to get humidity value. - + Supported Platforms ------------------- Android diff --git a/sbapp/plyer/facades/maps.py b/sbapp/plyer/facades/maps.py new file mode 100644 index 0000000..ba8d5fe --- /dev/null +++ b/sbapp/plyer/facades/maps.py @@ -0,0 +1,88 @@ +''' +Maps +======= +The :class:`Maps` creates a client for accessing the default Maps API. + +Holds features such as opening a location by +address & latitude/longitude, create queries, or find directions between +two points + +Simple Examples +--------------- + +Perform a search:: + + >>> from plyer import maps + >>> maps.search('Mexican Restaurant') + >>> maps.search('Taco Bell', latitude=38.5810606, longitude=-121.493895) + +Get directions to a location:: + + >>> from plyer import maps + >>> maps.route('Cupertino', 'San Francisco') + >>> maps.route('41.9156316,-72.6130726', '42.65228271484,-73.7577362060') + +View a specific location:: + + >>> from plyer import maps + >>> maps.open_by_address('25 Leshin Lane, Hightstown, NJ') + >>> maps.open_by_lat_long(30.451468, -91.187149) + >>> maps.open_by_lat_long(30.451468, -91.187149, name='Home') + +Supported Platforms +------------------- +macOS, iOS +--------------- +''' + + +class Maps: + ''' + Maps facade. + ''' + + def open_by_address(self, address, **kwargs): + ''' + Open the specificed location by address in the default Maps API + ''' + self._open_by_address(address, **kwargs) + + def open_by_lat_long(self, latitude, longitude, **kwargs): + ''' + Open the specificed location by latitude & longitude coordinates + in the default Maps API + ''' + self._open_by_lat_long(latitude, longitude, **kwargs) + + def search(self, query, **kwargs): + ''' + The query. This parameter is treated as if its value had been typed + into the Maps search field by the user. + + Note that query=* is not supported + ''' + self._search(query, **kwargs) + + def route(self, saddr, daddr, **kwargs): + ''' + To provide navigation directions from one location to another. + + :param saddr: The source address to be used as the starting + point for directions. + + :param daddr: The destination address to be used as the + destination point for directions. + ''' + self._route(saddr, daddr, **kwargs) + + def _open_by_address(self, address, **kwargs): + raise NotImplementedError() + + def _open_by_lat_long(self, latitude, longitude, **kwargs): + raise NotImplementedError() + + def _search(self, query, **kwargs): + raise NotImplementedError() + + def _route(self, saddr, daddr, **kwargs): + raise NotImplementedError() diff --git a/sbapp/plyer/facades/notification.py b/sbapp/plyer/facades/notification.py index 71c7d53..db0d227 100644 --- a/sbapp/plyer/facades/notification.py +++ b/sbapp/plyer/facades/notification.py @@ -45,8 +45,8 @@ class Notification: Notification facade. ''' - def notify(self, title='', message='', app_name='', app_icon='', notification_icon=None, - timeout=10, ticker='', toast=False, hints={}, context_override=None): + def notify(self, title='', message='', app_name='', app_icon='', + timeout=10, ticker='', toast=False, hints={}): ''' Send a notification. @@ -83,8 +83,8 @@ class Notification: self._notify( title=title, message=message, - app_icon=app_icon, app_name=app_name, notification_icon=notification_icon, - timeout=timeout, ticker=ticker, toast=toast, hints=hints, context_override=context_override + app_icon=app_icon, app_name=app_name, + timeout=timeout, ticker=ticker, toast=toast, hints=hints ) # private diff --git a/sbapp/plyer/facades/orientation.py b/sbapp/plyer/facades/orientation.py index 56ea0ba..077de55 100644 --- a/sbapp/plyer/facades/orientation.py +++ b/sbapp/plyer/facades/orientation.py @@ -30,7 +30,7 @@ To set sensor:: Supported Platforms ------------------- -Android +Android, Linux ''' diff --git a/sbapp/plyer/facades/sms.py b/sbapp/plyer/facades/sms.py index 0e58f44..5940822 100644 --- a/sbapp/plyer/facades/sms.py +++ b/sbapp/plyer/facades/sms.py @@ -23,7 +23,7 @@ To send sms:: Supported Platforms ------------------- -Android, iOS +Android, iOS, macOS ''' @@ -33,17 +33,23 @@ class Sms: Sms facade. ''' - def send(self, recipient, message): + def send(self, recipient, message, mode=None, **kwargs): ''' Send SMS or open SMS interface. + Includes optional `mode` parameter for macOS that can be set to + `'SMS'` if carrier-activated device is correctly paired and + configured to macOS. :param recipient: The receiver :param message: the message + :param mode: (optional, macOS only), can be set to 'iMessage' + (default) or 'SMS' :type recipient: number :type message: str + :type mode: str ''' - self._send(recipient=recipient, message=message) + self._send(recipient=recipient, message=message, mode=mode, **kwargs) # private diff --git a/sbapp/plyer/platforms/android/accelerometer.py b/sbapp/plyer/platforms/android/accelerometer.py index 00c73cf..7754579 100644 --- a/sbapp/plyer/platforms/android/accelerometer.py +++ b/sbapp/plyer/platforms/android/accelerometer.py @@ -70,7 +70,7 @@ class AndroidAccelerometer(Accelerometer): return (None, None, None) def __del__(self): - if(self.bState): + if self.bState: self._disable() super().__del__() diff --git a/sbapp/plyer/platforms/android/audio.py b/sbapp/plyer/platforms/android/audio.py deleted file mode 100644 index 9f000ff..0000000 --- a/sbapp/plyer/platforms/android/audio.py +++ /dev/null @@ -1,58 +0,0 @@ -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 = '/sdcard/testrecorder.3gp' - super().__init__(file_path or default_path) - - self._recorder = None - self._player = None - - def _start(self): - self._recorder = MediaRecorder() - self._recorder.setAudioSource(AudioSource.DEFAULT) - self._recorder.setOutputFormat(OutputFormat.DEFAULT) - self._recorder.setAudioEncoder(AudioEncoder.DEFAULT) - self._recorder.setOutputFile(self.file_path) - - self._recorder.prepare() - self._recorder.start() - - def _stop(self): - if self._recorder: - self._recorder.stop() - self._recorder.release() - self._recorder = None - - if self._player: - self._player.stop() - self._player.release() - self._player = None - - def _play(self): - self._player = MediaPlayer() - self._player.setDataSource(self.file_path) - self._player.prepare() - self._player.start() - - -def instance(): - return AndroidAudio() diff --git a/sbapp/plyer/platforms/android/camera.py b/sbapp/plyer/platforms/android/camera.py index 19707bd..3384a66 100644 --- a/sbapp/plyer/platforms/android/camera.py +++ b/sbapp/plyer/platforms/android/camera.py @@ -14,7 +14,7 @@ Uri = autoclass('android.net.Uri') class AndroidCamera(Camera): def _take_picture(self, on_complete, filename=None): - assert(on_complete is not None) + assert on_complete is not None self.on_complete = on_complete self.filename = filename android.activity.unbind(on_activity_result=self._on_activity_result) @@ -26,7 +26,7 @@ class AndroidCamera(Camera): activity.startActivityForResult(intent, 0x123) def _take_video(self, on_complete, filename=None): - assert(on_complete is not None) + assert on_complete is not None self.on_complete = on_complete self.filename = filename android.activity.unbind(on_activity_result=self._on_activity_result) diff --git a/sbapp/plyer/platforms/android/compass.py b/sbapp/plyer/platforms/android/compass.py index fcf0483..5bb16c6 100644 --- a/sbapp/plyer/platforms/android/compass.py +++ b/sbapp/plyer/platforms/android/compass.py @@ -110,7 +110,7 @@ class AndroidCompass(Compass): return (None, None, None, None, None, None) def __del__(self): - if(self.bState): + if self.bState: self._disable() super().__del__() diff --git a/sbapp/plyer/platforms/android/filechooser.py b/sbapp/plyer/platforms/android/filechooser.py index b809ccb..b8c943c 100644 --- a/sbapp/plyer/platforms/android/filechooser.py +++ b/sbapp/plyer/platforms/android/filechooser.py @@ -43,7 +43,7 @@ using that result will use an incorrect one i.e. the default value of .. versionadded:: 1.4.0 ''' -from os.path import join, basename +from os.path import join from random import randint from android import activity, mActivity @@ -62,6 +62,8 @@ Long = autoclass('java.lang.Long') IMedia = autoclass('android.provider.MediaStore$Images$Media') VMedia = autoclass('android.provider.MediaStore$Video$Media') AMedia = autoclass('android.provider.MediaStore$Audio$Media') +Files = autoclass('android.provider.MediaStore$Files') +FileOutputStream = autoclass('java.io.FileOutputStream') class AndroidFileChooser(FileChooser): @@ -74,6 +76,7 @@ class AndroidFileChooser(FileChooser): # filechooser activity <-> result pair identification select_code = None + save_code = None # default selection value selection = None @@ -105,6 +108,7 @@ class AndroidFileChooser(FileChooser): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.select_code = randint(123456, 654321) + self.save_code = randint(123456, 654321) self.selection = None # bind a function for a response from filechooser activity @@ -139,9 +143,11 @@ class AndroidFileChooser(FileChooser): # create Intent for opening file_intent = Intent(Intent.ACTION_GET_CONTENT) - if not self.selected_mime_type or \ - type(self.selected_mime_type) != str or \ - self.selected_mime_type not in self.mime_type: + if ( + not self.selected_mime_type + or not isinstance(self.selected_mime_type, str) + or self.selected_mime_type not in self.mime_type + ): file_intent.setType("*/*") else: file_intent.setType(self.mime_type[self.selected_mime_type]) @@ -163,6 +169,38 @@ class AndroidFileChooser(FileChooser): self.select_code ) + def _save_file(self, **kwargs): + self._save_callback = kwargs.pop("callback") + + title = kwargs.pop("title", None) + + self.selected_mime_type = \ + kwargs.pop("filters")[0] if "filters" in kwargs else "" + + file_intent = Intent(Intent.ACTION_CREATE_DOCUMENT) + if ( + not self.selected_mime_type + or not isinstance(self.selected_mime_type, str) + or self.selected_mime_type not in self.mime_type + ): + file_intent.setType("*/*") + else: + file_intent.setType(self.mime_type[self.selected_mime_type]) + file_intent.addCategory( + Intent.CATEGORY_OPENABLE + ) + + if title: + file_intent.putExtra(Intent.EXTRA_TITLE, title) + + mActivity.startActivityForResult( + Intent.createChooser(file_intent, cast( + 'java.lang.CharSequence', + String("FileChooser") + )), + self.save_code + ) + def _on_activity_result(self, request_code, result_code, data): ''' Listener for ``android.app.Activity.onActivityResult()`` assigned @@ -171,28 +209,41 @@ class AndroidFileChooser(FileChooser): .. versionadded:: 1.4.0 ''' - # not our response - if request_code != self.select_code: + # bad data + if data is None: return if result_code != Activity.RESULT_OK: # The action had been cancelled. return - selection = [] - # Process multiple URI if multiple files selected - try: - for count in range(data.getClipData().getItemCount()): - ele = self._resolve_uri( - data.getClipData().getItemAt(count).getUri()) or [] - selection.append(ele) - except Exception: - selection = [self._resolve_uri(data.getData()), ] + if request_code == self.select_code: + selection = [] + # Process multiple URI if multiple files selected + try: + for count in range(data.getClipData().getItemCount()): + ele = self._resolve_uri( + data.getClipData().getItemAt(count).getUri()) or [] + selection.append(ele) + except Exception: + selection = [self._resolve_uri(data.getData()), ] - # return value to object - self.selection = selection - # return value via callback - self._handle_selection(selection) + # return value to object + self.selection = selection + # return value via callback + self._handle_selection(selection) + + elif request_code == self.save_code: + uri = data.getData() + + with mActivity.getContentResolver().openFileDescriptor( + uri, "w" + ) as pfd: + with FileOutputStream( + pfd.getFileDescriptor() + ) as fileOutputStream: + # return value via callback + self._save_callback(fileOutputStream) @staticmethod def _handle_external_documents(uri): @@ -206,28 +257,19 @@ class AndroidFileChooser(FileChooser): file_id = DocumentsContract.getDocumentId(uri) file_type, file_name = file_id.split(':') - # internal SD card mostly mounted as a files storage in phone - internal = storagepath.get_external_storage_dir() + primary_storage = storagepath.get_external_storage_dir() + sdcard_storage = storagepath.get_sdcard_dir() - # external (removable) SD card i.e. microSD - external = storagepath.get_sdcard_dir() - try: - external_base = basename(external) - except TypeError: - external_base = basename(internal) + directory = primary_storage - # resolve sdcard path - sd_card = internal - - # because external might have /storage/.../1 or other suffix - # and file_type might be only a part of the real folder in /storage - if file_type in external_base or external_base in file_type: - sd_card = external + if file_type == "primary": + directory = primary_storage elif file_type == "home": - sd_card = join(Environment.getExternalStorageDirectory( - ).getAbsolutePath(), Environment.DIRECTORY_DOCUMENTS) + directory = join(primary_storage, Environment.DIRECTORY_DOCUMENTS) + elif sdcard_storage and file_type in sdcard_storage: + directory = sdcard_storage - return join(sd_card, file_name) + return join(directory, file_name) @staticmethod def _handle_media_documents(uri): @@ -248,6 +290,11 @@ class AndroidFileChooser(FileChooser): uri = VMedia.EXTERNAL_CONTENT_URI elif file_type == 'audio': uri = AMedia.EXTERNAL_CONTENT_URI + + # Other file type was selected (probably in the Documents folder) + else: + uri = Files.getContentUri("external") + return file_name, selection, uri @staticmethod @@ -279,6 +326,23 @@ class AndroidFileChooser(FileChooser): .. versionadded:: 1.4.0 ''' + try: + download_dir = Environment.getExternalStoragePublicDirectory( + Environment.DIRECTORY_DOWNLOADS + ).getPath() + path = AndroidFileChooser._parse_content( + uri=uri, + projection=["_display_name"], + selection=None, + selection_args=None, + sort_order=None, + ) + return join(download_dir, path) + + except Exception: + import traceback + traceback.print_exc() + # known locations, differ between machines downloads = [ 'content://downloads/public_downloads', @@ -441,6 +505,8 @@ class AndroidFileChooser(FileChooser): mode = kwargs.pop('mode', None) if mode == 'open': self._open_file(**kwargs) + elif mode == 'save': + self._save_file(**kwargs) def instance(): diff --git a/sbapp/plyer/platforms/android/gps.py b/sbapp/plyer/platforms/android/gps.py index b173876..740b636 100644 --- a/sbapp/plyer/platforms/android/gps.py +++ b/sbapp/plyer/platforms/android/gps.py @@ -86,4 +86,4 @@ class AndroidGPS(GPS): def instance(): - return AndroidGPS() \ No newline at end of file + return AndroidGPS() diff --git a/sbapp/plyer/platforms/android/gyroscope.py b/sbapp/plyer/platforms/android/gyroscope.py index d6382b1..99b224e 100644 --- a/sbapp/plyer/platforms/android/gyroscope.py +++ b/sbapp/plyer/platforms/android/gyroscope.py @@ -110,7 +110,7 @@ class AndroidGyroscope(Gyroscope): return (None, None, None, None, None, None) def __del__(self): - if(self.bState): + if self.bState: self._disable() super().__del__() diff --git a/sbapp/plyer/platforms/android/notification.py b/sbapp/plyer/platforms/android/notification.py index ac9f76b..ee0de2d 100644 --- a/sbapp/plyer/platforms/android/notification.py +++ b/sbapp/plyer/platforms/android/notification.py @@ -154,10 +154,15 @@ class AndroidNotification(Notification): notification_intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) notification_intent.setAction(Intent.ACTION_MAIN) notification_intent.addCategory(Intent.CATEGORY_LAUNCHER) + if SDK_INT >= 23: + # FLAG_IMMUTABLE added in SDK 23, required since SDK 31: + pending_flags = PendingIntent.FLAG_IMMUTABLE + else: + pending_flags = 0 # get our application Activity pending_intent = PendingIntent.getActivity( - app_context, 0, notification_intent, 0 + app_context, 0, notification_intent, pending_flags ) notification.setContentIntent(pending_intent) @@ -179,8 +184,6 @@ class AndroidNotification(Notification): kwargs.get('title', '').encode('utf-8') ) icon = kwargs.get('app_icon') - notification_icon = kwargs.get('notification_icon') - context_override = kwargs.get('context_override') # decide whether toast only or proper notification if kwargs.get('toast'): diff --git a/sbapp/plyer/platforms/android/storagepath.py b/sbapp/plyer/platforms/android/storagepath.py index 788e3fc..d18ea61 100755 --- a/sbapp/plyer/platforms/android/storagepath.py +++ b/sbapp/plyer/platforms/android/storagepath.py @@ -3,14 +3,13 @@ Android Storage Path -------------------- ''' -from os import listdir, access, R_OK -from os.path import join from plyer.facades import StoragePath -from jnius import autoclass +from plyer.platforms.android import SDK_INT +from jnius import autoclass, cast from android import mActivity -Environment = autoclass('android.os.Environment') -Context = autoclass('android.content.Context') +Environment = autoclass("android.os.Environment") +Context = autoclass("android.content.Context") class AndroidStoragePath(StoragePath): @@ -25,17 +24,29 @@ class AndroidStoragePath(StoragePath): ''' .. versionadded:: 1.4.0 ''' - # folder in /storage/ that is readable - # and is not internal SD card path = None - for folder in listdir('/storage'): - folder = join('/storage', folder) - if folder in self._get_external_storage_dir(): - continue - if not access(folder, R_OK): - continue - path = folder - break + context = mActivity.getApplicationContext() + storage_manager = cast( + "android.os.storage.StorageManager", + context.getSystemService(Context.STORAGE_SERVICE), + ) + + if storage_manager is not None: + if SDK_INT >= 24: + storage_volumes = storage_manager.getStorageVolumes() + for storage_volume in storage_volumes: + if storage_volume.isRemovable(): + try: + directory = storage_volume.getDirectory() + except AttributeError: + directory = storage_volume.getPathFile() + path = directory.getAbsolutePath() + else: + storage_volumes = storage_manager.getVolumeList() + for storage_volume in storage_volumes: + if storage_volume.isRemovable(): + path = storage_volume.getPath() + return path def _get_root_dir(self): diff --git a/sbapp/plyer/platforms/ios/accelerometer.py b/sbapp/plyer/platforms/ios/accelerometer.py deleted file mode 100644 index 7250384..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 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 a5c5dc3..0000000 --- a/sbapp/plyer/platforms/ios/barometer.py +++ /dev/null @@ -1,31 +0,0 @@ -''' -iOS Barometer -------------- -''' - -from 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 818f0be..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 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 065869a..0000000 --- a/sbapp/plyer/platforms/ios/brightness.py +++ /dev/null @@ -1,27 +0,0 @@ -''' -iOS Brightness --------------- -''' - -from pyobjus import autoclass -from 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 c751399..0000000 --- a/sbapp/plyer/platforms/ios/call.py +++ /dev/null @@ -1,29 +0,0 @@ -''' -IOS Call ----------- -''' - -from 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 dfe5265..0000000 --- a/sbapp/plyer/platforms/ios/camera.py +++ /dev/null @@ -1,52 +0,0 @@ -from os import remove -from plyer.facades import Camera - -from 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 855484b..0000000 --- a/sbapp/plyer/platforms/ios/compass.py +++ /dev/null @@ -1,43 +0,0 @@ -''' -iOS Compass ------------ -''' - -from 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 e1cc7cb..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 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 ba49ba9..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 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 e4bedac..0000000 --- a/sbapp/plyer/platforms/ios/flash.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -""" -Flash ------ -""" -from 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 4c52738..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 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 a2b1be0..0000000 --- a/sbapp/plyer/platforms/ios/gravity.py +++ /dev/null @@ -1,31 +0,0 @@ -''' -iOS Gravity ------------ - -''' - -from 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 340653c..0000000 --- a/sbapp/plyer/platforms/ios/gyroscope.py +++ /dev/null @@ -1,55 +0,0 @@ -''' -iOS Gyroscope ---------------------- -''' - -from 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 289a5c0..0000000 --- a/sbapp/plyer/platforms/ios/keystore.py +++ /dev/null @@ -1,23 +0,0 @@ -from 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/sms.py b/sbapp/plyer/platforms/ios/sms.py deleted file mode 100644 index ef3acaa..0000000 --- a/sbapp/plyer/platforms/ios/sms.py +++ /dev/null @@ -1,43 +0,0 @@ -''' -IOS Sms ----------- -''' - -from 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 d42d0fa..0000000 --- a/sbapp/plyer/platforms/ios/spatialorientation.py +++ /dev/null @@ -1,31 +0,0 @@ -''' -iOS Spatial Orientation ------------------------ - -''' - -from 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 cd8bbc3..0000000 --- a/sbapp/plyer/platforms/ios/storagepath.py +++ /dev/null @@ -1,62 +0,0 @@ -''' -iOS Storage Path --------------------- -''' - -from 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 046769f..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 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 4d30249..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 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 922182c..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 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/accelerometer.py b/sbapp/plyer/platforms/linux/accelerometer.py index 7af283b..889de15 100644 --- a/sbapp/plyer/platforms/linux/accelerometer.py +++ b/sbapp/plyer/platforms/linux/accelerometer.py @@ -3,7 +3,7 @@ Linux accelerometer --------------------- ''' -from plyer.facades import Accelerometer +from sbapp.plyer.facades import Accelerometer import glob import re diff --git a/sbapp/plyer/platforms/linux/battery.py b/sbapp/plyer/platforms/linux/battery.py index b0c4691..9fc9f9f 100644 --- a/sbapp/plyer/platforms/linux/battery.py +++ b/sbapp/plyer/platforms/linux/battery.py @@ -2,13 +2,12 @@ Module of Linux API for plyer.battery. ''' -import os from math import floor from os import environ from os.path import exists, join from subprocess import Popen, PIPE -from plyer.facades import Battery -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Battery +from sbapp.plyer.utils import whereis_exe class LinuxBattery(Battery): @@ -20,10 +19,10 @@ class LinuxBattery(Battery): def _get_state(self): status = {"isCharging": None, "percentage": None} - kernel_bat_path = join('/sys', 'class', 'power_supply', self.node_name) + kernel_bat_path = join('/sys', 'class', 'power_supply', 'BAT0') uevent = join(kernel_bat_path, 'uevent') - with open(uevent, "rb") as fle: + with open(uevent) as fle: lines = [ line.decode('utf-8').strip() for line in fle.readlines() @@ -34,34 +33,70 @@ class LinuxBattery(Battery): } is_charging = output['POWER_SUPPLY_STATUS'] == 'Charging' - charge_percent = float(output['POWER_SUPPLY_CAPACITY']) + total = float(output['POWER_SUPPLY_CHARGE_FULL']) + now = float(output['POWER_SUPPLY_CHARGE_NOW']) - status['percentage'] = charge_percent + capacity = floor(now / total * 100) + + status['percentage'] = capacity status['isCharging'] = is_charging return status +class UPowerBattery(Battery): + ''' + Implementation of UPower battery API. + ''' + + def _get_state(self): + # if no LANG specified, return empty string + old_lang = environ.get('LANG', '') + environ['LANG'] = 'C' + status = {"isCharging": None, "percentage": None} + + # We are supporting only one battery now + # this will fail if there is no object with such path, + # however it's safer than 'upower -d' which provides + # multiple unrelated 'state' and 'percentage' keywords + dev = "/org/freedesktop/UPower/devices/battery_BAT0" + upower_process = Popen( + ["upower", "--show-info", dev], + stdout=PIPE + ) + output = upower_process.communicate()[0].decode() + environ['LANG'] = old_lang + if not output: + return status + state = percentage = None + + for line in output.splitlines(): + if 'state' in line: + state = line.rpartition(':')[-1].strip() + + if 'percentage' in line: + percentage = line.rpartition(':')[-1].strip()[:-1] + + # switching decimal comma to dot + # (different LC_NUMERIC locale) + percentage = float( + percentage.replace(',', '.') + ) + + if state: + status['isCharging'] = state == "charging" + status['percentage'] = percentage + return status + + def instance(): ''' Instance for facade proxy. ''' import sys - # if whereis_exe('upower'): - # return UPowerBattery() - # sys.stderr.write("upower not found.") - - node_exists = False - bn = 0 - node_name = None - for bi in range(0,10): - path = join('/sys', 'class', 'power_supply', 'BAT'+str(bi)) - if os.path.isdir(path): - node_name = "BAT"+str(bi) - break - - if node_name: - b = LinuxBattery() - b.node_name = node_name - return b + if whereis_exe('upower'): + return UPowerBattery() + sys.stderr.write("upower not found.") + if exists(join('/sys', 'class', 'power_supply', 'BAT0')): + return LinuxBattery() return Battery() diff --git a/sbapp/plyer/platforms/linux/brightness.py b/sbapp/plyer/platforms/linux/brightness.py index 0de1698..eb30536 100755 --- a/sbapp/plyer/platforms/linux/brightness.py +++ b/sbapp/plyer/platforms/linux/brightness.py @@ -4,7 +4,7 @@ Linux Brightness ''' -from plyer.facades import Brightness +from sbapp.plyer.facades import Brightness import subprocess import os diff --git a/sbapp/plyer/platforms/linux/cpu.py b/sbapp/plyer/platforms/linux/cpu.py index 049a2d4..66a532f 100644 --- a/sbapp/plyer/platforms/linux/cpu.py +++ b/sbapp/plyer/platforms/linux/cpu.py @@ -5,8 +5,8 @@ Module of Linux API for plyer.cpu. from os.path import join from os import environ, listdir from subprocess import Popen, PIPE -from plyer.facades import CPU -from plyer.utils import whereis_exe +from sbapp.plyer.facades import CPU +from sbapp.plyer.utils import whereis_exe class LinuxCPU(CPU): diff --git a/sbapp/plyer/platforms/linux/devicename.py b/sbapp/plyer/platforms/linux/devicename.py index 8941379..cbd9008 100644 --- a/sbapp/plyer/platforms/linux/devicename.py +++ b/sbapp/plyer/platforms/linux/devicename.py @@ -3,7 +3,7 @@ Module of Linux API for plyer.devicename. ''' import socket -from plyer.facades import DeviceName +from sbapp.plyer.facades import DeviceName class LinuxDeviceName(DeviceName): diff --git a/sbapp/plyer/platforms/linux/email.py b/sbapp/plyer/platforms/linux/email.py index 64cbb6d..90efce9 100644 --- a/sbapp/plyer/platforms/linux/email.py +++ b/sbapp/plyer/platforms/linux/email.py @@ -7,8 +7,8 @@ try: from urllib.parse import quote except ImportError: from urllib import quote -from plyer.facades import Email -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Email +from sbapp.plyer.utils import whereis_exe class LinuxEmail(Email): diff --git a/sbapp/plyer/platforms/linux/filechooser.py b/sbapp/plyer/platforms/linux/filechooser.py index cfdb1ae..a8e2ef2 100644 --- a/sbapp/plyer/platforms/linux/filechooser.py +++ b/sbapp/plyer/platforms/linux/filechooser.py @@ -3,7 +3,7 @@ Linux file chooser ------------------ ''' -from plyer.facades import FileChooser +from sbapp.plyer.facades import FileChooser from distutils.spawn import find_executable as which import os import subprocess as sp @@ -122,7 +122,7 @@ class ZenityFileChooser(SubprocessFileChooser): if self.icon: cmdline += ["--window-icon", self.icon] for f in self.filters: - if type(f) == str: + if isinstance(f, str): cmdline += ["--file-filter", f] else: cmdline += [ @@ -150,7 +150,7 @@ class KDialogFileChooser(SubprocessFileChooser): filt = [] for f in self.filters: - if type(f) == str: + if isinstance(f, str): filt += [f] else: filt += list(f[1:]) @@ -195,7 +195,7 @@ class YADFileChooser(SubprocessFileChooser): def _gen_cmdline(self): cmdline = [ which(self.executable), - "--file-selection", + "--file", "--confirm-overwrite", "--geometry", "800x600+150+150" @@ -215,7 +215,7 @@ class YADFileChooser(SubprocessFileChooser): if self.icon: cmdline += ["--window-icon", self.icon] for f in self.filters: - if type(f) == str: + if isinstance(f, str): cmdline += ["--file-filter", f] else: cmdline += [ diff --git a/sbapp/plyer/platforms/linux/keystore.py b/sbapp/plyer/platforms/linux/keystore.py index 105ebd3..b43be70 100644 --- a/sbapp/plyer/platforms/linux/keystore.py +++ b/sbapp/plyer/platforms/linux/keystore.py @@ -3,7 +3,7 @@ try: except ImportError: raise NotImplementedError() -from plyer.facades import Keystore +from sbapp.plyer.facades import Keystore class LinuxKeystore(Keystore): diff --git a/sbapp/plyer/platforms/linux/notification.py b/sbapp/plyer/platforms/linux/notification.py index 95a6472..552519e 100644 --- a/sbapp/plyer/platforms/linux/notification.py +++ b/sbapp/plyer/platforms/linux/notification.py @@ -4,8 +4,8 @@ Module of Linux API for plyer.notification. import warnings import subprocess -from plyer.facades import Notification -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Notification +from sbapp.plyer.utils import whereis_exe import os @@ -63,7 +63,7 @@ class NotifyDbus(Notification): def _notify(self, **kwargs): summary = kwargs.get('title', "title") body = kwargs.get('message', "body") - app_name = kwargs.get('app_name', '') + app_name = "Sideband" app_icon = kwargs.get('app_icon', '') timeout = kwargs.get('timeout', 10) actions = kwargs.get('actions', []) diff --git a/sbapp/plyer/platforms/linux/orientation.py b/sbapp/plyer/platforms/linux/orientation.py index e60fa42..c190128 100644 --- a/sbapp/plyer/platforms/linux/orientation.py +++ b/sbapp/plyer/platforms/linux/orientation.py @@ -1,5 +1,5 @@ import subprocess as sb -from plyer.facades import Orientation +from sbapp.plyer.facades import Orientation class LinuxOrientation(Orientation): diff --git a/sbapp/plyer/platforms/linux/processors.py b/sbapp/plyer/platforms/linux/processors.py index 74bb73a..332ec83 100644 --- a/sbapp/plyer/platforms/linux/processors.py +++ b/sbapp/plyer/platforms/linux/processors.py @@ -1,6 +1,6 @@ from subprocess import Popen, PIPE -from plyer.facades import Processors -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Processors +from sbapp.plyer.utils import whereis_exe from os import environ diff --git a/sbapp/plyer/platforms/linux/screenshot.py b/sbapp/plyer/platforms/linux/screenshot.py index 00eeb5c..5dc2ccf 100644 --- a/sbapp/plyer/platforms/linux/screenshot.py +++ b/sbapp/plyer/platforms/linux/screenshot.py @@ -1,8 +1,8 @@ import subprocess from os.path import join -from plyer.facades import Screenshot -from plyer.utils import whereis_exe -from plyer.platforms.linux.storagepath import LinuxStoragePath +from sbapp.plyer.facades import Screenshot +from sbapp.plyer.utils import whereis_exe +from sbapp.plyer.platforms.linux.storagepath import LinuxStoragePath class LinuxScreenshot(Screenshot): diff --git a/sbapp/plyer/platforms/linux/storagepath.py b/sbapp/plyer/platforms/linux/storagepath.py index 736674a..b32a5fe 100755 --- a/sbapp/plyer/platforms/linux/storagepath.py +++ b/sbapp/plyer/platforms/linux/storagepath.py @@ -3,7 +3,7 @@ Linux Storage Path -------------------- ''' -from plyer.facades import StoragePath +from sbapp.plyer.facades import StoragePath from os.path import expanduser, dirname, abspath, join, exists # Default paths for each name diff --git a/sbapp/plyer/platforms/linux/tts.py b/sbapp/plyer/platforms/linux/tts.py index 3932772..3b8b634 100644 --- a/sbapp/plyer/platforms/linux/tts.py +++ b/sbapp/plyer/platforms/linux/tts.py @@ -1,6 +1,6 @@ import subprocess -from plyer.facades import TTS -from plyer.utils import whereis_exe +from sbapp.plyer.facades import TTS +from sbapp.plyer.utils import whereis_exe class EspeakTextToSpeech(TTS): diff --git a/sbapp/plyer/platforms/linux/uniqueid.py b/sbapp/plyer/platforms/linux/uniqueid.py index 44926b1..30c1112 100644 --- a/sbapp/plyer/platforms/linux/uniqueid.py +++ b/sbapp/plyer/platforms/linux/uniqueid.py @@ -4,8 +4,8 @@ Module of Linux API for plyer.uniqueid. from os import environ from subprocess import Popen, PIPE -from plyer.facades import UniqueID -from plyer.utils import whereis_exe +from sbapp.plyer.facades import UniqueID +from sbapp.plyer.utils import whereis_exe class LinuxUniqueID(UniqueID): diff --git a/sbapp/plyer/platforms/linux/wifi.py b/sbapp/plyer/platforms/linux/wifi.py index 73f09b6..144f58a 100644 --- a/sbapp/plyer/platforms/linux/wifi.py +++ b/sbapp/plyer/platforms/linux/wifi.py @@ -6,8 +6,8 @@ ''' from subprocess import Popen, PIPE, call -from plyer.facades import Wifi -from plyer.utils import whereis_exe, deprecated +from sbapp.plyer.facades import Wifi +from sbapp.plyer.utils import whereis_exe, deprecated try: import wifi diff --git a/sbapp/plyer/platforms/macosx/accelerometer.py b/sbapp/plyer/platforms/macosx/accelerometer.py index 91e72c3..5b52578 100644 --- a/sbapp/plyer/platforms/macosx/accelerometer.py +++ b/sbapp/plyer/platforms/macosx/accelerometer.py @@ -3,8 +3,8 @@ MacOSX accelerometer --------------------- ''' -from plyer.facades import Accelerometer -from plyer.platforms.macosx.libs import osx_motion_sensor +from sbapp.plyer.facades import Accelerometer +from sbapp.plyer.platforms.macosx.libs import osx_motion_sensor class OSXAccelerometer(Accelerometer): diff --git a/sbapp/plyer/platforms/macosx/audio.py b/sbapp/plyer/platforms/macosx/audio.py deleted file mode 100644 index 3ab9ce1..0000000 --- a/sbapp/plyer/platforms/macosx/audio.py +++ /dev/null @@ -1,90 +0,0 @@ -from os.path import join - -from pyobjus import autoclass -from pyobjus.dylib_manager import INCLUDE, load_framework - -from plyer.facades import Audio -from plyer.platforms.macosx.storagepath import OSXStoragePath - -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 = join( - OSXStoragePath().get_music_dir(), - 'audio.wav' - ) - super().__init__(file_path or default_path) - - self._recorder = None - self._player = None - self._current_file = None - - 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, 2, 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): - # 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() - - -def instance(): - return OSXAudio() diff --git a/sbapp/plyer/platforms/macosx/battery.py b/sbapp/plyer/platforms/macosx/battery.py index 57965d3..ec42486 100644 --- a/sbapp/plyer/platforms/macosx/battery.py +++ b/sbapp/plyer/platforms/macosx/battery.py @@ -4,8 +4,8 @@ Module of MacOS API for plyer.battery. from os import environ from subprocess import Popen, PIPE -from plyer.facades import Battery -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Battery +from sbapp.plyer.utils import whereis_exe class OSXBattery(Battery): diff --git a/sbapp/plyer/platforms/macosx/bluetooth.py b/sbapp/plyer/platforms/macosx/bluetooth.py index 2575817..7c2ec22 100644 --- a/sbapp/plyer/platforms/macosx/bluetooth.py +++ b/sbapp/plyer/platforms/macosx/bluetooth.py @@ -3,8 +3,8 @@ Module of MacOS API for plyer.bluetooth. ''' from subprocess import Popen, PIPE -from plyer.facades import Bluetooth -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Bluetooth +from sbapp.plyer.utils import whereis_exe from os import environ diff --git a/sbapp/plyer/platforms/macosx/cpu.py b/sbapp/plyer/platforms/macosx/cpu.py index 7b7da7f..26eeebb 100644 --- a/sbapp/plyer/platforms/macosx/cpu.py +++ b/sbapp/plyer/platforms/macosx/cpu.py @@ -3,8 +3,8 @@ Module of MacOS API for plyer.cpu. ''' from subprocess import Popen, PIPE -from plyer.facades import CPU -from plyer.utils import whereis_exe +from sbapp.plyer.facades import CPU +from sbapp.plyer.utils import whereis_exe class OSXCPU(CPU): diff --git a/sbapp/plyer/platforms/macosx/devicename.py b/sbapp/plyer/platforms/macosx/devicename.py index 6652425..e100246 100644 --- a/sbapp/plyer/platforms/macosx/devicename.py +++ b/sbapp/plyer/platforms/macosx/devicename.py @@ -3,7 +3,7 @@ Module of MacOSX API for plyer.devicename. ''' import socket -from plyer.facades import DeviceName +from sbapp.plyer.facades import DeviceName class OSXDeviceName(DeviceName): diff --git a/sbapp/plyer/platforms/macosx/email.py b/sbapp/plyer/platforms/macosx/email.py index 49c5d4d..42295ad 100644 --- a/sbapp/plyer/platforms/macosx/email.py +++ b/sbapp/plyer/platforms/macosx/email.py @@ -9,8 +9,8 @@ try: except ImportError: from urllib import quote -from plyer.facades import Email -from plyer.utils import whereis_exe +from sbapp.plyer.facades import Email +from sbapp.plyer.utils import whereis_exe class MacOSXEmail(Email): diff --git a/sbapp/plyer/platforms/macosx/filechooser.py b/sbapp/plyer/platforms/macosx/filechooser.py index 85fb91c..1d48062 100644 --- a/sbapp/plyer/platforms/macosx/filechooser.py +++ b/sbapp/plyer/platforms/macosx/filechooser.py @@ -3,7 +3,7 @@ Mac OS X file chooser --------------------- ''' -from plyer.facades import FileChooser +from sbapp.plyer.facades import FileChooser from pyobjus import autoclass, objc_arr, objc_str from pyobjus.dylib_manager import load_framework, INCLUDE @@ -80,7 +80,7 @@ class MacFileChooser: if self.filters: filthies = [] for f in self.filters: - if type(f) == str: + if isinstance(f, str): f = (None, f) for s in f[1:]: if not self.use_extensions: diff --git a/sbapp/plyer/platforms/macosx/keystore.py b/sbapp/plyer/platforms/macosx/keystore.py index 11e60e8..ec00cff 100644 --- a/sbapp/plyer/platforms/macosx/keystore.py +++ b/sbapp/plyer/platforms/macosx/keystore.py @@ -3,7 +3,7 @@ try: except ImportError: raise NotImplementedError() -from plyer.facades import Keystore +from sbapp.plyer.facades import Keystore class OSXKeystore(Keystore): diff --git a/sbapp/plyer/platforms/macosx/libs/osx_motion_sensor.py b/sbapp/plyer/platforms/macosx/libs/osx_motion_sensor.py index d49df43..a5dc76a 100644 --- a/sbapp/plyer/platforms/macosx/libs/osx_motion_sensor.py +++ b/sbapp/plyer/platforms/macosx/libs/osx_motion_sensor.py @@ -86,7 +86,7 @@ def read_sms(): inStructure = data_structure() outStructure = data_structure() - if(is_os_64bit() or hasattr(IOKit, 'IOConnectCallStructMethod')): + if is_os_64bit() or hasattr(IOKit, 'IOConnectCallStructMethod'): structureInSize = IOItemCount(sizeof(data_structure)) structureOutSize = c_size_t(sizeof(data_structure)) @@ -120,7 +120,7 @@ def get_coord(): ret, data = read_sms() if (ret > 0): - if(data.x): + if data.x: return (data.x, data.y, data.z) else: return (None, None, None) diff --git a/sbapp/plyer/platforms/macosx/maps.py b/sbapp/plyer/platforms/macosx/maps.py new file mode 100644 index 0000000..7a6d998 --- /dev/null +++ b/sbapp/plyer/platforms/macosx/maps.py @@ -0,0 +1,90 @@ +''' +Module of macOS API for plyer.maps. +''' + +from subprocess import Popen, PIPE +from sbapp.plyer.facades import Maps +from urllib.parse import quote_plus + + +class MacOSMaps(Maps): + ''' + Implementation of MacOS 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 + + process = Popen( + ['open', '-a', 'Maps', maps_address], + stdout=PIPE, stderr=PIPE) + stdout, stderr = process.communicate() + + 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) + + process = Popen( + ['open', '-a', 'Maps', maps_address], + stdout=PIPE, stderr=PIPE) + stdout, stderr = process.communicate() + + 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) + + process = Popen( + ['open', '-a', 'Maps', maps_address], + stdout=PIPE, stderr=PIPE) + stdout, stderr = process.communicate() + + 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) + process = Popen( + ['open', '-a', 'Maps', maps_address], + stdout=PIPE, stderr=PIPE) + stdout, stderr = process.communicate() + + +def instance(): + ''' + Instance for facade proxy. + ''' + return MacOSMaps() diff --git a/sbapp/plyer/platforms/macosx/notification.py b/sbapp/plyer/platforms/macosx/notification.py index ed78ab1..6a94bbd 100644 --- a/sbapp/plyer/platforms/macosx/notification.py +++ b/sbapp/plyer/platforms/macosx/notification.py @@ -2,7 +2,7 @@ Module of MacOS API for plyer.notification. ''' -from plyer.facades import Notification +from sbapp.plyer.facades import Notification from pyobjus import ( autoclass, protocol, objc_str, ObjcBOOL @@ -26,7 +26,7 @@ class OSXNotification(Notification): def _notify(self, **kwargs): title = kwargs.get('title', '') message = kwargs.get('message', '') - app_name = kwargs.get('app_name', '') + app_name = "Sideband" # app_icon, timeout, ticker are not supported (yet) notification = NSUserNotification.alloc().init() diff --git a/sbapp/plyer/platforms/macosx/screenshot.py b/sbapp/plyer/platforms/macosx/screenshot.py index c76766a..16a35c4 100644 --- a/sbapp/plyer/platforms/macosx/screenshot.py +++ b/sbapp/plyer/platforms/macosx/screenshot.py @@ -1,8 +1,8 @@ import subprocess from os.path import join -from plyer.facades import Screenshot -from plyer.utils import whereis_exe -from plyer.platforms.macosx.storagepath import OSXStoragePath +from sbapp.plyer.facades import Screenshot +from sbapp.plyer.utils import whereis_exe +from sbapp.plyer.platforms.macosx.storagepath import OSXStoragePath class OSXScreenshot(Screenshot): diff --git a/sbapp/plyer/platforms/macosx/sms.py b/sbapp/plyer/platforms/macosx/sms.py new file mode 100644 index 0000000..8634443 --- /dev/null +++ b/sbapp/plyer/platforms/macosx/sms.py @@ -0,0 +1,42 @@ +from subprocess import Popen, PIPE +from sbapp.plyer.facades import Sms as SMS +from sbapp.plyer.utils import whereis_exe + + +class MacOSSMS(SMS): + ''' + Implementation of macOS' Messages API + ''' + + def _send(self, **kwargs): + ''' + Will send `message` to `recipient` via Messages app + + By default, if `mode` is not explicitly set, `iMessage` is used. + In order to use `SMS` mode, a valid carrier-activated device must + be connected and configured. + ''' + + recipient = kwargs.get('recipient') + message = kwargs.get('message') + mode = kwargs.get('mode') # Supported modes: iMessage (default), SMS + if not mode: + mode = 'iMessage' + + APPLESCRIPT = f"""tell application "Messages" + set targetService to 1st account whose service type = {mode} + set targetBuddy to participant "{recipient}" of targetService + send "{message}" to targetBuddy +end tell""" + + osascript_process = Popen( + ['osascript', '-e', APPLESCRIPT], stdout=PIPE, stderr=PIPE) + stdout, stderr = osascript_process.communicate() + + +def instance(): + import sys + if whereis_exe('osascript'): + return MacOSSMS() + sys.stderr.write('osascript not found.') + return SMS() diff --git a/sbapp/plyer/platforms/macosx/storagepath.py b/sbapp/plyer/platforms/macosx/storagepath.py index 027b04e..79973a4 100644 --- a/sbapp/plyer/platforms/macosx/storagepath.py +++ b/sbapp/plyer/platforms/macosx/storagepath.py @@ -3,7 +3,7 @@ MacOS X Storage Path -------------------- ''' -from plyer.facades import StoragePath +from sbapp.plyer.facades import StoragePath from pyobjus import autoclass NSFileManager = autoclass('NSFileManager') diff --git a/sbapp/plyer/platforms/macosx/tts.py b/sbapp/plyer/platforms/macosx/tts.py index 755e820..464de56 100644 --- a/sbapp/plyer/platforms/macosx/tts.py +++ b/sbapp/plyer/platforms/macosx/tts.py @@ -1,6 +1,6 @@ import subprocess -from plyer.facades import TTS -from plyer.utils import whereis_exe +from sbapp.plyer.facades import TTS +from sbapp.plyer.utils import whereis_exe class NativeSayTextToSpeech(TTS): diff --git a/sbapp/plyer/platforms/macosx/uniqueid.py b/sbapp/plyer/platforms/macosx/uniqueid.py index dc84153..464e723 100644 --- a/sbapp/plyer/platforms/macosx/uniqueid.py +++ b/sbapp/plyer/platforms/macosx/uniqueid.py @@ -4,8 +4,8 @@ Module of MacOS API for plyer.uniqueid. from os import environ from subprocess import Popen, PIPE -from plyer.facades import UniqueID -from plyer.utils import whereis_exe +from sbapp.plyer.facades import UniqueID +from sbapp.plyer.utils import whereis_exe class OSXUniqueID(UniqueID): diff --git a/sbapp/plyer/platforms/macosx/wifi.py b/sbapp/plyer/platforms/macosx/wifi.py index 32c02ab..61da385 100644 --- a/sbapp/plyer/platforms/macosx/wifi.py +++ b/sbapp/plyer/platforms/macosx/wifi.py @@ -1,7 +1,7 @@ from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE -from plyer.facades import Wifi +from sbapp.plyer.facades import Wifi load_framework(INCLUDE.Foundation) load_framework(INCLUDE.CoreWLAN) diff --git a/sbapp/plyer/platforms/win/audio.py b/sbapp/plyer/platforms/win/audio.py deleted file mode 100644 index c9d8f35..0000000 --- a/sbapp/plyer/platforms/win/audio.py +++ /dev/null @@ -1,398 +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 plyer.facades import Audio -from 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 - - 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 instance(): - ''' - Instance for facade proxy. - ''' - return WinAudio() diff --git a/sbapp/plyer/platforms/win/battery.py b/sbapp/plyer/platforms/win/battery.py index 861d904..af899ca 100644 --- a/sbapp/plyer/platforms/win/battery.py +++ b/sbapp/plyer/platforms/win/battery.py @@ -2,8 +2,8 @@ Module of Windows API for plyer.battery. ''' -from plyer.platforms.win.libs.batterystatus import battery_status -from plyer.facades import Battery +from sbapp.plyer.platforms.win.libs.batterystatus import battery_status +from sbapp.plyer.facades import Battery from ctypes.wintypes import BYTE diff --git a/sbapp/plyer/platforms/win/cpu.py b/sbapp/plyer/platforms/win/cpu.py index d1262dc..9b65549 100644 --- a/sbapp/plyer/platforms/win/cpu.py +++ b/sbapp/plyer/platforms/win/cpu.py @@ -11,7 +11,7 @@ from ctypes.wintypes import ( BYTE, DWORD, WORD ) -from plyer.facades import CPU +from sbapp.plyer.facades import CPU KERNEL = windll.kernel32 diff --git a/sbapp/plyer/platforms/win/devicename.py b/sbapp/plyer/platforms/win/devicename.py index d35d76b..d631ac4 100644 --- a/sbapp/plyer/platforms/win/devicename.py +++ b/sbapp/plyer/platforms/win/devicename.py @@ -3,7 +3,7 @@ Module of Win API for plyer.devicename. ''' import socket -from plyer.facades import DeviceName +from sbapp.plyer.facades import DeviceName class WinDeviceName(DeviceName): diff --git a/sbapp/plyer/platforms/win/email.py b/sbapp/plyer/platforms/win/email.py index 4c0f9b7..3c43cde 100644 --- a/sbapp/plyer/platforms/win/email.py +++ b/sbapp/plyer/platforms/win/email.py @@ -7,7 +7,7 @@ try: from urllib.parse import quote except ImportError: from urllib import quote -from plyer.facades import Email +from sbapp.plyer.facades import Email class WindowsEmail(Email): diff --git a/sbapp/plyer/platforms/win/filechooser.py b/sbapp/plyer/platforms/win/filechooser.py index d61fdc1..9932d9b 100644 --- a/sbapp/plyer/platforms/win/filechooser.py +++ b/sbapp/plyer/platforms/win/filechooser.py @@ -3,7 +3,7 @@ Windows file chooser -------------------- ''' -from plyer.facades import FileChooser +from sbapp.plyer.facades import FileChooser from win32com.shell.shell import ( SHBrowseForFolder as browse, SHGetPathFromIDList as get_path @@ -84,7 +84,7 @@ class Win32FileChooser: # e.g. open_file(filters=['*.txt', '*.py']) filters = "" for f in self.filters: - if type(f) == str: + if isinstance(f, str): filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" diff --git a/sbapp/plyer/platforms/win/keystore.py b/sbapp/plyer/platforms/win/keystore.py index 0065a6a..59e48d1 100644 --- a/sbapp/plyer/platforms/win/keystore.py +++ b/sbapp/plyer/platforms/win/keystore.py @@ -3,7 +3,7 @@ try: except Exception: raise NotImplementedError() -from plyer.facades import Keystore +from sbapp.plyer.facades import Keystore class WinKeystore(Keystore): diff --git a/sbapp/plyer/platforms/win/libs/balloontip.py b/sbapp/plyer/platforms/win/libs/balloontip.py index 5494f4e..1334a99 100644 --- a/sbapp/plyer/platforms/win/libs/balloontip.py +++ b/sbapp/plyer/platforms/win/libs/balloontip.py @@ -12,7 +12,7 @@ import ctypes import atexit from threading import RLock -from plyer.platforms.win.libs import win_api_defs +from sbapp.plyer.platforms.win.libs import win_api_defs WS_OVERLAPPED = 0x00000000 diff --git a/sbapp/plyer/platforms/win/libs/batterystatus.py b/sbapp/plyer/platforms/win/libs/batterystatus.py index 1d8202d..0c0c635 100644 --- a/sbapp/plyer/platforms/win/libs/batterystatus.py +++ b/sbapp/plyer/platforms/win/libs/batterystatus.py @@ -6,7 +6,7 @@ __all__ = ('battery_status') import ctypes -from plyer.platforms.win.libs import win_api_defs +from sbapp.plyer.platforms.win.libs import win_api_defs def battery_status(): diff --git a/sbapp/plyer/platforms/win/notification.py b/sbapp/plyer/platforms/win/notification.py index bac381b..b83838e 100644 --- a/sbapp/plyer/platforms/win/notification.py +++ b/sbapp/plyer/platforms/win/notification.py @@ -4,8 +4,8 @@ Module of Windows API for plyer.notification. from threading import Thread as thread -from plyer.facades import Notification -from plyer.platforms.win.libs.balloontip import balloon_tip +from sbapp.plyer.facades import Notification +from sbapp.plyer.platforms.win.libs.balloontip import balloon_tip class WindowsNotification(Notification): diff --git a/sbapp/plyer/platforms/win/screenshot.py b/sbapp/plyer/platforms/win/screenshot.py index b04eab5..1291fe9 100644 --- a/sbapp/plyer/platforms/win/screenshot.py +++ b/sbapp/plyer/platforms/win/screenshot.py @@ -18,8 +18,8 @@ from win32con import ( SRCCOPY ) -from plyer.facades import Screenshot -from plyer.platforms.win.storagepath import WinStoragePath +from sbapp.plyer.facades import Screenshot +from sbapp.plyer.platforms.win.storagepath import WinStoragePath class WinScreenshot(Screenshot): diff --git a/sbapp/plyer/platforms/win/storagepath.py b/sbapp/plyer/platforms/win/storagepath.py index fd905d8..1528483 100755 --- a/sbapp/plyer/platforms/win/storagepath.py +++ b/sbapp/plyer/platforms/win/storagepath.py @@ -3,9 +3,9 @@ Windows Storage Path -------------------- ''' -from plyer.facades import StoragePath +from sbapp.plyer.facades import StoragePath from os.path import expanduser -from plyer.platforms.win.libs.win_api_defs import get_PATH +from sbapp.plyer.platforms.win.libs.win_api_defs import get_PATH from uuid import UUID diff --git a/sbapp/plyer/platforms/win/tts.py b/sbapp/plyer/platforms/win/tts.py index e2539c3..2b9f8f9 100644 --- a/sbapp/plyer/platforms/win/tts.py +++ b/sbapp/plyer/platforms/win/tts.py @@ -1,6 +1,6 @@ import subprocess -from plyer.facades import TTS -from plyer.utils import whereis_exe +from sbapp.plyer.facades import TTS +from sbapp.plyer.utils import whereis_exe class EspeakTextToSpeech(TTS): diff --git a/sbapp/plyer/platforms/win/uniqueid.py b/sbapp/plyer/platforms/win/uniqueid.py index 6d42391..42853b7 100644 --- a/sbapp/plyer/platforms/win/uniqueid.py +++ b/sbapp/plyer/platforms/win/uniqueid.py @@ -10,7 +10,7 @@ except ImportError: except ImportError: raise NotImplementedError() -from plyer.facades import UniqueID +from sbapp.plyer.facades import UniqueID class WinUniqueID(UniqueID): diff --git a/sbapp/plyer/platforms/win/wifi.py b/sbapp/plyer/platforms/win/wifi.py index 68efb2f..152d4c0 100644 --- a/sbapp/plyer/platforms/win/wifi.py +++ b/sbapp/plyer/platforms/win/wifi.py @@ -1,5 +1,5 @@ -import plyer.platforms.win.libs.wifi_defs as wifi_lib -from plyer.facades import Wifi +import sbapp.plyer.platforms.win.libs.wifi_defs as wifi_lib +from sbapp.plyer.facades import Wifi class WindowWifi(Wifi): diff --git a/sbapp/plyer/tests/common.py b/sbapp/plyer/tests/common.py deleted file mode 100644 index 7436db8..0000000 --- a/sbapp/plyer/tests/common.py +++ /dev/null @@ -1,76 +0,0 @@ -''' -Common objects for testing -========================== - -* :class:`PlatformTest` - used as a decorator, allows running a test function - only on a specific platform (see `plyer.utils.platform`). -* :func:`platform_import` - manual import of a platform specific class instead - of using `plyer.facades.*` proxies. -''' - -import traceback -from os import sep -from os.path import normpath, splitdrive -from plyer.utils import platform as plyer_platform - - -class PlatformTest: - ''' - Class for the @PlatformTest decorator to prevent running tests - calling platform dependent API on different platforms. - ''' - - def __init__(self, platform): - self.platform = platform - - def __call__(self, func): - platform = self.platform - - if platform != plyer_platform: - print("Skipping test '{}' - not on '{}'".format( - func.__name__, platform - )) - func = self.eat - return func - - @staticmethod - def eat(*args, **kwargs): - ''' - Simply eat all positional and keyword arguments - and return None as an empty function. - ''' - - -def platform_import(platform, module_name, whereis_exe=None): - ''' - Import platform API directly instead of through Proxy. - ''' - - try: - module = 'plyer.platforms.{}.{}'.format( - platform, module_name - ) - mod = __import__(module, fromlist='.') - - except ImportError as exc: - print(vars(exc)) - traceback.print_exc() - - if whereis_exe: - mod.whereis_exe = whereis_exe - return mod - - -def splitpath(path): - ''' - Split string path into a list of folders (+ file if available). - ''' - if path[0] == sep and path[1] != sep: - path = path[1:] - path = normpath(path).split(sep) - else: - drive, path = splitdrive(path) - if path[0] == sep and path[1] != sep: - path = path[1:] - path = [drive, ] + normpath(path).split(sep) - return path diff --git a/sbapp/plyer/tests/images/kivy32.ico b/sbapp/plyer/tests/images/kivy32.ico deleted file mode 100644 index 2010bf3..0000000 Binary files a/sbapp/plyer/tests/images/kivy32.ico and /dev/null differ diff --git a/sbapp/plyer/tests/test_audio.py b/sbapp/plyer/tests/test_audio.py deleted file mode 100644 index e811891..0000000 --- a/sbapp/plyer/tests/test_audio.py +++ /dev/null @@ -1,110 +0,0 @@ -''' -TestAudio -========= - -Tested platforms: - -* macOS -* Windows - -.. versionadded:: 1.4.0 -''' - -import unittest -import time - -from os import mkdir, remove, environ -from os.path import join, expanduser, exists -from plyer.tests.common import platform_import, PlatformTest - - -class TestAudio(unittest.TestCase): - ''' - TestCase for plyer.audio. - - .. versionadded:: 1.4.0 - ''' - - @PlatformTest('macosx') - def test_audio_macosx(self): - ''' - Test macOS audio start, stop and play - - .. versionadded:: 1.4.0 - ''' - - path = join(expanduser('~'), 'Music') - if not exists(path): - mkdir(path) - - audio = platform_import( - platform='macosx', - module_name='audio', - ) - - self.assertIn('OSXAudio', dir(audio)) - audio = audio.instance() - self.assertIn('OSXAudio', str(audio)) - - self.assertFalse(exists(audio.file_path)) - self.assertIsNone(audio.start()) - time.sleep(0.5) - self.assertIsNone(audio.stop()) - self.assertIsNone(audio.play()) - time.sleep(0.5) - self.assertIsNone(audio.stop()) - - audio.file_path = audio.file_path.replace( - 'file://', '' - ) - - self.assertTrue(exists(audio.file_path)) - - remove(audio.file_path) - - @PlatformTest('win') - def test_audio_win(self): - ''' - Test Windows audio start, stop and play - - .. versionadded:: 1.4.0 - ''' - - if environ.get('APPVEYOR'): - # Appveyor has no recording device installed - # therefore the test will 100% fail - # - # error_code: 328 - # message: - # 'No wave device is installed that can record files in the current - # format. To install a wave device, go to Control Panel, click P') - return - - path = join(environ['USERPROFILE'], 'Music') - if not exists(path): - mkdir(path) - - audio = platform_import( - platform='win', - module_name='audio', - ) - - self.assertIn('WinAudio', dir(audio)) - audio = audio.instance() - self.assertIn('WinAudio', str(audio)) - - self.assertFalse(exists(audio.file_path)) - self.assertIsNone(audio.start()) - time.sleep(0.5) - self.assertIsNone(audio.stop()) - self.assertIsNone(audio.play()) - time.sleep(0.5) - self.assertIsNone(audio.stop()) - - self.assertTrue(exists(audio.file_path)) - - remove(audio.file_path) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_battery.py b/sbapp/plyer/tests/test_battery.py deleted file mode 100644 index b44d504..0000000 --- a/sbapp/plyer/tests/test_battery.py +++ /dev/null @@ -1,413 +0,0 @@ -''' -TestBattery -=========== - -Tested platforms: - -* Windows -* Linux - upower, kernel sysclass -* macOS - ioreg -''' - -import unittest -from io import BytesIO -from os.path import join -from textwrap import dedent -from mock import patch, Mock - -from plyer.tests.common import PlatformTest, platform_import - - -class MockedKernelSysclass: - ''' - Mocked object used instead of Linux's sysclass for power_supply - battery uevent. - ''' - - @property - def path(self): - ''' - Mocked path to Linux kernel sysclass. - ''' - return join('/sys', 'class', 'power_supply', 'BAT0') - - @property - def charging(self): - ''' - Mocked battery charging status. - ''' - return u'Discharging' - - @property - def percentage(self): - ''' - Mocked battery charge percentage. - ''' - return 89.0 - - @property - def full(self): - ''' - Mocked full battery charge. - ''' - return 4764000 - - @property - def now(self): - ''' - Calculated current mocked battery charge. - ''' - return self.percentage * self.full / 100.0 - - @property - def uevent(self): - ''' - Mocked /sys/class/power_supply/BAT0 file. - ''' - return BytesIO(dedent(b'''\ - POWER_SUPPLY_NAME=BAT0 - POWER_SUPPLY_STATUS={} - POWER_SUPPLY_PRESENT=1 - POWER_SUPPLY_TECHNOLOGY=Li-ion - POWER_SUPPLY_CYCLE_COUNT=0 - POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 - POWER_SUPPLY_VOLTAGE_NOW=12074000 - POWER_SUPPLY_CURRENT_NOW=1584000 - POWER_SUPPLY_CHARGE_FULL_DESIGN=5800000 - POWER_SUPPLY_CHARGE_FULL={} - POWER_SUPPLY_CHARGE_NOW={} - POWER_SUPPLY_CAPACITY={} - POWER_SUPPLY_CAPACITY_LEVEL=Normal - POWER_SUPPLY_MODEL_NAME=1005HA - POWER_SUPPLY_MANUFACTURER=ASUS - POWER_SUPPLY_SERIAL_NUMBER=0 - '''.decode('utf-8').format( - self.charging, self.full, - self.now, int(self.percentage) - )).encode('utf-8')) - - -class MockedUPower: - ''' - Mocked object used instead of 'upower' binary in the Linux specific API - plyer.platforms.linux.battery. The same output structure is tested for - the range of . - - .. note:: Extend the object with another data sample if it does not match. - ''' - - min_version = '0.99.4' - max_version = '0.99.4' - - values = { - u'Device': u'/org/freedesktop/UPower/devices/battery_BAT0', - u'native-path': u'BAT0', - u'vendor': u'ASUS', - u'model': u'1005HA', - u'power supply': u'yes', - u'updated': u'Thu 05 Jul 2018 23:15:01 PM CEST', - u'has history': u'yes', - u'has statistics': u'yes', - u'battery': { - u'present': u'yes', - u'rechargeable': u'yes', - u'state': u'discharging', - u'warning-level': u'none', - u'energy': u'48,708 Wh', - u'energy-empty': u'0 Wh', - u'energy-full': u'54,216 Wh', - u'energy-full-design': u'62,64 Wh', - u'energy-rate': u'7,722 W', - u'voltage': u'11,916 V', - u'time to empty': u'6,3 hours', - u'percentage': u'89%', - u'capacity': u'86,5517%', - u'technology': u'lithium-ion', - u'icon-name': u"'battery-full-symbolic" - }, - u'History (charge)': u'1530959637 89,000 discharging', - u'History (rate)': u'1530958556 7,474 discharging' - } - - data = str( - ' native-path: {native-path}\n' - ' vendor: {vendor}\n' - ' model: {model}\n' - ' power supply: {power supply}\n' - ' updated: {updated}\n' - ' has history: {has history}\n' - ' has statistics: {has statistics}\n' - ' battery\n' - ' present: {battery[present]}\n' - ' rechargeable: {battery[rechargeable]}\n' - ' state: {battery[state]}\n' - ' warning-level: {battery[warning-level]}\n' - ' energy: {battery[energy]}\n' - ' energy-empty: {battery[energy-empty]}\n' - ' energy-full: {battery[energy-full]}\n' - ' energy-full-design: {battery[energy-full-design]}\n' - ' energy-rate: {battery[energy-rate]}\n' - ' voltage: {battery[voltage]}\n' - ' time to empty: {battery[time to empty]}\n' - ' percentage: {battery[percentage]}\n' - ' capacity: {battery[capacity]}\n' - ' technology: {battery[technology]}\n' - ' icon-name: {battery[icon-name]}\n' - ' History (charge):\n' - ' {History (charge)}\n' - ' History (rate):\n' - ' {History (rate)}\n' - ).format(**values).encode('utf-8') - # LinuxBattery calls decode() - - def __init__(self, *args, **kwargs): - # only to ignore all args, kwargs - pass - - @staticmethod - def communicate(): - ''' - Mock Popen.communicate, so that 'upower' isn't used. - ''' - return (MockedUPower.data, ) - - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - Linux UPower binary is present on the system. - ''' - return binary == 'upower' - - @staticmethod - def charging(): - ''' - Return charging bool from mocked data. - ''' - return MockedUPower.values['battery']['state'] == 'charging' - - @staticmethod - def percentage(): - ''' - Return percentage from mocked data. - ''' - percentage = MockedUPower.values['battery']['percentage'][:-1] - return float(percentage.replace(',', '.')) - - -class MockedIOReg: - ''' - Mocked object used instead of Apple's ioreg. - ''' - values = { - "MaxCapacity": "5023", - "CurrentCapacity": "4222", - "IsCharging": "No" - } - - output = dedent( - """+-o AppleSmartBattery - {{ - "TimeRemaining" = 585 - "AvgTimeToEmpty" = 585 - "InstantTimeToEmpty" = 761 - "ExternalChargeCapable" = Yes - "FullPathUpdated" = 1541845134 - "CellVoltage" = (4109,4118,4099,0) - "PermanentFailureStatus" = 0 - "BatteryInvalidWakeSeconds" = 30 - "AdapterInfo" = 0 - "MaxCapacity" = {MaxCapacity} - "Voltage" = 12326 - "DesignCycleCount70" = 13 - "Manufacturer" = "SWD" - "Location" = 0 - "CurrentCapacity" = {CurrentCapacity} - "LegacyBatteryInfo" = {{"Amperage"=18446744073709551183,"Flags"=4,\ - "Capacity"=5023,"Current"=4222,"Voltage"=12326,"Cycle Count"=40}} - "FirmwareSerialNumber" = 1 - "BatteryInstalled" = Yes - "PackReserve" = 117 - "CycleCount" = 40 - "DesignCapacity" = 5088 - "OperationStatus" = 58435 - "ManufactureDate" = 19700 - "AvgTimeToFull" = 65535 - "BatterySerialNumber" = "1234567890ABCDEFGH" - "BootPathUpdated" = 1541839734 - "PostDischargeWaitSeconds" = 120 - "Temperature" = 3038 - "UserVisiblePathUpdated" = 1541845194 - "InstantAmperage" = 18446744073709551249 - "ManufacturerData" = <000000000> - "FullyCharged" = No - "MaxErr" = 1 - "DeviceName" = "bq20z451" - "IOGeneralInterest" = "IOCommand is not serializable" - "Amperage" = 18446744073709551183 - "IsCharging" = {IsCharging} - "DesignCycleCount9C" = 1000 - "PostChargeWaitSeconds" = 120 - "ExternalConnected" = No - }}""" - ).format(**values).encode('utf-8') - - def __init__(self, *args, **kwargs): - # only to ignore all args, kwargs - pass - - @staticmethod - def communicate(): - ''' - Mock Popen.communicate, so that 'ioreg' isn't used. - ''' - return (MockedIOReg.output, ) - - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - macOS ioreg binary is present on the system. - ''' - return binary == 'ioreg' - - @staticmethod - def charging(): - ''' - Return charging bool from mocked data. - ''' - return MockedIOReg.values['IsCharging'] == 'Yes' - - @staticmethod - def percentage(): - ''' - Return percentage from mocked data. - ''' - current_capacity = int(MockedIOReg.values['CurrentCapacity']) - max_capacity = int(MockedIOReg.values['MaxCapacity']) - percentage = 100.0 * current_capacity / max_capacity - - return percentage - - -class TestBattery(unittest.TestCase): - ''' - TestCase for plyer.battery. - ''' - - def test_battery_linux_upower(self): - ''' - Test mocked Linux UPower for plyer.battery. - ''' - battery = platform_import( - platform='linux', - module_name='battery', - whereis_exe=MockedUPower.whereis_exe - ) - battery.Popen = MockedUPower - battery = battery.instance() - - self.assertEqual( - battery.status, { - 'isCharging': MockedUPower.charging(), - 'percentage': MockedUPower.percentage() - } - ) - - def test_battery_linux_kernel(self): - ''' - Test mocked Linux kernel sysclass for plyer.battery. - ''' - - def false(*args, **kwargs): - return False - - sysclass = MockedKernelSysclass() - - with patch(target='os.path.exists') as bat_path: - # first call to trigger exists() call - platform_import( - platform='linux', - module_name='battery', - whereis_exe=false - ).instance() - bat_path.assert_called_once_with(sysclass.path) - - # exists() checked with sysclass path - # set mock to proceed with this branch - bat_path.return_value = True - - battery = platform_import( - platform='linux', - module_name='battery', - whereis_exe=false - ).instance() - - stub = Mock(return_value=sysclass.uevent) - target = 'builtins.open' - - with patch(target=target, new=stub): - self.assertEqual( - battery.status, { - 'isCharging': sysclass.charging == 'Charging', - 'percentage': sysclass.percentage - } - ) - - @PlatformTest('win') - def test_battery_win(self): - ''' - Test Windows API for plyer.battery. - ''' - battery = platform_import( - platform='win', - module_name='battery' - ).instance() - for key in ('isCharging', 'percentage'): - self.assertIn(key, battery.status) - self.assertIsNotNone(battery.status[key]) - - def test_battery_macosx(self): - ''' - Test macOS IOReg for plyer.battery. - ''' - battery = platform_import( - platform='macosx', - module_name='battery', - whereis_exe=MockedIOReg.whereis_exe - ) - - battery.Popen = MockedIOReg - self.assertIn('OSXBattery', dir(battery)) - battery = battery.instance() - self.assertIn('OSXBattery', str(battery)) - - self.assertEqual( - battery.status, { - 'isCharging': MockedIOReg.charging(), - 'percentage': MockedIOReg.percentage() - } - ) - - def test_battery_macosx_instance(self): - ''' - Test macOS instance for plyer.battery - ''' - - def no_exe(*args, **kwargs): - return - - battery = platform_import( - platform='macosx', - module_name='battery', - whereis_exe=no_exe - ) - - battery = battery.instance() - self.assertNotIn('OSXBattery', str(battery)) - self.assertIn('Battery', str(battery)) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_bluetooth.py b/sbapp/plyer/tests/test_bluetooth.py deleted file mode 100644 index 8997c4d..0000000 --- a/sbapp/plyer/tests/test_bluetooth.py +++ /dev/null @@ -1,144 +0,0 @@ -''' -TestBluetooth -============= - -Tested platforms: - -* macOS - system_profiler -''' - -import unittest - -from plyer.tests.common import platform_import -from textwrap import dedent - - -class MockedSystemProfiler: - ''' - Mocked object used instead of Apple's system_profiler - ''' - value = "On" - output = dedent( - """Bluetooth: - - Apple Bluetooth Software Version: 6.0.7f11 - Hardware, Features, and Settings: - Address: AA-00-BB-11-CC-22 - Bluetooth Low Energy Supported: Yes - Handoff Supported: Yes - Instant Hot Spot Supported: Yes - Manufacturer: Broadcom - Transport: UART - Chipset: 1234 - Firmware Version: v00 c0000 - Bluetooth Power: {} - Auto Seek Pointing: On - Remote wake: On - Vendor ID: 0x0000 - Product ID: 0x0000 - HCI Version: (0x0) - HCI Revision: 0x0000 - LMP Version: (0x0) - LMP Subversion: 0x0000 - Auto Seek Keyboard: On - Devices (Paired, Configured, etc.): - iPhone: - Address: AA-00-BB-11-CC-22 - Major Type: Miscellaneous - Minor Type: Unknown - Services: - Paired: No - Configured: Yes - Connected: No - Class of Device: 0x00 0x00 0x0000 - Services: - Bluetooth File Transfer: - Folder other devices can browse: ~/Public - When receiving items: Accept all without warning - State: Disabled - Bluetooth File Exchange: - Folder for accepted items: ~/Downloads - When other items are accepted: Save to location - When receiving items: Accept all without warning - State: Disabled - Bluetooth Internet Sharing: - State: Disabled - Incoming Serial Ports: - Bluetooth-Incoming-Port: - RFCOMM Channel: 3 - Requires Authentication: No""" - ).format(value).encode('utf-8') - - def __init__(self, *args, **kwargs): - # only to ignore all args, kwargs - pass - - @staticmethod - def communicate(): - ''' - Mock Popen.communicate, so that 'system_profiler' - isn't used. - ''' - return (MockedSystemProfiler.output, ) - - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - macOS system_profiler binary is present on the system. - ''' - return binary == 'system_profiler' - - @staticmethod - def get_info(): - ''' - Return current bluetooth status from mocked output. - ''' - return MockedSystemProfiler.value - - -class TestBluetooth(unittest.TestCase): - ''' - TestCase for plyer.bluetooth. - ''' - - def test_bluetooth_macosx(self): - ''' - Test macOS system_profiler for plyer.bluetooth. - ''' - bluetooth = platform_import( - platform='macosx', - module_name='bluetooth', - whereis_exe=MockedSystemProfiler.whereis_exe - ) - - bluetooth.Popen = MockedSystemProfiler - self.assertIn('OSXBluetooth', dir(bluetooth)) - bluetooth = bluetooth.instance() - self.assertIn('OSXBluetooth', str(bluetooth)) - - self.assertEqual( - bluetooth.info, MockedSystemProfiler.get_info() - ) - - def test_bluetooth_macosx_instance(self): - ''' - Test macOS instance for plyer.bluetooth. - ''' - - def no_exe(*args, **kwargs): - return - - bluetooth = platform_import( - platform='macosx', - module_name='bluetooth', - whereis_exe=no_exe - ) - - bluetooth = bluetooth.instance() - self.assertNotIn('OSXBluetooth', str(bluetooth)) - self.assertIn('Bluetooth', str(bluetooth)) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_cpu.py b/sbapp/plyer/tests/test_cpu.py deleted file mode 100644 index 8882522..0000000 --- a/sbapp/plyer/tests/test_cpu.py +++ /dev/null @@ -1,262 +0,0 @@ -''' -TestCPU -======= - -Tested platforms: - -* Windows -* Linux - nproc -''' - -import unittest -from os import environ -from os.path import join -from mock import patch, Mock -from textwrap import dedent - -from plyer.tests.common import PlatformTest, platform_import, splitpath - - -class MockedKernelCPU: - def __init__(self, *args, **kwargs): - self.fname = args[0] if args else '' - self.cpu_path = join('/sys', 'devices', 'system', 'cpu') - self.cores = 16 - self.indicies = 4 - - def __enter__(self, *args): - file_value = None - cpu_path = self.cpu_path - spath = splitpath(self.fname) - - if self.fname == join(cpu_path, 'present'): - file_value = Mock() - file_value.read.return_value = self.present - elif spath[5] == 'cache' and spath[7] == 'level': - file_value = Mock() - # force bytes, because reading files as bytes - file_value.read.return_value = str( - self.index_types[spath[4]][spath[6]][spath[7]] - ).encode('utf-8') - return file_value - - def __exit__(self, *args): - pass - - @property - def present(self): - rng = list(range(self.cores)) - start = str(rng[0]) - end = str(rng[-1]) - if start == end: # cores == 1 --> b'0' - value = str(start) - else: # cores > 1 --> b'0-n' - value = str('-'.join([start, end])) - return value.encode('utf-8') - - @property - def listdir(self): - return ['index{}'.format(i) for i in range(self.indicies)] - - @property - def index_types(self): - # assign L1 to index0-1, L2 to 2, L3 to 3 - types = {0: 1, 1: 1, 2: 2, 3: 3} - - return { - 'cpu{}'.format(c): { - 'index{}'.format(i): { - 'level': types[i] - } - for i in range(self.indicies) - } - for c in range(self.cores) - } - - -class MockedNProc: - ''' - Mocked object used instead of 'nproc' binary in the Linux specific API - plyer.platforms.linux.cpu. The same output structure is tested for - the range of . - - .. note:: Extend the object with another data sample if it does not match. - ''' - - min_version = '8.21' - max_version = '8.21' - logical_cores = 99 - - def __init__(self, *args, **kwargs): - # only to ignore all args, kwargs - pass - - @staticmethod - def communicate(): - ''' - Mock Popen.communicate, so that 'nproc' isn't used. - ''' - return (str(MockedNProc.logical_cores).encode('utf-8'), ) - - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - Linux NProc binary is present on the system. - ''' - return binary == 'nproc' - - @staticmethod - def logical(): - ''' - Return percentage from mocked data. - ''' - return int(MockedNProc.logical_cores) - - -class MockedProcinfo: - # docs: - # https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git - # /tree/arch/x86/kernel/cpu/proc.c - sockets = 1 # physical id - physical = 2 # core id - threads_per_core = 2 # Intel specs document for i7-4500U - logical = physical * threads_per_core # processor - - def __init__(self, *args, **kwargs): - self.fname = args[0] if args else '' - - self.output = [] - __step = 0 # 0,1,0,1 -> 0,0,1,1 - for soc in range(self.sockets): - for log in range(self.logical): - if log != 0 and not log % self.physical: - __step += 1 - self.output.append((dedent( - '''\ - processor\t: {logical} - vendor_id\t: GenuineIntel - cpu family\t: 6 - model\t\t: 69 - model name\t: Intel(R) Core(TM) i7-4500U CPU @ 1.80GHz - stepping\t: 1 - microcode\t: 0x17 - cpu MHz\t\t: 774.000 - cache size\t: 4096 KB - physical id\t: {socket} - siblings\t: 4 - core id\t\t: {physical} - cpu cores\t: {threads_per_core} - apicid\t\t: {logical} - initial apicid\t: 0 - fpu\t\t: yes - fpu_exception\t: yes - cpuid level\t: 13 - wp\t\t: yes - flags\t\t: fpu vme de pse tsc msr pae mce cx8 ... - bogomips\t: 3591.40 - clflush size\t: 64 - cache_alignment\t: 64 - address sizes\t: 39 bits physical, 48 bits virtual - power management: - \n''' - )).format(**{ - 'socket': soc, - 'physical': __step, - 'logical': log, - 'threads_per_core': self.threads_per_core - })) - self.output = ''.join(self.output).encode('utf-8') - - def __enter__(self, *args): - file_value = None - - if self.fname == '/proc/cpuinfo': - file_value = Mock() - file_value.readlines.return_value = self.output.split( - '\n'.encode('utf-8') - ) - return file_value - - def __exit__(self, *args): - pass - - -class TestCPU(unittest.TestCase): - ''' - TestCase for plyer.cpu. - ''' - - def test_cpu_linux_physical(self): - cpu = platform_import( - platform='linux', - module_name='cpu', - whereis_exe=lambda b: b == 'nproc' - ).instance() - - stub = MockedProcinfo - target = 'builtins.open' - - with patch(target=target, new=stub): - sb = stub() - self.assertEqual( - cpu.physical, sb.physical - ) - - def test_cpu_linux_logical(self): - ''' - Test mocked Linux NProc for plyer.cpu. - ''' - cpu = platform_import( - platform='linux', - module_name='cpu', - whereis_exe=MockedNProc.whereis_exe - ) - cpu.Popen = MockedNProc - cpu = cpu.instance() - - self.assertEqual( - cpu.logical, MockedNProc.logical() - ) - - @PlatformTest('linux') - def test_cpu_linux_cache(self): - cpu = platform_import( - platform='linux', - module_name='cpu', - whereis_exe=lambda b: b == 'nproc' - ).instance() - - stub = MockedKernelCPU - target = 'builtins.open' - sub_target = 'plyer.platforms.linux.cpu.listdir' - - with patch(target=target, new=stub): - with patch(target=sub_target, return_value=stub().listdir): - sb = stub() - self.assertEqual( - cpu.cache, { - 'L1': sb.cores * 2, - 'L2': sb.cores, - 'L3': sb.cores - } - ) - - @PlatformTest('win') - def test_cpu_win_logical(self): - cpu = platform_import( - platform='win', - module_name='cpu' - ) - - cpu = cpu.instance() - self.assertEqual( - cpu.logical, - # https://docs.microsoft.com/en-us/previous-versions/ - # windows/it-pro/windows-xp/bb490954(v=technet.10) - int(environ['NUMBER_OF_PROCESSORS']) - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_devicename.py b/sbapp/plyer/tests/test_devicename.py deleted file mode 100644 index cbb0fc4..0000000 --- a/sbapp/plyer/tests/test_devicename.py +++ /dev/null @@ -1,77 +0,0 @@ -''' -TestDeviceName -============ - -Tested platforms: - -* Windows -''' - -import unittest -from mock import patch -from plyer.tests.common import PlatformTest, platform_import -import socket - - -class TestDeviceName(unittest.TestCase): - ''' - TestCase for plyer.devicename. - ''' - - @PlatformTest('win') - def test_devicename_win(self): - ''' - Test Windows API for plyer.devicename. - ''' - devicename = platform_import(platform='win', - module_name='devicename' - ) - devicename_instance = devicename.instance() - - with patch.object(socket, - 'gethostname', - return_value='mocked_windows_hostname' - ) as _: - - evaluated_device_name = devicename_instance.device_name - self.assertEqual(evaluated_device_name, 'mocked_windows_hostname') - - @PlatformTest('linux') - def test_devicename_linux(self): - ''' - Test Linux API for plyer.devicename. - ''' - devicename = platform_import(platform='linux', - module_name='devicename' - ) - devicename_instance = devicename.instance() - - with patch.object(socket, - 'gethostname', - return_value='mocked_linux_hostname' - ) as _: - - evaluated_device_name = devicename_instance.device_name - self.assertEqual(evaluated_device_name, 'mocked_linux_hostname') - - @PlatformTest('macosx') - def test_devicename_macosx(self): - ''' - Test MacOSX API for plyer.devicename. - ''' - devicename = platform_import(platform='macosx', - module_name='devicename' - ) - devicename_instance = devicename.instance() - - with patch.object(socket, - 'gethostname', - return_value='mocked_macosx_hostname' - ) as _: - - evaluated_device_name = devicename_instance.device_name - self.assertEqual(evaluated_device_name, 'mocked_macosx_hostname') - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_email.py b/sbapp/plyer/tests/test_email.py deleted file mode 100644 index 60aa86f..0000000 --- a/sbapp/plyer/tests/test_email.py +++ /dev/null @@ -1,48 +0,0 @@ -''' -TestEmail -========= - -Tested platforms: - -* Windows -''' - -import unittest - -from mock import Mock, patch -from plyer.tests.common import PlatformTest, platform_import - - -class TestEmail(unittest.TestCase): - ''' - TestCase for plyer.email. - ''' - - @staticmethod - @PlatformTest('win') - def test_email_win(): - ''' - Test starting Windows email client for plyer.email. - ''' - email = platform_import( - platform='win', - module_name='email' - ) - - try: - test_mailto = 'mailto:recipient?subject=subject&body=text' - with patch(target='os.startfile', new=Mock()) as startfile: - email.instance().send( - recipient='recipient', - subject='subject', - text='text' - ) - startfile.assert_called_once_with(test_mailto) - except WindowsError: - # if WE is raised, email client isn't found, - # but the platform code works correctly - print('Mail client not found!') - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_facade.py b/sbapp/plyer/tests/test_facade.py deleted file mode 100644 index b49b15f..0000000 --- a/sbapp/plyer/tests/test_facade.py +++ /dev/null @@ -1,183 +0,0 @@ -''' -TestFacade -========== - -Tested platforms: - -* Android -* iOS -* Windows -* MacOS -* Linux -''' - -import unittest - -import sys -from types import MethodType - -from mock import Mock, patch - -import plyer - - -def mock_platform_module(mod, platform, cls): - ''' - Create a stub module for a specific platform. This module contains: - - * class inheriting from facade implementing the desired feature - * 'instance' function returning an instance of the implementing class - ''' - - # assemble an instance returned from the instance() function - # which is created from a dynamically created class - # .'> e.g.: - # - stub_inst = Mock( - __module__=mod, - __class__=type( - '{}{}'.format(platform.title(), cls), (object, ), { - '__module__': mod - } - ), - ) - - # manual 'return_value' assign to Mock, so that the instance() call - # can return stub_inst's own instance instead of creating another - # unnecessary Mock object - stub_inst.return_value = stub_inst - - # bind custom function returning the class name to stub_inst instance, - # so that instance().show() call requires 'self' i.e. instance parameter - # for the function to access the instance's class name - stub_inst.show = MethodType(lambda slf: slf, stub_inst) - - stub_mod = Mock(instance=stub_inst) - return stub_mod - - -# dummy pyjnius class to silence the import + config -class DummyJnius: - ''' - Mocked PyJNIus module. - ''' - - def __init__(self, *args, **kwargs): - class JavaClass: - ''' - Mocked PyJNIus JavaClass object. - ''' - - def __init__(self): - self.ANDROID_VERSION = None - self.SDK_INT = 1 - self.mActivity = None - - self.autoclass = lambda *a, **kw: JavaClass() - - -class TestFacade(unittest.TestCase): - ''' - TestCase for plyer.utils.Proxy and plyer.facades. - ''' - - def test_facade_existing_platforms(self): - ''' - Test for returning an object for Android API implementation - from Proxy object using a dynamically generated dummy objects. - ''' - _original = plyer.utils.platform - - for plat in {'android', 'ios', 'win', 'macosx', 'linux'}: - plyer.utils.platform = plat - - if plat == 'android': - # android platform automatically imports jnius - sys.modules['jnius'] = DummyJnius() - - # create stub module with instance func and class - stub_mod = mock_platform_module( - mod='plyer.platforms.{}.dummy'.format(plat), - platform=plyer.utils.platform, - cls='Dummy' - ) - - proxy_cls = plyer.utils.Proxy - target = 'builtins.__import__' - - with patch(target=target, return_value=stub_mod): - dummy = proxy_cls('dummy', stub_mod) - - self.assertEqual( - str(dummy.__class__).split("'")[1], - 'plyer.platforms.{}.dummy.{}Dummy'.format( - plat, plat.title() - ) - ) - self.assertEqual( - str(dummy.show().__class__).split("'")[1], - 'plyer.platforms.{}.dummy.{}Dummy'.format( - plat, plat.title() - ) - ) - - plyer.utils.platform = _original - - def test_facade_unknown(self): - ''' - Test fallback of Proxy to facade if there - is no such requested platform. - ''' - - _original = plyer.utils.platform - plyer.utils.platform = 'unknown' - - # no 'unknown' platform (folder), fallback to facade - class MockedProxy(plyer.utils.Proxy): - ''' - Partially mocked Proxy class, so that we pull the error - from traceback.print_exc to the test and check the calls. - ''' - - # _ensure_obj is called only once, to either - # get the platform object or fall back to facade - # therefore the three self.asserts below will return - # different values - expected_asserts = [True, False, False] - - def _ensure_obj(inst): - # called once, prints to stderr - - # mock stderr because traceback.print_exc uses it - # https://github.com/python/cpython/blob/ - # 16dfca4d829e45f36e71bf43f83226659ce49315/Lib/traceback.py#L99 - sys.stderr = Mock() - - # call the original function to trigger - # ImportError warnings in stderr - super(MockedProxy, inst)._ensure_obj() - - # Traceback (most recent call last): - # File "/app/plyer/utils.py", line 88, in _ensure_obj - # mod = __import__(module, fromlist='.') - # ImportError: No module named unknown.dummy - - # must not use self.assertX - # (has to be checked on the go!) - expected_bool = MockedProxy.expected_asserts.pop(0) - call_count = sys.stderr.write.call_count - assert (call_count == 6) == expected_bool, call_count - - # return stderr to the original state - sys.stderr = sys.__stderr__ - - proxy_cls = MockedProxy - facade = Mock() - dummy = proxy_cls('dummy', facade) - - self.assertEqual(dummy._mock_new_parent, facade) - plyer.utils.platform = _original - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_notification.py b/sbapp/plyer/tests/test_notification.py deleted file mode 100644 index 7177ad7..0000000 --- a/sbapp/plyer/tests/test_notification.py +++ /dev/null @@ -1,209 +0,0 @@ -''' -TestNotification -================ - -Tested platforms: - -* Windows -* Linux - notify-send, dbus -''' - -import unittest -import sys - -from time import sleep -from os.path import dirname, abspath, join - -from mock import Mock, patch -from plyer.tests.common import PlatformTest, platform_import - - -class MockedNotifySend: - ''' - Mocked object used instead of the console-like calling - of notify-send binary with parameters. - ''' - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - Linux notify-send binary is present on the system. - ''' - return binary == 'notify-send' - - @staticmethod - def call(args): - ''' - Mocked subprocess.call to check console parameters. - ''' - assert len(args) >= 3 - assert TestNotification.data['title'] in args - assert TestNotification.data['message'] in args - - @staticmethod - def warn(msg): - ''' - Mocked warnings.warn, so that we check the custom ImportError message. - ''' - assert 'dbus package is not installed' in msg - - -class TestNotification(unittest.TestCase): - ''' - TestCase for plyer.notification. - ''' - - data = { - 'title': 'title', - 'message': 'My Message\nis multiline', - 'app_name': 'Plyer Test', - 'app_icon': join( - dirname(abspath(__file__)), - 'images', 'kivy32.ico' - ), - 'timeout': 0.7 - } - - def show_notification(self, instance): - ''' - Call notify() from platform specific instance with sample data. - ''' - instance.notify(**self.data) - - @PlatformTest('win') - def test_notification_windows(self): - ''' - Test Windows API for plyer.notification. - ''' - import ctypes - from ctypes import ( - WINFUNCTYPE, POINTER, - create_unicode_buffer, - c_bool, c_int - ) - notif = platform_import( - platform='win', - module_name='notification' - ).instance() - enum_windows = ctypes.windll.user32.EnumWindows - get_class_name = ctypes.windll.user32.GetClassNameW - - # loop over windows and get refs to - # the opened plyer notifications - clsnames = [] - - def fetch_class(hwnd, *args): - ''' - EnumWindowsProc callback for EnumWindows. - ''' - buff = create_unicode_buffer(50) - get_class_name(hwnd, buff, 50) - - if 'Plyer' in buff.value: - clsnames.append(buff.value) - - # ensure it's not an empty facade - self.assertIn('WindowsNotification', str(notif)) - - # create enum function for EnumWindows - enum_windows_proc = WINFUNCTYPE( - # returns - c_bool, - - # input params: hwnd, lParam - POINTER(c_int), POINTER(c_int) - ) - - for i in range(3): - self.show_notification(notif) - - # the balloon needs some time to became visible in WinAPI - sleep(0.2) - - # fetch window class names - enum_windows( - # enum & params - enum_windows_proc(fetch_class), None - ) - - # 3 active balloons at the same time, - # class_name is incremented - see WindowsBalloonTip - self.assertEqual(len(clsnames), i + 1) - self.assertIn('PlyerTaskbar' + str(i), clsnames) - clsnames = [] - - @PlatformTest('linux') - def test_notification_dbus(self): - ''' - Test mocked Linux DBus for plyer.notification. - ''' - notif = platform_import( - platform='linux', - module_name='notification' - ) - self.assertIn('NotifyDbus', dir(notif)) - - # (3) mocked Interface called from dbus - interface = Mock() - interface.side_effect = (interface, ) - - # (2) mocked SessionBus called from dbus - session_bus = Mock() - session_bus.side_effect = (session_bus, ) - - # (1) mocked dbus for import - dbus = Mock(SessionBus=session_bus, Interface=interface) - - # inject the mocked module - self.assertNotIn('dbus', sys.modules) - sys.modules['dbus'] = dbus - - try: - notif = notif.instance() - self.assertIn('NotifyDbus', str(notif)) - - # call notify() - self.show_notification(notif) - - # check whether Mocks were called - dbus.SessionBus.assert_called_once() - - session_bus.get_object.assert_called_once_with( - 'org.freedesktop.Notifications', - '/org/freedesktop/Notifications' - ) - - interface.Notify.assert_called_once_with( - TestNotification.data['app_name'], - 0, - TestNotification.data['app_icon'], - TestNotification.data['title'], - TestNotification.data['message'], - [], {}, - TestNotification.data['timeout'] * 1000 - ) - finally: - del sys.modules['dbus'] - self.assertNotIn('dbus', sys.modules) - - @PlatformTest('linux') - def test_notification_notifysend(self): - ''' - Test mocked Linux notify-send for plyer.notification. - ''' - notif = platform_import( - platform='linux', - module_name='notification', - whereis_exe=MockedNotifySend.whereis_exe - ) - self.assertIn('NotifySendNotification', dir(notif)) - with patch(target='warnings.warn', new=MockedNotifySend.warn): - notif = notif.instance() - self.assertIn('NotifySendNotification', str(notif)) - - with patch(target='subprocess.call', new=MockedNotifySend.call): - self.assertIsNone(self.show_notification(notif)) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_screenshot.py b/sbapp/plyer/tests/test_screenshot.py deleted file mode 100644 index 931fac2..0000000 --- a/sbapp/plyer/tests/test_screenshot.py +++ /dev/null @@ -1,137 +0,0 @@ -''' -TestScreenshot -============== - -Tested platforms: - -* MacOS -* Linux -''' - -import unittest - -from os import mkdir, remove -from os.path import join, expanduser, exists - -from mock import patch -from plyer.tests.common import PlatformTest, platform_import - - -class MockedScreenCapture: - ''' - Mocked object used instead of the console-like calling - of screencapture binary with parameters. - ''' - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - MacOS screencapture binary is present on the system. - ''' - return binary == 'screencapture' - - @staticmethod - def call(args): - ''' - Mocked subprocess.call to check console parameters. - ''' - assert len(args) == 2, len(args) - assert args[0] == 'screencapture', args - assert args[1] == join( - expanduser('~'), 'Pictures', 'screenshot.png' - ), args - with open(args[1], 'w') as scr: - scr.write('') - - -class MockedXWD: - ''' - Mocked object used instead of the console-like calling - of X11 xwd binary with parameters. - ''' - @staticmethod - def whereis_exe(binary): - ''' - Mock whereis_exe, so that it looks like - X11 xwd binary is present on the system. - ''' - return binary == 'xwd' - - @staticmethod - def call(args, stdout): - ''' - Mocked subprocess.call to check console parameters. - ''' - assert len(args) == 3, args - assert args[0] == 'xwd', args - assert args[1:] == ['-silent', '-root'], args - assert stdout.name == join( - expanduser('~'), 'Pictures', 'screenshot.xwd' - ), stdout.name - with open(stdout.name, 'w') as scr: - scr.write('') - - -class TestScreenshot(unittest.TestCase): - ''' - TestCase for plyer.screenshot. - ''' - - def setUp(self): - path = join(expanduser('~'), 'Pictures') - if not exists(path): - mkdir(path) - - @PlatformTest('macosx') - def test_screenshot_screencapture(self): - ''' - Test mocked MacOS screencapture for plyer.screenshot. - ''' - scr = platform_import( - platform='macosx', - module_name='screenshot', - whereis_exe=MockedScreenCapture.whereis_exe - ) - - # such class exists in screenshot module - self.assertIn('OSXScreenshot', dir(scr)) - - # the required instance is created - scr = scr.instance() - self.assertIn('OSXScreenshot', str(scr)) - - # move capture from context manager to run without mock - with patch(target='subprocess.call', new=MockedScreenCapture.call): - self.assertIsNone(scr.capture()) - - self.assertTrue(exists(scr.file_path)) - remove(scr.file_path) - - @PlatformTest('linux') - def test_screenshot_xwd(self): - ''' - Test mocked X11 xwd for plyer.screenshot. - ''' - scr = platform_import( - platform='linux', - module_name='screenshot', - whereis_exe=MockedXWD.whereis_exe - ) - - # such class exists in screenshot module - self.assertIn('LinuxScreenshot', dir(scr)) - - # the required instance is created - scr = scr.instance() - self.assertIn('LinuxScreenshot', str(scr)) - - # move capture from context manager to run without mock - with patch(target='subprocess.call', new=MockedXWD.call): - self.assertIsNone(scr.capture()) - - self.assertTrue(exists(scr.file_path)) - remove(scr.file_path) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_storagepath.py b/sbapp/plyer/tests/test_storagepath.py deleted file mode 100644 index 35b8139..0000000 --- a/sbapp/plyer/tests/test_storagepath.py +++ /dev/null @@ -1,72 +0,0 @@ -''' -TestStoragePath -=============== - -Tested platforms: - -* macOS -''' - -import unittest - -from plyer.tests.common import platform_import, PlatformTest - - -class TestStoragePath(unittest.TestCase): - ''' - TestCase for plyer.storagepath. - ''' - - @PlatformTest('macosx') - def test_storagepath_macosx(self): - ''' - Test macOS for plyer.storagepath. - ''' - storagepath = platform_import( - platform='macosx', - module_name='storagepath' - ) - - self.assertIn('OSXStoragePath', dir(storagepath)) - storagepath = storagepath.instance() - self.assertIn('OSXStoragePath', str(storagepath)) - - path_format = 'file:///Users/' - - self.assertIn(path_format, storagepath.get_home_dir()) - self.assertIn('/', storagepath.get_root_dir()) - self.assertIn(path_format, storagepath.get_documents_dir()) - self.assertIn(path_format, storagepath.get_downloads_dir()) - self.assertIn(path_format, storagepath.get_videos_dir()) - self.assertIn(path_format, storagepath.get_music_dir()) - self.assertIn(path_format, storagepath.get_pictures_dir()) - self.assertIn(path_format, storagepath.get_application_dir()) - - @PlatformTest('win') - def test_storagepath_windows(self): - ''' - Test win for plyer.storagepath. - ''' - storagepath = platform_import( - platform='win', - module_name='storagepath' - ) - - self.assertIn('WinStoragePath', dir(storagepath)) - storagepath = storagepath.instance() - self.assertIn('WinStoragePath', str(storagepath)) - - path_format = ':\\' - - self.assertIn(path_format, storagepath.get_home_dir()) - self.assertIn(path_format, storagepath.get_root_dir()) - self.assertIn(path_format, storagepath.get_documents_dir()) - self.assertIn(path_format, storagepath.get_downloads_dir()) - self.assertIn(path_format, storagepath.get_videos_dir()) - self.assertIn(path_format, storagepath.get_music_dir()) - self.assertIn(path_format, storagepath.get_pictures_dir()) - self.assertIn(path_format, storagepath.get_application_dir()) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_uniqueid.py b/sbapp/plyer/tests/test_uniqueid.py deleted file mode 100644 index 629c840..0000000 --- a/sbapp/plyer/tests/test_uniqueid.py +++ /dev/null @@ -1,78 +0,0 @@ -''' -TestUniqueID -============ - -Tested platforms: - -* Windows -''' - -import unittest -from mock import patch, Mock -from plyer.tests.common import PlatformTest, platform_import - - -class TestUniqueID(unittest.TestCase): - ''' - TestCase for plyer.uniqueid. - ''' - - def test_uniqueid(self): - ''' - General all platform test for plyer.uniqueid. - ''' - from plyer import uniqueid - self.assertTrue(len(uniqueid.id) > 0) - - @PlatformTest('win') - def test_uniqueid_win(self): - ''' - Test Windows API for plyer.uniqueid. - ''' - try: - from winreg import ( - HKEY_LOCAL_MACHINE as HKLM, - KEY_READ as READ, KEY_WOW64_64KEY as VIEW - ) - except ImportError: - from _winreg import ( - HKEY_LOCAL_MACHINE as HKLM, - KEY_READ as READ, KEY_WOW64_64KEY as VIEW - ) - - # mock the 'regedit' alias for winreg, - # see if the import passes and get the instance - regedit_mod = 'plyer.platforms.win.uniqueid.regedit' - with patch(target=regedit_mod): - uniqueid_ = platform_import( - platform='win', - module_name='uniqueid' - ) - uniqueid = uniqueid_.instance() - self.assertIsInstance(uniqueid_.regedit, Mock) - - # out of mocking block, regedit should be a winreg module - self.assertIsInstance(uniqueid_.regedit, type(unittest)) - - # OpenKey is supposed to return a handle to registry key - regedit_opkey = 'plyer.platforms.win.uniqueid.regedit.OpenKey' - with patch(target=regedit_opkey, return_value='unicorn') as opkey: - - # QueryValueEx is supposed to return 2 packed values - # (key, type_id) - queryval = 'plyer.platforms.win.uniqueid.regedit.QueryValueEx' - retval = ('unique', None) - with patch(target=queryval, return_value=retval) as query: - uid = uniqueid.id - opkey.assert_called_once_with( - # key, subkey - HKLM, r'SOFTWARE\\Microsoft\\Cryptography', - # reserved integer (has to be 0 - zero), access mask - 0, READ | VIEW - ) - query.assert_called_once_with('unicorn', 'MachineGuid') - self.assertEqual(uid, retval[0]) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/tests/test_utils.py b/sbapp/plyer/tests/test_utils.py deleted file mode 100644 index 3532b76..0000000 --- a/sbapp/plyer/tests/test_utils.py +++ /dev/null @@ -1,417 +0,0 @@ -''' -TestUtils -========= - -Tested platforms: - -* Android -* iOS -* Windows -* MacOS -* Linux -''' - -import unittest -from mock import patch - - -class TestUtils(unittest.TestCase): - ''' - TestCase for plyer.utils. - ''' - - def cutter(self, part, string): - ''' - Cut off a part of a string if it contains a substring, - otherwise raise an error. - ''' - self.assertIn(part, string) - return string[len(part):] - - def test_deprecated_function(self): - ''' - Test printed out warning with @deprecated decorator - on a function without any arguments. - ''' - - from plyer.utils import deprecated - - @deprecated - def function(): - ''' - Dummy deprecated function. - ''' - return 1 - - with patch(target='warnings.warn') as stderr: - self.assertEqual(function(), 1) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function function', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_function().\n', args) - - args, _ = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated function. - ''', - )) - - def test_deprecated_function_arg(self): - ''' - Test printed out warning with @deprecated decorator - on a function with arguments. - ''' - - from plyer.utils import deprecated - - @deprecated - def function_with_arg(arg): - ''' - Dummy deprecated function with arg. - ''' - return arg - - with patch(target='warnings.warn') as stderr: - self.assertEqual(function_with_arg(1), 1) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function function_with_arg', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_function_arg().\n', args) - - args, _ = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated function with arg. - ''', - )) - - def test_deprecated_function_kwarg(self): - ''' - Test printed out warning with @deprecated decorator - on a function with keyword arguments. - ''' - - from plyer.utils import deprecated - - @deprecated - def function_with_kwarg(kwarg): - ''' - Dummy deprecated function with kwarg. - ''' - return kwarg - - with patch(target='warnings.warn') as stderr: - self.assertEqual(function_with_kwarg(kwarg=1), 1) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function function_with_kwarg', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_function_kwarg().\n', args) - - args, _ = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated function with kwarg. - ''', - )) - - def test_deprecated_class_method(self): - ''' - Test printed out warning with @deprecated decorator - on a instance bound method. - ''' - - from plyer.utils import deprecated - - class Class: - ''' - Dummy class with deprecated method method. - ''' - def __init__(self, *args, **kwargs): - self.args = args - self.kwargs = kwargs - - @deprecated - def method(self): - ''' - Dummy deprecated method. - ''' - return (self.args, self.kwargs) - - with patch(target='warnings.warn') as stderr: - args = (1, 2, 3) - kwargs = dict(x=1, y=2) - - cls = Class(*args, **kwargs) - self.assertEqual(cls.method(), (args, kwargs)) - - args, kwargs = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function method', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_class_method().\n', args) - - args, kwargs = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated method. - ''', - )) - - def test_deprecated_class_static_none(self): - ''' - Test printed out warning with @deprecated decorator - on a static method without arguments. - ''' - - from plyer.utils import deprecated - - class Class: - ''' - Dummy class with deprecated static method. - ''' - args = None - kwargs = None - - def __init__(self, *args, **kwargs): - Class.args = args - Class.kwargs = kwargs - - @staticmethod - @deprecated - def static(): - ''' - Dummy deprecated static method. - ''' - return (Class.args, Class.kwargs) - - with patch(target='warnings.warn') as stderr: - self.assertEqual(Class.static(), (None, None)) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function static', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter( - 'by test_deprecated_class_static_none().\n', args - ) - - args, _ = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated static method. - ''', - )) - - def test_deprecated_class_static_argskwargs(self): - ''' - Test printed out warning with @deprecated decorator - on a static method with arguments and keyword argument. - ''' - - from plyer.utils import deprecated - - class Class: - ''' - Dummy class with deprecated static method. - ''' - args = None - kwargs = None - - def __init__(self, *args, **kwargs): - Class.args = args - Class.kwargs = kwargs - - @staticmethod - @deprecated - def static(): - ''' - Dummy deprecated static method. - ''' - return (Class.args, Class.kwargs) - - with patch(target='warnings.warn') as stderr: - args = (1, 2, 3) - kwargs = dict(x=1, y=2) - - cls = Class(*args, **kwargs) - self.assertEqual(cls.static(), (args, kwargs)) - - args, kwargs = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function static', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter( - 'by test_deprecated_class_static_argskwargs().\n', args - ) - - args, kwargs = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated static method. - ''', - )) - - def test_deprecated_class_clsmethod(self): - ''' - Test printed out warning with @deprecated decorator - on a class bound method. - ''' - - from plyer.utils import deprecated - - class Class: - ''' - Dummy class with deprecated class method. - ''' - args = None - kwargs = None - - @classmethod - @deprecated - def clsmethod(cls): - ''' - Dummy deprecated class method. - ''' - return (cls.args, cls.kwargs) - - with patch(target='warnings.warn') as stderr: - self.assertEqual(Class.clsmethod(), (None, None)) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('deprecated function clsmethod', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_class_clsmethod().\n', args) - - args, _ = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated class method. - ''', - )) - - def test_deprecated_class(self): - ''' - Test printed out warning with @deprecated decorator on a class. - ''' - - from plyer.utils import deprecated - - @deprecated - class Class: - ''' - Dummy deprecated class. - ''' - def __init__(self, *args, **kwargs): - self.args = args - self.kwargs = kwargs - - with patch(target='warnings.warn') as stderr: - args = (1, 2, 3) - kwargs = dict(x=1, y=2) - - cls = Class(*args, **kwargs) - self.assertIsInstance(cls, Class) - self.assertEqual(cls.args, args) - self.assertEqual(cls.kwargs, kwargs) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('Creating an instance', args) - args = self.cutter('deprecated class Class in', args) - args = self.cutter(__name__, args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_class().\n', args) - - args, kwargs = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated class. - ''', - )) - - def test_deprecated_class_inherited(self): - ''' - Test printed out warning with @deprecated decorator on a class - which inherits from a deprecated class. - ''' - - from plyer.utils import deprecated - - @deprecated - class Class: - ''' - Dummy deprecated class. - ''' - def __init__(self, *args, **kwargs): - self.args = args - self.kwargs = kwargs - - class Inherited(Class): - ''' - Dummy class inheriting from a dummy deprecated class. - ''' - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.args = args - self.kwargs = kwargs - - with patch(target='warnings.warn') as stderr: - args = (1, 2, 3) - kwargs = dict(x=1, y=2) - - cls = Inherited(*args, **kwargs) - self.assertIsInstance(cls, Inherited) - self.assertEqual(cls.args, args) - self.assertEqual(cls.kwargs, kwargs) - - args, _ = stderr.call_args_list[0] - args = args[0] - args = self.cutter('[WARNING] ', args) - args = self.cutter('Creating an instance', args) - args = self.cutter('deprecated class Class in', args) - args = self.cutter(__name__, args) - args = self.cutter('Called from', args) - args = self.cutter('test_utils.py', args) - args = self.cutter('by test_deprecated_class_inherited().\n', args) - - args, kwargs = stderr.call_args_list[1] - self.assertEqual(args, ( - ''' - Dummy deprecated class. - ''', - )) - - -if __name__ == '__main__': - unittest.main() diff --git a/sbapp/plyer/utils.py b/sbapp/plyer/utils.py index 101763e..573075d 100644 --- a/sbapp/plyer/utils.py +++ b/sbapp/plyer/utils.py @@ -9,6 +9,7 @@ from os import environ from os import path from sys import platform as _sys_platform import sys +import RNS class Platform: @@ -91,8 +92,10 @@ class Proxy: # do the import try: name = object.__getattribute__(self, '_name') - module = 'plyer.platforms.{}.{}'.format( - platform, name) + if RNS.vendor.platformutils.is_android(): + module = 'plyer.platforms.{}.{}'.format(platform, name) + else: + module = 'sbapp.plyer.platforms.{}.{}'.format(platform, name) mod = __import__(module, fromlist='.') obj = mod.instance() except Exception: 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 diff --git a/sbapp/services/sidebandservice.py b/sbapp/services/sidebandservice.py index 43da2ae..e5a4b43 100644 --- a/sbapp/services/sidebandservice.py +++ b/sbapp/services/sidebandservice.py @@ -38,10 +38,12 @@ if RNS.vendor.platformutils.get_platform() == "android": AndroidString = autoclass('java.lang.String') NotificationManager = autoclass('android.app.NotificationManager') Context = autoclass('android.content.Context') + JString = autoclass('java.lang.String') if android_api_version >= 26: NotificationBuilder = autoclass('android.app.Notification$Builder') NotificationChannel = autoclass('android.app.NotificationChannel') + RingtoneManager = autoclass('android.media.RingtoneManager') from usb4a import usb from usbserial4a import serial4a @@ -58,68 +60,88 @@ class SidebandService(): 0x1a86: [0x5523, 0x7523, 0x55D4], # Qinheng 0x0483: [0x5740], # ST CDC 0x2E8A: [0x0005, 0x000A], # Raspberry Pi Pico + 0x239A: [0x8029], # Adafruit (RAK4631) + 0x303A: [0x1001, 0x4001], # ESP-32S3 } 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.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)) - - # 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 - 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) + 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) + 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) + self.notification_channel.setShowBadge(True) + self.notification_service.createNotificationChannel(self.notification_channel) + + 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 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) + + 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) - if not self.notification_intent: 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) - self.notification_intent = PendingIntent.getActivity(self.app_context, 0, notification_intent, 0) + 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) + notification.setContentIntent(self.notification_intent) + notification.setAutoCancel(True) - built_notification = notification.build() - self.notification_service.notify(0, built_notification) + 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(): @@ -147,6 +169,18 @@ class SidebandService(): return True + def update_power_restrictions(self): + package_name = "io.unsigned.sideband" + if RNS.vendor.platformutils.is_android(): + if android_api_version >= 28: + if self.power_manager != None: + if self.power_manager.isIgnoringBatteryOptimizations(package_name): + self.power_restricted = False + else: + self.power_restricted = True + + self.sideband.setstate("android.power_restricted", self.power_restricted) + def android_location_callback(self, **kwargs): self._raw_gps = kwargs self._last_gps_update = time.time() @@ -198,6 +232,7 @@ class SidebandService(): self.app_context = None self.wifi_manager = None self.power_manager = None + self.power_restricted = False self.usb_devices = [] self.usb_device_filter = SidebandService.usb_device_filter @@ -206,6 +241,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() @@ -233,6 +270,7 @@ class SidebandService(): self.sideband.start() self.update_connectivity_type() + self.update_power_restrictions() if RNS.vendor.platformutils.is_android(): RNS.log("Discovered USB devices: "+str(self.usb_devices), RNS.LOG_EXTREME) @@ -346,7 +384,29 @@ class SidebandService(): else: rs = "Interface Down" - stat += "[b]RNode[/b]\n{rs}\n\n".format(rs=rs) + bs = "" + bat_state = self.sideband.interface_rnode.get_battery_state_string() + bat_percent = self.sideband.interface_rnode.get_battery_percent() + if bat_state != "unknown": + bs = f"\nBattery at {bat_percent}%" + + 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: @@ -446,11 +506,23 @@ 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() 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/share/flasher.html b/sbapp/share/flasher.html new file mode 100644 index 0000000..a45de5f --- /dev/null +++ b/sbapp/share/flasher.html @@ -0,0 +1,33 @@ + + + + + + +Sideband Repository + + + + +

Start | Software | RNode Flasher | Guides


+
Sideband includes a copy of the web-based RNode Flasher developed by Liam Cottle. You can use this flasher to install and provision the RNode firmware on any compatible boards.
+
+Please note! Your browser must support Web-USB for this to work.
+
+To use the flasher, you will need firmware packages for the boards you want use. You can obtain these in different ways: + +
+
+
+
+

+ diff --git a/sbapp/share/guides.html b/sbapp/share/guides.html index 143b70c..cc1741d 100644 --- a/sbapp/share/guides.html +++ b/sbapp/share/guides.html @@ -9,16 +9,16 @@ -

Start | Software | Guides


+

Start | Software | RNode Flasher | Guides



Welcome to the Guide Section!

From here, you can browse or download various included manuals, documentation, references and guides. +

\ No newline at end of file diff --git a/sbapp/share/index.html b/sbapp/share/index.html index 7143405..4f34587 100644 --- a/sbapp/share/index.html +++ b/sbapp/share/index.html @@ -10,7 +10,7 @@ -

Start | Software | Guides


Hello!

+

Start | Software | RNode Flasher | Guides


Hello!

diff --git a/sbapp/share/pkgs.html b/sbapp/share/pkgs.html index 0ed8470..d022983 100644 --- a/sbapp/share/pkgs.html +++ b/sbapp/share/pkgs.html @@ -9,10 +9,10 @@ -

Start | Software | Guides


+

Start | Software | RNode Flasher | Guides



Welcome to the Software Library!

From here, you can download installable Python Wheel packages of Reticulum and various other auxillary programs and utilities. +

diff --git a/sbapp/sideband/audioproc.py b/sbapp/sideband/audioproc.py new file mode 100644 index 0000000..215fcd8 --- /dev/null +++ b/sbapp/sideband/audioproc.py @@ -0,0 +1,168 @@ +import os +import io +import math +import time +import struct +import numpy as np +import RNS +import LXMF + +if RNS.vendor.platformutils.is_android(): + from LXST.Codecs.libs.pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter + from LXST.Codecs.libs.pydub import AudioSegment +else: + from LXST.Codecs.libs.pyogg import OpusFile, OpusBufferedEncoder, OggOpusWriter + from LXST.Codecs.libs.pydub import AudioSegment + +codec2_modes = { + # LXMF.AM_CODEC2_450PWB: ???, # No bindings + # LXMF.AM_CODEC2_450: ???, # No bindings + LXMF.AM_CODEC2_700C: 700, + LXMF.AM_CODEC2_1200: 1200, + LXMF.AM_CODEC2_1300: 1300, + LXMF.AM_CODEC2_1400: 1400, + LXMF.AM_CODEC2_1600: 1600, + LXMF.AM_CODEC2_2400: 2400, + LXMF.AM_CODEC2_3200: 3200, +} + +def samples_from_ogg(file_path=None, output_rate=8000): + if file_path != None and os.path.isfile(file_path): + opus_file = OpusFile(file_path) + audio = AudioSegment( + bytes(opus_file.as_array()), + frame_rate=opus_file.frequency, + sample_width=opus_file.bytes_per_sample, + channels=opus_file.channels) + + audio = audio.split_to_mono()[0] + audio = audio.apply_gain(-audio.max_dBFS) + audio = audio.set_frame_rate(output_rate) + audio = audio.set_sample_width(2) + + return audio.get_array_of_samples() + +def resample(samples, width, channels, input_rate, output_rate, normalize): + audio = AudioSegment( + samples, + frame_rate=input_rate, + sample_width=width, + channels=channels) + + if normalize: + audio = audio.apply_gain(-audio.max_dBFS) + + resampled_audio = audio.set_frame_rate(output_rate) + return resampled_audio.get_array_of_samples().tobytes() + +def samples_to_ogg(samples=None, file_path=None, normalize=False, input_channels=1, input_sample_width=2, input_rate=8000, output_rate=12000, profile="audio"): + try: + if file_path != None and samples != None: + if input_rate != output_rate or normalize: + samples = resample(samples, input_sample_width, input_channels, input_rate, output_rate, normalize) + + pcm_data = io.BytesIO(samples) + channels = input_channels; samples_per_second = output_rate; bytes_per_sample = 2 + frame_duration_ms = 60 + + opus_buffered_encoder = OpusBufferedEncoder() + opus_buffered_encoder.set_application(profile) + opus_buffered_encoder.set_sampling_frequency(samples_per_second) + opus_buffered_encoder.set_channels(channels) + opus_buffered_encoder.set_frame_size(frame_duration_ms) + ogg_opus_writer = OggOpusWriter(file_path, opus_buffered_encoder) + + frame_duration = frame_duration_ms/1000.0 + frame_size = int(frame_duration * samples_per_second) + bytes_per_frame = frame_size*bytes_per_sample + + ogg_opus_writer.write(memoryview(bytearray(samples))) + ogg_opus_writer.close() + + return True + + except Exception as e: + RNS.trace_exception(e) + return False + +def samples_to_wav(samples=None, file_path=None): + if samples != None and file_path != None: + import wave + with wave.open(file_path, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) + wf.setframerate(8000) + wf.writeframes(samples) + return True + +def voice_processing(input_path): + try: + # Moving to LXST native processing + return None + + except Exception as e: + return None + +def detect_codec2(): + try: + import pycodec2 + return True + except Exception as e: + RNS.log("Could not import codec2 module, libcodec2 is probably not installed or available", RNS.LOG_ERROR) + RNS.trace_exception(e) + + return False + +# Samples must be 8KHz, 16-bit, 1 channel +def encode_codec2(samples, mode): + ap_start = time.time() + import pycodec2 + if not mode in codec2_modes: + return None + + c2 = pycodec2.Codec2(codec2_modes[mode]) + SPF = c2.samples_per_frame() + PACKET_SIZE = SPF * 2 # 16-bit samples + STRUCT_FORMAT = '{}h'.format(SPF) + F_FRAMES = len(samples)/SPF + N_FRAMES = math.floor(len(samples)/SPF) + # TODO: Add padding to align to whole frames + frames = np.array(samples[0:N_FRAMES*SPF], dtype=np.int16) + + encoded = b"" + for pi in range(0, N_FRAMES): + pstart = pi*SPF + pend = (pi+1)*SPF + frame = frames[pstart:pend] + encoded_packet = c2.encode(frame) + encoded += encoded_packet + + ap_duration = time.time() - ap_start + RNS.log("Codec2 encoding complete in "+RNS.prettytime(ap_duration)+", bytes out: "+str(len(encoded)), RNS.LOG_DEBUG) + + return encoded + +def decode_codec2(encoded_bytes, mode): + ap_start = time.time() + import pycodec2 + if not mode in codec2_modes: + return None + + c2 = pycodec2.Codec2(codec2_modes[mode]) + SPF = c2.samples_per_frame() + BPF = c2.bytes_per_frame() + STRUCT_FORMAT = '{}h'.format(SPF) + N_FRAMES = math.floor(len(encoded_bytes)/BPF) + + decoded = b"" + for pi in range(0, N_FRAMES): + pstart = pi*BPF + pend = (pi+1)*BPF + encoded_packet = encoded_bytes[pstart:pend] + decoded_frame = c2.decode(encoded_packet) + decoded += struct.pack(STRUCT_FORMAT, *decoded_frame) + + ap_duration = time.time() - ap_start + RNS.log("Codec2 decoding complete in "+RNS.prettytime(ap_duration)+", samples out: "+str(len(decoded)), RNS.LOG_DEBUG) + + return decoded \ No newline at end of file diff --git a/sbapp/sideband/certgen.py b/sbapp/sideband/certgen.py new file mode 100644 index 0000000..631a8b4 --- /dev/null +++ b/sbapp/sideband/certgen.py @@ -0,0 +1,106 @@ +# MIT License +# +# Copyright (c) 2024 Mark Qvist / unsigned.io. +# +# 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. + +KEY_PASSPHRASE = None +LOADED_KEY = None + +import os +import RNS +import datetime +from cryptography import x509 +from cryptography.x509.oid import NameOID +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.serialization import load_pem_private_key + +from cryptography import __version__ as cryptography_version_str +try: + cryptography_major_version = int(cryptography_version_str.split(".")[0]) +except: + RNS.log(f"Could not determine PyCA/cryptography version: {e}", RNS.LOG_ERROR) + RNS.log(f"Assuming recent version with automatic backend selection", RNS.LOG_ERROR) + +def get_key(key_path, force_reload=False): + KEY_PATH = key_path + key = None + if LOADED_KEY != None and not force_reload: + return LOADED_KEY + elif os.path.isfile(KEY_PATH): + with open(KEY_PATH, "rb") as f: + if cryptography_major_version > 3: + key = load_pem_private_key(f.read(), KEY_PASSPHRASE) + else: + from cryptography.hazmat.backends import default_backend + key = load_pem_private_key(f.read(), KEY_PASSPHRASE, backend=default_backend()) + else: + if cryptography_major_version > 3: + key = ec.generate_private_key(curve=ec.SECP256R1()) + else: + from cryptography.hazmat.backends import default_backend + key = ec.generate_private_key(curve=ec.SECP256R1(), backend=default_backend()) + + if KEY_PASSPHRASE == None: + key_encryption = serialization.NoEncryption() + else: + key_encryption = serialization.BestAvailableEncryption(KEY_PASSPHRASE) + + with open(KEY_PATH, "wb") as f: + f.write(key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=key_encryption)) + + return key + +def gen_cert(cert_path, key): + CERT_PATH = cert_path + cert_attrs = [x509.NameAttribute(NameOID.COUNTRY_NAME, "NA"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "None"), + x509.NameAttribute(NameOID.LOCALITY_NAME, "Earth"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Sideband"), + x509.NameAttribute(NameOID.COMMON_NAME, "Sideband Repository")] + + issuer = x509.Name(cert_attrs) + subject = issuer + + cb = x509.CertificateBuilder() + cb = cb.subject_name(subject) + cb = cb.issuer_name(issuer) + cb = cb.public_key(key.public_key()) + cb = cb.serial_number(x509.random_serial_number()) + cb = cb.not_valid_before(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(days=-14)) + cb = cb.not_valid_after(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(days=3652)) + cb = cb.add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False) + + if cryptography_major_version > 3: + cert = cb.sign(key, hashes.SHA256()) + else: + from cryptography.hazmat.backends import default_backend + cert = cb.sign(key, hashes.SHA256(), backend=default_backend()) + + with open(CERT_PATH, "wb") as f: + f.write(cert.public_bytes(serialization.Encoding.PEM)) + +def ensure_certificate(key_path, cert_path): + gen_cert(cert_path, get_key(key_path)) + return cert_path \ No newline at end of file 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 80ce3e0..baef83b 100644 --- a/sbapp/sideband/core.py +++ b/sbapp/sideband/core.py @@ -1,25 +1,31 @@ import RNS import LXMF import threading -import plyer import os.path import time import struct import sqlite3 import random import shlex +import re +import gc import RNS.vendor.umsgpack as msgpack import RNS.Interfaces.Interface as Interface +from LXMF import pn_announce_data_is_valid import multiprocessing.connection +from copy import deepcopy from threading import Lock +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 from jnius import autoclass, cast # Squelch excessive method signature logging import jnius.reflect @@ -33,7 +39,8 @@ if RNS.vendor.platformutils.get_platform() == "android": jnius.reflect.log_method = mod jnius.reflect.log = redirect_log() ############################################ - +else: + import sbapp.plyer as plyer class PropagationNodeDetector(): EMITTED_DELTA_GRACE = 300 @@ -41,38 +48,52 @@ class PropagationNodeDetector(): aspect_filter = "lxmf.propagation" - def received_announce(self, destination_hash, announced_identity, app_data): + def received_announce(self, destination_hash, announced_identity, app_data, announce_packet_hash): try: if app_data != None and len(app_data) > 0: - unpacked = msgpack.unpackb(app_data) - node_active = unpacked[0] - emitted = unpacked[1] - hops = RNS.Transport.hops_to(destination_hash) + if pn_announce_data_is_valid(app_data): + unpacked = msgpack.unpackb(app_data) + node_active = unpacked[2] + emitted = unpacked[1] + hops = RNS.Transport.hops_to(destination_hash) - age = time.time() - emitted - if age < 0: - RNS.log("Warning, propagation node announce emitted in the future, possible timing inconsistency or tampering attempt.") - if age < -1*PropagationNodeDetector.EMITTED_DELTA_GRACE: - raise ValueError("Announce timestamp too far in the future, discarding it") + age = time.time() - emitted + if age < 0: + RNS.log("Warning, propagation node announce emitted in the future, possible timing inconsistency or tampering attempt.") + if age < -1*PropagationNodeDetector.EMITTED_DELTA_GRACE: + raise ValueError("Announce timestamp too far in the future, discarding it") - if age > -1*PropagationNodeDetector.EMITTED_DELTA_IGNORE: - # age = 0 - pass + if age > -1*PropagationNodeDetector.EMITTED_DELTA_IGNORE: + # age = 0 + pass - RNS.log("Detected active propagation node "+RNS.prettyhexrep(destination_hash)+" emission "+str(age)+" seconds ago, "+str(hops)+" hops away") - self.owner.log_announce(destination_hash, RNS.prettyhexrep(destination_hash).encode("utf-8"), dest_type=PropagationNodeDetector.aspect_filter) + if self.owner_app != None: stat_endpoint = self.owner_app.sideband + else: stat_endpoint = self.owner - if self.owner.config["lxmf_propagation_node"] == None: - if self.owner.active_propagation_node == None: - self.owner.set_active_propagation_node(destination_hash) - else: - prev_hops = RNS.Transport.hops_to(self.owner.active_propagation_node) - if hops <= prev_hops: + link_stats = {"rssi": stat_endpoint.reticulum.get_packet_rssi(announce_packet_hash), + "snr": stat_endpoint.reticulum.get_packet_snr(announce_packet_hash), + "q": stat_endpoint.reticulum.get_packet_q(announce_packet_hash)} + + RNS.log("Detected active propagation node "+RNS.prettyhexrep(destination_hash)+" emission "+str(age)+" seconds ago, "+str(hops)+" hops away", 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: + if self.owner.active_propagation_node == None: self.owner.set_active_propagation_node(destination_hash) else: - pass + prev_hops = RNS.Transport.hops_to(self.owner.active_propagation_node) + if hops <= prev_hops: + self.owner.set_active_propagation_node(destination_hash) + else: + pass + else: + pass + else: - pass + 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)}", RNS.LOG_EXTREME) except Exception as e: RNS.log("Error while processing received propagation node announce: "+str(e)) @@ -82,116 +103,190 @@ class PropagationNodeDetector(): self.owner_app = owner.owner_app class SidebandCore(): - CONV_P2P = 0x01 - CONV_GROUP = 0x02 - CONV_BROADCAST = 0x03 + 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_INTERVAL = 60 - SERVICE_TELEMETRY_INTERVAL = 300 + 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 = 6 # In seconds + IF_CHANGE_ANNOUNCE_MIN_INTERVAL = 3.5 # In seconds AUTO_ANNOUNCE_RANDOM_MIN = 90 # In minutes - AUTO_ANNOUNCE_RANDOM_MAX = 480 # In minutes + AUTO_ANNOUNCE_RANDOM_MAX = 300 # In minutes DEFAULT_APPEARANCE = ["account", [0,0,0,1], [1,1,1,1]] + LOG_DEQUE_MAXLEN = 128 + + ERROR_INVALID_BLE_MTU = 0x20 + aspect_filter = "lxmf.delivery" - def received_announce(self, destination_hash, announced_identity, app_data): + def received_announce(self, destination_hash, announced_identity, app_data, announce_packet_hash): # Add the announce to the directory announce # stream logger - self.log_announce(destination_hash, app_data, dest_type=SidebandCore.aspect_filter) - def __init__(self, owner_app, is_service=False, is_client=False, android_app_dir=None, verbose=False, owner_service=None, service_context=None, is_daemon=False): + if self.reticulum != None: + link_stats = {"rssi": self.reticulum.get_packet_rssi(announce_packet_hash), + "snr": self.reticulum.get_packet_snr(announce_packet_hash), + "q": self.reticulum.get_packet_q(announce_packet_hash)} + + # This reformats the new v0.5.0 announce data back to the expected format + # for 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"" + if dn != None: + app_data = dn.encode("utf-8") + + self.log_announce(destination_hash, app_data, dest_type=SidebandCore.aspect_filter, stamp_cost=sc, link_stats=link_stats) + + 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 + self.ptt_player = None + self.ptt_player_lock = threading.Lock() + self.last_msg_audio = None + self.ui_recording = False self.db = None + self.db_lock = threading.Lock() if not self.is_service and not self.is_client: self.is_standalone = True 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 self.webshare_server = None + self.voice_running = False + self.telephone = None self.telemeter = None self.telemetry_running = False 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 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 = {} + self.default_lxm_limit = 128*1000 self.state_db = {} self.state_lock = Lock() + self.message_router = None self.rpc_connection = None + self.rpc_lock = Lock() self.service_stopped = False self.service_context = service_context self.owner_service = owner_service + self.allow_service_dispatch = True + self.version_str = "" + self.config_template = rns_config + self.default_config_template = rns_config - 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.cache_dir = self.app_dir+"/cache" + 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: + self.app_dir = config_path + + self.cache_dir = os.path.join(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: + 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(): - core_path = os.path.abspath(__file__) self.asset_dir = core_path.replace("/sideband/core.py", "/assets") elif RNS.vendor.platformutils.get_platform() == "linux": - core_path = os.path.abspath(__file__) self.asset_dir = core_path.replace("/sideband/core.py", "/assets") elif RNS.vendor.platformutils.is_windows(): - core_path = os.path.abspath(__file__) 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.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.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 = os.path.join(self.cache_dir, "share") + if not os.path.isdir(self.share_cache): + os.makedirs(self.share_cache) + + 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.webshare_dir = "./share/" + 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/" + else: + 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 = 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() self.first_run = True self.saving_configuration = False self.last_lxmf_announce = 0 self.last_if_change_announce = 0 self.interface_local_adding = False - self.next_auto_announce = time.time() + 60*(random.random()*(SidebandCore.AUTO_ANNOUNCE_RANDOM_MAX-SidebandCore.AUTO_ANNOUNCE_RANDOM_MIN)) + 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: if not os.path.isfile(self.config_path): @@ -201,6 +296,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 @@ -217,25 +314,51 @@ 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 + + if RNS.vendor.platformutils.is_android(): + if self.config["config_template"] != None: + try: + if not os.path.isfile(os.path.join(self.rns_configdir, "config_template_invalid")): + if self.is_service: + with open(os.path.join(self.rns_configdir, "config_template_invalid"), "w") as invalidation_file: + invalidation_file.write("\n") + + ct = self.config["config_template"] + RNS.log(f"Loading modified RNS config template", RNS.LOG_WARNING) + self.config_template = ct + + else: + RNS.log("Custom configuration template invalid, using default configuration template", RNS.LOG_WARNING) + self.config_template = rns_config + if self.is_service: + self.setstate("hardware_operation.error", "At the previous start, Sideband could not initialise Reticulum. Custom configuration template loading has been temporarily disabled. Please check and fix any errors in your configuration template.") + + except Exception as e: + RNS.log(f"An error occurred while setting RNS configuration template: {e}", RNS.LOG_ERROR) + RNS.log(f"Using default configuration template", RNS.LOG_ERROR) + self.config_template = rns_config # 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) RNS.log("Configuring Reticulum instance...") if self.config["connect_transport"]: RNS.log("Enabling Reticulum Transport") - generated_config = rns_config.replace("TRANSPORT_IS_ENABLED", "Yes") + generated_config = self.config_template.replace("TRANSPORT_IS_ENABLED", "Yes") else: RNS.log("Not enabling Reticulum Transport") - generated_config = rns_config.replace("TRANSPORT_IS_ENABLED", "No") + 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() @@ -248,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 = {} @@ -261,16 +385,68 @@ class SidebandCore(): threading.Thread(target=load_job, daemon=True).start() + if RNS.vendor.platformutils.is_linux(): + try: + if not self.is_daemon: + lde_level = RNS.LOG_DEBUG + RNS.log("Checking desktop integration...", lde_level) + local_share_dir = os.path.expanduser("~/.local/share") + 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 = 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) + + update_de = False + if not os.path.exists(de_target): + update_de = True + else: + included_de_version = "" + with open(de_source, "rb") as sde_file: + included_de_version = sde_file.readline() + existing_de_version = None + with open(de_target, "rb") as de_file: + existing_de_version = de_file.readline() + + if included_de_version != existing_de_version: + update_de = True + RNS.log("Existing desktop entry doesn't match included, updating it", lde_level) + else: + update_de = False + RNS.log("Existing desktop entry matches included, not updating it", lde_level) + + if update_de: + RNS.log("Setting up desktop integration...", lde_level) + import shutil + RNS.log("Installing menu entry to \""+str(de_target)+"\"...", lde_level) + shutil.copy(de_source, de_target) + if not os.path.exists(icon_dir): + os.makedirs(icon_dir) + RNS.log("Installing icon to \""+str(icn_target)+"\"...", lde_level) + shutil.copy(icn_source, icn_target) + else: + RNS.log("Desktop integration is already set up", lde_level) + + except Exception as e: + RNS.log("An error occurred while setting up desktop integration: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + + 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) @@ -287,7 +463,7 @@ class SidebandCore(): self.config["debug"] = False self.config["display_name"] = "Anonymous Peer" self.config["notifications_on"] = True - self.config["dark_ui"] = False + self.config["dark_ui"] = True self.config["start_announce"] = True self.config["propagation_by_default"] = False self.config["home_node_as_broadcast_repeater"] = False @@ -298,11 +474,16 @@ class SidebandCore(): self.config["lxmf_periodic_sync"] = False self.config["lxmf_ignore_unknown"] = False self.config["lxmf_sync_interval"] = 43200 + self.config["lxmf_require_stamps"] = False + self.config["lxmf_inbound_stamp_cost"] = None self.config["last_lxmf_propagation_node"] = None self.config["nn_home_node"] = None self.config["print_command"] = "lp" - self.config["eink_mode"] = False + self.config["eink_mode"] = True 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 @@ -347,6 +528,7 @@ class SidebandCore(): self.config["hw_rnode_beacondata"] = None self.config["hw_rnode_bt_device"] = None self.config["hw_rnode_bluetooth"] = False + self.config["hw_rnode_ble"] = False self.config["hw_modem_baudrate"] = 57600 self.config["hw_modem_databits"] = 8 self.config["hw_modem_stopbits"] = 1 @@ -367,6 +549,14 @@ 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 + 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() @@ -376,7 +566,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): @@ -391,17 +581,40 @@ 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): + 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) - 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) @@ -410,237 +623,163 @@ 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"] = 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 - if not "lxmf_try_propagation_on_fail" in self.config: - self.config["lxmf_try_propagation_on_fail"] = True - 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"] = False - if not "display_style_in_contact_list" in self.config: - self.config["display_style_in_contact_list"] = False - if not "lxm_limit_1mb" in self.config: - self.config["lxm_limit_1mb"] = 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 "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 + 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"] = 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 - 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 "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 "connect_transport" in self.config: - self.config["connect_transport"] = 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 "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_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_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_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 - 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_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"] = False - if not "telemetry_display_trusted_only" in self.config: - self.config["telemetry_display_trusted_only"] = False - 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_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 # 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() @@ -648,6 +787,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: @@ -658,28 +799,35 @@ class SidebandCore(): if unpacked_config != None and len(unpacked_config) != 0: self.config = unpacked_config self.update_active_lxmf_propagation_node() + self.update_ignore_invalid_stamps() except Exception as e: 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: - time.sleep(0.15) + while self.saving_configuration: time.sleep(0.15) try: self.saving_configuration = True - config_file = open(self.config_path, "wb") - config_file.write(msgpack.packb(self.config)) - config_file.close() + 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 = 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") + 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) - 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) + 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"] @@ -699,7 +847,10 @@ 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(f"Error loading plugin \"{file}\": {e}", RNS.LOG_ERROR) + continue plugin_class = plugin_globals["plugin_class"] if plugin_class != None: @@ -759,25 +910,33 @@ class SidebandCore(): def save_configuration(self): self.__save_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: RNS.log("No active propagation node configured") else: try: - self.active_propagation_node = dest - self.config["last_lxmf_propagation_node"] = dest - self.message_router.set_outbound_propagation_node(dest) - - RNS.log("Active propagation node set to: "+RNS.prettyhexrep(dest)) - self.__save_config() + if self.message_router: + self.active_propagation_node = dest + self.config["last_lxmf_propagation_node"] = dest + self.message_router.set_outbound_propagation_node(dest) + + RNS.log("Active propagation node set to: "+RNS.prettyhexrep(dest)) + self.__save_config() except Exception as e: RNS.log("Error while setting LXMF propagation node: "+str(e), RNS.LOG_ERROR) def notify(self, title, content, group=None, context_id=None): if not self.is_daemon: + if RNS.vendor.platformutils.is_linux(): + from sbapp.ui.helpers import strip_emojis + title = strip_emojis(title) + content = strip_emojis(content) + + if self.config["notifications_on"]: - if RNS.vendor.platformutils.get_platform() == "android": + if RNS.vendor.platformutils.is_android(): if self.getpersistent("permissions.notifications"): notifications_permitted = True else: @@ -786,27 +945,29 @@ 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) + 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) - def log_announce(self, dest, app_data, dest_type): + def log_announce(self, dest, app_data, dest_type, stamp_cost=None, link_stats=None): try: - if app_data == None: - app_data = b"" - RNS.log("Received "+str(dest_type)+" announce for "+RNS.prettyhexrep(dest)+" with data: "+app_data.decode("utf-8"), RNS.LOG_DEBUG) - self._db_save_announce(dest, app_data, dest_type) + 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) except Exception as e: RNS.log("Exception while decoding LXMF destination announce data:"+str(e)) - def list_conversations(self): - result = self._db_conversations() + def list_conversations(self, conversations=True, objects=False): + result = self._db_conversations(conversations, objects) if result != None: return result else: @@ -845,10 +1006,66 @@ class SidebandCore(): RNS.log("Error while checking trust for "+RNS.prettyhexrep(context_dest)+": "+str(e), RNS.LOG_ERROR) return False - def should_send_telemetry(self, context_dest): + 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: + existing_conv = self._db_conversation(context_dest) + else: + existing_conv = conv_data + + if existing_conv != None: + data_dict = existing_conv["data"] + if data_dict != None: + if "is_object" in data_dict: + return data_dict["is_object"] + + return False + + except Exception as e: + RNS.log("Error while checking trust for "+RNS.prettyhexrep(context_dest)+": "+str(e), RNS.LOG_ERROR) + return False + + def ptt_enabled(self, context_dest, conv_data = None): + try: + if conv_data == None: + existing_conv = self._db_conversation(context_dest) + else: + existing_conv = conv_data + + if existing_conv != None: + data_dict = existing_conv["data"] + if data_dict != None: + if "ptt_enabled" in data_dict: + return data_dict["ptt_enabled"] + + return False + + except Exception as e: + RNS.log("Error while checking PTT-enabled for "+RNS.prettyhexrep(context_dest)+": "+str(e), RNS.LOG_ERROR) + return False + + def should_send_telemetry(self, context_dest, conv_data=None): try: if self.config["telemetry_enabled"]: - existing_conv = self._db_conversation(context_dest) + if conv_data == None: + existing_conv = self._db_conversation(context_dest) + else: + existing_conv = conv_data + if existing_conv != None: cd = existing_conv["data"] if cd != None and "telemetry" in cd and cd["telemetry"] == True: @@ -883,9 +1100,13 @@ class SidebandCore(): RNS.log("Error while checking request permissions for "+RNS.prettyhexrep(context_dest)+": "+str(e), RNS.LOG_ERROR) return False - def requests_allowed_from(self, context_dest): + def requests_allowed_from(self, context_dest, conv_data=None): try: - existing_conv = self._db_conversation(context_dest) + if conv_data == None: + existing_conv = self._db_conversation(context_dest) + else: + existing_conv = conv_data + if existing_conv != None: cd = existing_conv["data"] if cd != None and "allow_requests" in cd and cd["allow_requests"] == True: @@ -939,23 +1160,41 @@ class SidebandCore(): app_data = RNS.Identity.recall_app_data(context_dest) if app_data != None: if existing_conv["trust"] == 1: - return app_data.decode("utf-8") + return LXMF.display_name_from_app_data(app_data) else: - return app_data.decode("utf-8")+" "+RNS.prettyhexrep(context_dest) + return LXMF.display_name_from_app_data(app_data)+" "+RNS.prettyhexrep(context_dest) else: return RNS.prettyhexrep(context_dest) else: app_data = RNS.Identity.recall_app_data(context_dest) if app_data != None: - return app_data.decode("utf-8")+" "+RNS.prettyhexrep(context_dest) + name_str = LXMF.display_name_from_app_data(app_data) + addr_str = RNS.prettyhexrep(context_dest) + return name_str+" "+addr_str else: - return RNS.prettyhexrep(context_dest) + return "Anonymous Peer "+RNS.prettyhexrep(context_dest) 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 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) + 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) @@ -988,6 +1227,12 @@ class SidebandCore(): def untrusted_conversation(self, context_dest): self._db_conversation_set_trusted(context_dest, False) + def conversation_set_object(self, context_dest, is_object): + self._db_conversation_set_object(context_dest, is_object) + + def conversation_set_ptt_enabled(self, context_dest, ptt_enabled): + self._db_conversation_set_ptt_enabled(context_dest, ptt_enabled) + def send_telemetry_in_conversation(self, context_dest): self._db_conversation_set_telemetry(context_dest, True) @@ -1042,7 +1287,8 @@ class SidebandCore(): self.message_router.handle_outbound(message) else: if message.state == LXMF.LXMessage.DELIVERED: - self.setpersistent(f"telemetry.{RNS.hexrep(message.destination_hash, delimit=False)}.last_request_success_timebase", message.request_timebase) + delivery_timebase = int(time.time()) + self.setpersistent(f"telemetry.{RNS.hexrep(message.destination_hash, delimit=False)}.last_request_success_timebase", delivery_timebase) self.setstate(f"telemetry.{RNS.hexrep(message.destination_hash, delimit=False)}.request_sending", False) if message.destination_hash == self.config["telemetry_collector"]: self.pending_telemetry_request = False @@ -1051,130 +1297,246 @@ class SidebandCore(): else: self.setstate(f"telemetry.{RNS.hexrep(message.destination_hash, delimit=False)}.request_sending", False) - - def request_latest_telemetry(self, from_addr=None): - if from_addr == None or from_addr == self.lxmf_destination.hash: - return "no_address" + 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.getstate(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.request_sending") == True: - RNS.log("Not sending new telemetry request, since an earlier transfer is already in progress", RNS.LOG_DEBUG) - return "in_progress" - - if from_addr != None: - dest_identity = RNS.Identity.recall(from_addr) - - if dest_identity == None: - RNS.log("The identity for "+RNS.prettyhexrep(from_addr)+" could not be recalled. Requesting identity from network...", RNS.LOG_DEBUG) - RNS.Transport.request_path(from_addr) - return "destination_unknown" - - else: - now = time.time() - dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") - source = self.lxmf_destination + if self.is_client: + try: + return self.service_rpc_request({"request_latest_telemetry": {"from_addr": from_addr, "is_collector_request": is_collector_request}}) - if self.config["telemetry_use_propagation_only"] == True: - desired_method = LXMF.LXMessage.PROPAGATED - else: - desired_method = LXMF.LXMessage.DIRECT - - 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}, - ]} - - lxm = LXMF.LXMessage(dest, source, "", desired_method=desired_method, fields = lxm_fields) - lxm.request_timebase = request_timebase - lxm.register_delivery_callback(self.telemetry_request_finished) - lxm.register_failed_callback(self.telemetry_request_finished) - - if self.message_router.get_outbound_propagation_node() != None: - if self.config["telemetry_try_propagation_on_fail"]: - lxm.try_propagation_on_fail = True - - RNS.log(f"Sending telemetry request with timebase {request_timebase}", RNS.LOG_DEBUG) - self.setpersistent(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.last_request_attempt", time.time()) - self.setstate(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.request_sending", True) - self.message_router.handle_outbound(lxm) - return "sent" - + except Exception as e: + RNS.log("Error while requesting latest telemetry over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False else: + return 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, is_collector_request=is_collector_request) + + except Exception as e: + RNS.log("Error requesting latest telemetry: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) return "not_sent" + else: + if from_addr == None or from_addr == self.lxmf_destination.hash: + return "no_address" + else: + if self.getstate(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.request_sending") == True: + RNS.log("Not sending new telemetry request, since an earlier transfer is already in progress", RNS.LOG_DEBUG) + return "in_progress" - def send_latest_telemetry(self, to_addr=None, stream=None, is_authorized_telemetry_request=False): - if to_addr == None or to_addr == self.lxmf_destination.hash: - return "no_address" - else: - if to_addr == self.config["telemetry_collector"]: - is_authorized_telemetry_request = True + if from_addr != None: + dest_identity = RNS.Identity.recall(from_addr) + + if dest_identity == None: + RNS.log("The identity for "+RNS.prettyhexrep(from_addr)+" could not be recalled. Requesting identity from network...", RNS.LOG_DEBUG) + RNS.Transport.request_path(from_addr) + return "destination_unknown" - if self.getstate(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.update_sending") == True: - RNS.log("Not sending new telemetry update, since an earlier transfer is already in progress", RNS.LOG_DEBUG) - return "in_progress" + else: + now = time.time() + dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") + source = self.lxmf_destination + + if self.config["telemetry_use_propagation_only"] == True: + desired_method = LXMF.LXMessage.PROPAGATED + else: + if not self.message_router.delivery_link_available(from_addr) and RNS.Identity.current_ratchet_id(from_addr) != None: + RNS.log(f"Have ratchet for {RNS.prettyhexrep(from_addr)}, requesting opportunistic delivery of telemetry request", RNS.LOG_DEBUG) + desired_method = LXMF.LXMessage.OPPORTUNISTIC + else: + desired_method = LXMF.LXMessage.DIRECT - if (self.latest_packed_telemetry != None and self.latest_telemetry != None) or stream != None: - dest_identity = RNS.Identity.recall(to_addr) - - if dest_identity == None: - RNS.log("The identity for "+RNS.prettyhexrep(to_addr)+" could not be recalled. Requesting identity from network...", RNS.LOG_DEBUG) - RNS.Transport.request_path(to_addr) - return "destination_unknown" + 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, is_collector_request]}, + ]} + + lxm = LXMF.LXMessage(dest, source, "", desired_method=desired_method, fields = lxm_fields, include_ticket=True) + lxm.request_timebase = request_timebase + lxm.register_delivery_callback(self.telemetry_request_finished) + lxm.register_failed_callback(self.telemetry_request_finished) + + if self.message_router.get_outbound_propagation_node() != None: + if self.config["telemetry_try_propagation_on_fail"] and not is_livetrack: + lxm.try_propagation_on_fail = True + + RNS.log(f"Sending telemetry request with timebase {request_timebase}", RNS.LOG_DEBUG) + self.setpersistent(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.last_request_attempt", time.time()) + self.setstate(f"telemetry.{RNS.hexrep(from_addr, delimit=False)}.request_sending", True) + self.message_router.handle_outbound(lxm) + return "sent" else: - dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") - source = self.lxmf_destination - - if self.config["telemetry_use_propagation_only"] == True: - desired_method = LXMF.LXMessage.PROPAGATED - else: - desired_method = LXMF.LXMessage.DIRECT + return "not_sent" - lxm_fields = self.get_message_fields(to_addr, is_authorized_telemetry_request=is_authorized_telemetry_request, signal_already_sent=True) - if lxm_fields == False and stream == None: - return "already_sent" - - if stream != None and len(stream) > 0: - if lxm_fields == False: - lxm_fields = {} - lxm_fields[LXMF.FIELD_TELEMETRY_STREAM] = stream - - if lxm_fields != None and lxm_fields != False and (LXMF.FIELD_TELEMETRY in lxm_fields or LXMF.FIELD_TELEMETRY_STREAM in lxm_fields): - if LXMF.FIELD_TELEMETRY in lxm_fields: - telemeter = Telemeter.from_packed(lxm_fields[LXMF.FIELD_TELEMETRY]) - telemetry_timebase = telemeter.read_all()["time"]["utc"] - elif LXMF.FIELD_TELEMETRY_STREAM in lxm_fields: - telemetry_timebase = 0 - for te in lxm_fields[LXMF.FIELD_TELEMETRY_STREAM]: - ts = te[1] - telemetry_timebase = max(telemetry_timebase, ts) - - if telemetry_timebase > (self.getpersistent(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.last_send_success_timebase") or 0): - lxm = LXMF.LXMessage(dest, source, "", desired_method=desired_method, fields = lxm_fields) - lxm.telemetry_timebase = telemetry_timebase - lxm.register_delivery_callback(self.outbound_telemetry_finished) - lxm.register_failed_callback(self.outbound_telemetry_finished) - - if self.message_router.get_outbound_propagation_node() != None: - if self.config["telemetry_try_propagation_on_fail"]: - lxm.try_propagation_on_fail = True - - RNS.log(f"Sending telemetry update with timebase {telemetry_timebase}", RNS.LOG_DEBUG) - - self.setpersistent(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.last_send_attempt", time.time()) - self.setstate(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.update_sending", True) - self.message_router.handle_outbound(lxm) - return "sent" - - else: - RNS.log(f"Telemetry update with timebase {telemetry_timebase} was already successfully sent", RNS.LOG_DEBUG) - return "already_sent" - else: - return "nothing_to_send" + def _is_tracking(self, object_addr): + return object_addr in self.live_tracked_objects + def is_tracking(self, object_addr, allow_cache=False): + if not RNS.vendor.platformutils.is_android(): + return self._is_tracking(object_addr) + else: + if self.is_service: + return self._is_tracking(object_addr) else: - RNS.log("A telemetry update was requested, but there was nothing to send.", RNS.LOG_WARNING) - return "nothing_to_send" + try: + return self.service_rpc_request({"is_tracking": object_addr}) + except Exception as e: + ed = "Error while getting tracking state over RPC: "+str(e) + RNS.log(ed, RNS.LOG_DEBUG) + return ed + + def _start_tracking(self, object_addr, interval, duration): + RNS.log("Starting tracking of "+RNS.prettyhexrep(object_addr), RNS.LOG_DEBUG) + self.live_tracked_objects[object_addr] = [interval, 0, time.time()+duration] + + def start_tracking(self, object_addr, interval, duration, allow_cache=False): + if not RNS.vendor.platformutils.is_android(): + return self._start_tracking(object_addr, interval, duration) + else: + if self.is_service: + return self._start_tracking(object_addr, interval, duration) + else: + try: + args = {"object_addr": object_addr, "interval": interval, "duration": duration} + return self.service_rpc_request({"start_tracking": args}) + except Exception as e: + ed = "Error while starting tracking over RPC: "+str(e) + RNS.log(ed, RNS.LOG_DEBUG) + return ed + + def _stop_tracking(self, object_addr): + RNS.log("Stopping tracking of "+RNS.prettyhexrep(object_addr), RNS.LOG_DEBUG) + if object_addr in self.live_tracked_objects: + self.live_tracked_objects.pop(object_addr) + + def stop_tracking(self, object_addr, allow_cache=False): + if not RNS.vendor.platformutils.is_android(): + return self._stop_tracking(object_addr) + else: + if self.is_service: + return self._stop_tracking(object_addr) + else: + try: + args = {"object_addr": object_addr} + return self.service_rpc_request({"stop_tracking": args}) + except Exception as e: + ed = "Error while stopping tracking over RPC: "+str(e) + RNS.log(ed, RNS.LOG_DEBUG) + return ed + + def _service_send_latest_telemetry(self, to_addr=None, stream=None, is_authorized_telemetry_request=False): + if not RNS.vendor.platformutils.is_android(): + return False + else: + if self.is_client: + try: + return self.service_rpc_request({"send_latest_telemetry": { + "to_addr": to_addr, + "stream": stream, + "is_authorized_telemetry_request": is_authorized_telemetry_request} + }) + + except Exception as e: + RNS.log("Error while sending latest telemetry over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + else: + return 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) + + except Exception as e: + RNS.log("Error requesting latest telemetry: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return "not_sent" + + else: + if to_addr == None or to_addr == self.lxmf_destination.hash: + return "no_address" + else: + if to_addr == self.config["telemetry_collector"]: + is_authorized_telemetry_request = True + + if self.getstate(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.update_sending") == True: + RNS.log("Not sending new telemetry update, since an earlier transfer is already in progress", RNS.LOG_DEBUG) + return "in_progress" + + if (self.latest_packed_telemetry != None and self.latest_telemetry != None) or stream != None: + dest_identity = RNS.Identity.recall(to_addr) + + if dest_identity == None: + RNS.log("The identity for "+RNS.prettyhexrep(to_addr)+" could not be recalled. Requesting identity from network...", RNS.LOG_DEBUG) + RNS.Transport.request_path(to_addr) + return "destination_unknown" + + else: + dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") + source = self.lxmf_destination + + if self.config["telemetry_use_propagation_only"] == True: + desired_method = LXMF.LXMessage.PROPAGATED + else: + if not self.message_router.delivery_link_available(to_addr) and RNS.Identity.current_ratchet_id(to_addr) != None: + RNS.log(f"Have ratchet for {RNS.prettyhexrep(to_addr)}, requesting opportunistic delivery of telemetry", RNS.LOG_DEBUG) + desired_method = LXMF.LXMessage.OPPORTUNISTIC + 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, is_collector_response=is_collector_response) + if lxm_fields == False and stream == None: + return "already_sent" + + if stream != None and len(stream) > 0: + if lxm_fields == False: + lxm_fields = {} + lxm_fields[LXMF.FIELD_TELEMETRY_STREAM] = stream + + if lxm_fields != None and lxm_fields != False and (LXMF.FIELD_TELEMETRY in lxm_fields or LXMF.FIELD_TELEMETRY_STREAM in lxm_fields): + if LXMF.FIELD_TELEMETRY in lxm_fields: + telemeter = Telemeter.from_packed(lxm_fields[LXMF.FIELD_TELEMETRY]) + telemetry_timebase = telemeter.read_all()["time"]["utc"] + elif LXMF.FIELD_TELEMETRY_STREAM in lxm_fields: + telemetry_timebase = 0 + for te in lxm_fields[LXMF.FIELD_TELEMETRY_STREAM]: + ts = te[1] + telemetry_timebase = max(telemetry_timebase, ts) + + if telemetry_timebase > (self.getpersistent(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.last_send_success_timebase") or 0): + lxm = LXMF.LXMessage(dest, source, "", desired_method=desired_method, fields = lxm_fields, include_ticket=self.is_trusted(to_addr)) + lxm.telemetry_timebase = telemetry_timebase + lxm.register_delivery_callback(self.outbound_telemetry_finished) + lxm.register_failed_callback(self.outbound_telemetry_finished) + + if self.message_router.get_outbound_propagation_node() != None: + if self.config["telemetry_try_propagation_on_fail"]: + lxm.try_propagation_on_fail = True + + RNS.log(f"Sending telemetry update with timebase {telemetry_timebase}", RNS.LOG_DEBUG) + + self.setpersistent(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.last_send_attempt", time.time()) + self.setstate(f"telemetry.{RNS.hexrep(to_addr, delimit=False)}.update_sending", True) + self.message_router.handle_outbound(lxm) + return "sent" + + else: + RNS.log(f"Telemetry update with timebase {telemetry_timebase} was already successfully sent", RNS.LOG_DEBUG) + return "already_sent" + else: + return "nothing_to_send" + + else: + RNS.log("A telemetry update was requested, but there was nothing to send.", RNS.LOG_WARNING) + return "nothing_to_send" def list_telemetry(self, context_dest = None, after = None, before = None, limit = None): @@ -1246,6 +1608,7 @@ class SidebandCore(): return [] def service_available(self): + heartbeat_stale_time = 7.5 now = time.time() service_heartbeat = self.getstate("service.heartbeat") if not service_heartbeat: @@ -1253,9 +1616,16 @@ class SidebandCore(): return False else: try: - if now - service_heartbeat > 4.0: - RNS.log("Stale service heartbeat at "+str(now), RNS.LOG_DEBUG) - return False + if now - service_heartbeat > heartbeat_stale_time: + RNS.log("Stale service heartbeat at "+str(now)+", retrying...", RNS.LOG_DEBUG) + now = time.time() + service_heartbeat = self.getstate("service.heartbeat") + if now - service_heartbeat > heartbeat_stale_time: + RNS.log("Service heartbeat did not recover after retry", RNS.LOG_DEBUG) + return False + else: + RNS.log("Service heartbeat recovered at"+str(now), RNS.LOG_DEBUG) + return True else: return True except Exception as e: @@ -1272,6 +1642,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: @@ -1284,11 +1657,7 @@ class SidebandCore(): return True else: def set(): - if self.rpc_connection == None: - self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, authkey=self.rpc_key) - self.rpc_connection.send({"setstate": (prop, val)}) - response = self.rpc_connection.recv() - return response + return self.service_rpc_request({"setstate": (prop, val)}) try: set() @@ -1310,11 +1679,7 @@ class SidebandCore(): return True else: try: - if self.rpc_connection == None: - self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, authkey=self.rpc_key) - self.rpc_connection.send({"latest_telemetry": (latest_telemetry, latest_packed_telemetry)}) - response = self.rpc_connection.recv() - return response + return self.service_rpc_request({"latest_telemetry": (latest_telemetry, latest_packed_telemetry)}) except Exception as e: RNS.log("Error while setting telemetry over RPC: "+str(e), RNS.LOG_DEBUG) return False @@ -1331,20 +1696,44 @@ class SidebandCore(): return True else: try: - if self.rpc_connection == None: - self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, authkey=self.rpc_key) - self.rpc_connection.send({"set_debug": debug}) - response = self.rpc_connection.recv() - return response + return self.service_rpc_request({"set_debug": debug}) except Exception as e: RNS.log("Error while setting log level over RPC: "+str(e), RNS.LOG_DEBUG) return False + def service_rpc_set_ui_recording(self, recording): + if not RNS.vendor.platformutils.is_android(): + pass + else: + if self.is_service: + self.ui_recording = recording + return True + else: + try: + return self.service_rpc_request({"set_ui_recording": recording}) + except Exception as e: + RNS.log("Error while setting UI recording status over RPC: "+str(e), RNS.LOG_DEBUG) + return False + + def service_rpc_request(self, request): + # RNS.log("Running service RPC call: "+str(request), RNS.LOG_DEBUG) + try: + with self.rpc_lock: + if self.rpc_connection == None: + 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 + + 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) + def getstate(self, prop, allow_cache=False): with self.state_lock: if not self.service_stopped: - # TODO: remove - # us = time.time() if not RNS.vendor.platformutils.is_android(): if prop in self.state_db: @@ -1359,13 +1748,7 @@ class SidebandCore(): return None else: try: - if self.rpc_connection == None: - self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, authkey=self.rpc_key) - self.rpc_connection.send({"getstate": prop}) - response = self.rpc_connection.recv() - # TODO: Remove - # RNS.log("RPC getstate result for "+str(prop)+"="+str(response)+" in "+RNS.prettytime(time.time()-us), RNS.LOG_WARNING) - return response + return self.service_rpc_request({"getstate": prop}) except Exception as e: RNS.log("Error while retrieving state "+str(prop)+" over RPC: "+str(e), RNS.LOG_DEBUG) @@ -1400,26 +1783,154 @@ class SidebandCore(): return self._get_plugins_info() else: try: - if self.rpc_connection == None: - self.rpc_connection = multiprocessing.connection.Client(self.rpc_addr, authkey=self.rpc_key) - self.rpc_connection.send({"get_plugins_info": True}) - response = self.rpc_connection.recv() - return response + return self.service_rpc_request({"get_plugins_info": True}) except Exception as e: ed = "Error while getting plugins info over RPC: "+str(e) RNS.log(ed, RNS.LOG_DEBUG) return ed - + def _get_destination_establishment_rate(self, destination_hash): + try: + mr = self.message_router + oh = destination_hash + ol = None + 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 and ol.status == RNS.Link.ACTIVE: + ler = ol.get_establishment_rate() + if ler: + return ler + + return None + + except Exception as e: + RNS.trace_exception(e) + return None + + def get_destination_establishment_rate(self, destination_hash): + if not RNS.vendor.platformutils.is_android(): + return self._get_destination_establishment_rate(destination_hash) + else: + if self.is_service: + return self._get_destination_establishment_rate(destination_hash) + else: + try: + return self.service_rpc_request({"get_destination_establishment_rate": destination_hash}) + except Exception as e: + ed = "Error while getting destination link etablishment rate over RPC: "+str(e) + 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 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 and ol.status == RNS.Link.ACTIVE: + 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 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 and ol.status == RNS.Link.ACTIVE: + 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 _get_destination_lmd(self, destination_hash): + try: + mr = self.message_router + oh = destination_hash + ol = None + 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 and ol.status == RNS.Link.ACTIVE: 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) - 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): @@ -1448,17 +1959,84 @@ class SidebandCore(): elif "set_debug" in call: self.service_rpc_set_debug(call["set_debug"]) connection.send(True) - elif "get_plugins_info" in call: - connection.send(self._get_plugins_info()) + elif "set_ui_recording" in call: + self.service_rpc_set_ui_recording(call["set_ui_recording"]) + connection.send(True) + elif "send_message" in call: + args = call["send_message"] + send_result = self.send_message( + args["content"], + args["destination_hash"], + args["propagation"], + skip_fields=args["skip_fields"], + no_display=args["no_display"], + attachment=args["attachment"], + image=args["image"], + audio=args["audio"]) + connection.send(send_result) + elif "cancel_message" in call: + args = call["cancel_message"] + cancel_result = self.cancel_message(args["message_id"]) + connection.send(cancel_result) + elif "send_command" in call: + args = call["send_command"] + send_result = self.send_command( + args["content"], + args["destination_hash"], + args["propagation"]) + connection.send(send_result) + elif "request_latest_telemetry" in call: + args = call["request_latest_telemetry"] + 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"] + send_result = self.send_latest_telemetry( + to_addr=args["to_addr"], + stream=args["stream"], + is_authorized_telemetry_request=args["is_authorized_telemetry_request"] + ) + 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_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"], 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) + 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) + elif "telephone_switch_profile" in call: connection.send(self.telephone.switch_profile(call["telephone_switch_profile"]) if self.telephone else False) else: - return None + connection.send(None) except Exception as e: RNS.log("Error on client RPC connection: "+str(e), RNS.LOG_ERROR) - try: - connection.close() - except: - pass + RNS.trace_exception(e) + try: connection.close() + except: pass return rpc_client_job @@ -1485,10 +2063,20 @@ class SidebandCore(): def __db_connect(self): if self.db == None: - self.db = sqlite3.connect(self.db_path, check_same_thread=False) + self.db = sqlite3.connect(self.db_path, check_same_thread=False, timeout=15.0) return self.db + def __db_reconnect(self): + if self.db != None: + try: + self.db.close() + except Exception as e: + RNS.log("Error while closing database for reconnect. The contained exception was:", RNS.LOG_ERROR) + RNS.trace_exception(e) + self.db = None + return self.__db_connect() + def __db_init(self): db = self.__db_connect() dbc = db.cursor() @@ -1526,16 +2114,17 @@ 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): # TODO: Remove this again at some point in the future db = self.__db_connect() dbc = db.cursor() - dbc.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'lxm' AND sql LIKE '%extra%'") + dbc.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'announce' AND sql LIKE '%extra%'") result = dbc.fetchall() if len(result) == 0: - dbc.execute("ALTER TABLE lxm ADD COLUMN extra BLOB") + dbc.execute("ALTER TABLE announce ADD COLUMN extra BLOB") db.commit() def _db_initstate(self): @@ -1547,67 +2136,6 @@ class SidebandCore(): # db.commit() self.setstate("database_ready", True) - # def _db_getstate(self, prop): - # try: - # db = self.__db_connect() - # dbc = db.cursor() - - # query = "select * from state where property=:uprop" - # dbc.execute(query, {"uprop": prop.encode("utf-8")}) - - # result = dbc.fetchall() - - # if len(result) < 1: - # return None - # else: - # try: - # entry = result[0] - # val = msgpack.unpackb(entry[1]) - - # return val - # except Exception as e: - # RNS.log("Could not unpack state value from database for property \""+str(prop)+"\". The contained exception was: "+str(e), RNS.LOG_ERROR) - # return None - - # except Exception as e: - # RNS.log("An error occurred during getstate database operation: "+str(e), RNS.LOG_ERROR) - # self.db = None - - # def _db_setstate(self, prop, val): - # try: - # uprop = prop.encode("utf-8") - # bval = msgpack.packb(val) - - # if self._db_getstate(prop) == None: - # try: - # db = self.__db_connect() - # dbc = db.cursor() - # query = "INSERT INTO state (property, value) values (?, ?)" - # data = (uprop, bval) - # dbc.execute(query, data) - # db.commit() - - # except Exception as e: - # RNS.log("Error while setting state property "+str(prop)+" in DB: "+str(e), RNS.LOG_ERROR) - # RNS.log("Retrying as update query...", RNS.LOG_ERROR) - # db = self.__db_connect() - # dbc = db.cursor() - # query = "UPDATE state set value=:bval where property=:uprop;" - # dbc.execute(query, {"bval": bval, "uprop": uprop}) - # db.commit() - - # else: - # db = self.__db_connect() - # dbc = db.cursor() - # query = "UPDATE state set value=:bval where property=:uprop;" - # dbc.execute(query, {"bval": bval, "uprop": uprop}) - # db.commit() - - - # except Exception as e: - # RNS.log("An error occurred during setstate database operation: "+str(e), RNS.LOG_ERROR) - # self.db = None - def _db_initpersistent(self): db = self.__db_connect() dbc = db.cursor() @@ -1616,223 +2144,260 @@ class SidebandCore(): db.commit() def _db_getpersistent(self, prop): - try: + with self.db_lock: + try: + db = self.__db_connect() + dbc = db.cursor() + + query = "select * from persistent where property=:uprop" + dbc.execute(query, {"uprop": prop.encode("utf-8")}) + result = dbc.fetchall() + + if len(result) < 1: + return None + else: + try: + entry = result[0] + val = msgpack.unpackb(entry[1]) + if val == None: + query = "delete from persistent where (property=:uprop);" + dbc.execute(query, {"uprop": prop.encode("utf-8")}) + db.commit() + + return val + except Exception as e: + RNS.log("Could not unpack persistent value from database for property \""+str(prop)+"\". The contained exception was: "+str(e), RNS.LOG_ERROR) + return None + + except Exception as e: + RNS.log("An error occurred during persistent getstate database operation: "+str(e), RNS.LOG_ERROR) + self.db = None + + def _db_setpersistent(self, prop, val): + existing_prop = self._db_getpersistent(prop) + + with self.db_lock: + try: + db = self.__db_connect() + dbc = db.cursor() + uprop = prop.encode("utf-8") + bval = msgpack.packb(val) + + if existing_prop == None: + try: + query = "INSERT INTO persistent (property, value) values (?, ?)" + data = (uprop, bval) + dbc.execute(query, data) + db.commit() + + except Exception as e: + RNS.log("Error while setting persistent state property "+str(prop)+" in DB: "+str(e), RNS.LOG_ERROR) + RNS.log("Retrying as update query...") + query = "UPDATE state set value=:bval where property=:uprop;" + dbc.execute(query, {"bval": bval, "uprop": uprop}) + db.commit() + + else: + query = "UPDATE persistent set value=:bval where property=:uprop;" + dbc.execute(query, {"bval": bval, "uprop": uprop}) + db.commit() + + except Exception as e: + RNS.log("An error occurred during persistent setstate database operation: "+str(e), RNS.LOG_ERROR) + self.db = None + + def _db_conversation_update_txtime(self, context_dest, is_retry = False): + with self.db_lock: + try: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set last_tx = ? where dest_context = ?" + data = (time.time(), context_dest) + + dbc.execute(query, data) + result = dbc.fetchall() + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation TX time: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_update_txtime(context_dest, is_retry=True) + + def _db_conversation_set_unread(self, context_dest, unread, tx = False, is_retry = False): + with self.db_lock: + try: + db = self.__db_connect() + dbc = db.cursor() + + if unread: + if tx: + query = "UPDATE conv set unread = ?, last_tx = ? where dest_context = ?" + data = (unread, time.time(), context_dest) + else: + query = "UPDATE conv set unread = ?, last_rx = ? where dest_context = ?" + data = (unread, time.time(), context_dest) + else: + query = "UPDATE conv set unread = ? where dest_context = ?" + data = (unread, context_dest) + + dbc.execute(query, data) + result = dbc.fetchall() + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation unread flag: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_set_unread(context_dest, unread, tx, is_retry=True) + + def _db_telemetry(self, context_dest = None, after = None, before = None, limit = None): + with self.db_lock: db = self.__db_connect() dbc = db.cursor() - - query = "select * from persistent where property=:uprop" - dbc.execute(query, {"uprop": prop.encode("utf-8")}) + + limit_part = "" + if limit: + limit_part = " LIMIT "+str(int(limit)) + order_part = " order by ts DESC"+limit_part + if context_dest == None: + if after != None and before == None: + query = "select * from telemetry where ts>:after_ts"+order_part + dbc.execute(query, {"after_ts": after}) + elif after == None and before != None: + query = "select * from telemetry where ts<:before_ts"+order_part + dbc.execute(query, {"before_ts": before}) + elif after != None and before != None: + query = "select * from telemetry where ts<:before_ts and ts>:after_ts"+order_part + dbc.execute(query, {"before_ts": before, "after_ts": after}) + else: + query = query = "select * from telemetry" + dbc.execute(query, {}) + + else: + if after != None and before == None: + query = "select * from telemetry where dest_context=:context_dest and ts>:after_ts"+order_part + dbc.execute(query, {"context_dest": context_dest, "after_ts": after}) + elif after == None and before != None: + query = "select * from telemetry where dest_context=:context_dest and ts<:before_ts"+order_part + dbc.execute(query, {"context_dest": context_dest, "before_ts": before}) + elif after != None and before != None: + query = "select * from telemetry where dest_context=:context_dest and ts<:before_ts and ts>:after_ts"+order_part + dbc.execute(query, {"context_dest": context_dest, "before_ts": before, "after_ts": after}) + else: + query = query = "select * from telemetry where dest_context=:context_dest"+order_part + dbc.execute(query, {"context_dest": context_dest}) + result = dbc.fetchall() if len(result) < 1: return None else: - try: - entry = result[0] - val = msgpack.unpackb(entry[1]) - if val == None: - query = "delete from persistent where (property=:uprop);" - dbc.execute(query, {"uprop": prop.encode("utf-8")}) - db.commit() + results = {} + for entry in result: + telemetry_source = entry[1] + telemetry_timestamp = entry[2] + telemetry_data = entry[3] + + if not telemetry_source in results: + results[telemetry_source] = [] - return val - except Exception as e: - RNS.log("Could not unpack persistent value from database for property \""+str(prop)+"\". The contained exception was: "+str(e), RNS.LOG_ERROR) + results[telemetry_source].append([telemetry_timestamp, telemetry_data]) + + return results + + def _db_save_telemetry(self, context_dest, telemetry, physical_link = None, source_dest = None, via = None, is_retry = False): + with self.db_lock: + try: + remote_telemeter = Telemeter.from_packed(telemetry) + read_telemetry = remote_telemeter.read_all() + telemetry_timestamp = read_telemetry["time"]["utc"] + + db = self.__db_connect() + dbc = db.cursor() + + query = "select * from telemetry where dest_context=:ctx and ts=:tts" + dbc.execute(query, {"ctx": context_dest, "tts": telemetry_timestamp}) + result = dbc.fetchall() + + if len(result) != 0: + RNS.log("Telemetry entry with source "+RNS.prettyhexrep(context_dest)+" and timestamp "+str(telemetry_timestamp)+" already exists, skipping save", RNS.LOG_DEBUG) return None - - except Exception as e: - RNS.log("An error occurred during persistent getstate database operation: "+str(e), RNS.LOG_ERROR) - self.db = None - def _db_setpersistent(self, prop, val): - try: - db = self.__db_connect() - dbc = db.cursor() - uprop = prop.encode("utf-8") - bval = msgpack.packb(val) + if physical_link != None and len(physical_link) != 0: + remote_telemeter.synthesize("physical_link") + if "rssi" in physical_link: remote_telemeter.sensors["physical_link"].rssi = physical_link["rssi"] + if "snr" in physical_link: remote_telemeter.sensors["physical_link"].snr = physical_link["snr"] + if "q" in physical_link: remote_telemeter.sensors["physical_link"].q = physical_link["q"] + remote_telemeter.sensors["physical_link"].update_data() + telemetry = remote_telemeter.packed() - if self._db_getpersistent(prop) == None: - try: - query = "INSERT INTO persistent (property, value) values (?, ?)" - data = (uprop, bval) - dbc.execute(query, data) - db.commit() - - except Exception as e: - RNS.log("Error while setting persistent state property "+str(prop)+" in DB: "+str(e), RNS.LOG_ERROR) - RNS.log("Retrying as update query...") - query = "UPDATE state set value=:bval where property=:uprop;" - dbc.execute(query, {"bval": bval, "uprop": uprop}) - db.commit() - - else: - query = "UPDATE persistent set value=:bval where property=:uprop;" - dbc.execute(query, {"bval": bval, "uprop": uprop}) - db.commit() - - except Exception as e: - RNS.log("An error occurred during persistent setstate database operation: "+str(e), RNS.LOG_ERROR) - self.db = None - - def _db_conversation_update_txtime(self, context_dest): - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE conv set last_tx = ? where dest_context = ?" - data = (time.time(), context_dest) - - dbc.execute(query, data) - result = dbc.fetchall() - db.commit() - - def _db_conversation_set_unread(self, context_dest, unread, tx = False): - db = self.__db_connect() - dbc = db.cursor() - - if unread: - if tx: - query = "UPDATE conv set unread = ?, last_tx = ? where dest_context = ?" - data = (unread, time.time(), context_dest) - else: - query = "UPDATE conv set unread = ?, last_rx = ? where dest_context = ?" - data = (unread, time.time(), context_dest) - else: - query = "UPDATE conv set unread = ? where dest_context = ?" - data = (unread, context_dest) - - dbc.execute(query, data) - result = dbc.fetchall() - db.commit() - - def _db_telemetry(self, context_dest = None, after = None, before = None, limit = None): - db = self.__db_connect() - dbc = db.cursor() - - limit_part = "" - if limit: - limit_part = " LIMIT "+str(int(limit)) - order_part = " order by ts DESC"+limit_part - if context_dest == None: - if after != None and before == None: - query = "select * from telemetry where ts>:after_ts"+order_part - dbc.execute(query, {"after_ts": after}) - elif after == None and before != None: - query = "select * from telemetry where ts<:before_ts"+order_part - dbc.execute(query, {"before_ts": before}) - elif after != None and before != None: - query = "select * from telemetry where ts<:before_ts and ts>:after_ts"+order_part - dbc.execute(query, {"before_ts": before, "after_ts": after}) - else: - query = query = "select * from telemetry" - dbc.execute(query, {}) - - else: - if after != None and before == None: - query = "select * from telemetry where dest_context=:context_dest and ts>:after_ts"+order_part - dbc.execute(query, {"context_dest": context_dest, "after_ts": after}) - elif after == None and before != None: - query = "select * from telemetry where dest_context=:context_dest and ts<:before_ts"+order_part - dbc.execute(query, {"context_dest": context_dest, "before_ts": before}) - elif after != None and before != None: - query = "select * from telemetry where dest_context=:context_dest and ts<:before_ts and ts>:after_ts"+order_part - dbc.execute(query, {"context_dest": context_dest, "before_ts": before, "after_ts": after}) - else: - query = query = "select * from telemetry where dest_context=:context_dest"+order_part - dbc.execute(query, {"context_dest": context_dest}) - - result = dbc.fetchall() - - if len(result) < 1: - return None - else: - results = {} - for entry in result: - telemetry_source = entry[1] - telemetry_timestamp = entry[2] - telemetry_data = entry[3] - - if not telemetry_source in results: - results[telemetry_source] = [] - - results[telemetry_source].append([telemetry_timestamp, telemetry_data]) - - return results - - def _db_save_telemetry(self, context_dest, telemetry, physical_link = None, source_dest = None, via = None): - try: - remote_telemeter = Telemeter.from_packed(telemetry) - read_telemetry = remote_telemeter.read_all() - telemetry_timestamp = read_telemetry["time"]["utc"] - - db = self.__db_connect() - dbc = db.cursor() - - query = "select * from telemetry where dest_context=:ctx and ts=:tts" - dbc.execute(query, {"ctx": context_dest, "tts": telemetry_timestamp}) - result = dbc.fetchall() - - if len(result) != 0: - RNS.log("Telemetry entry with source "+RNS.prettyhexrep(context_dest)+" and timestamp "+str(telemetry_timestamp)+" already exists, skipping save", RNS.LOG_DEBUG) - return None - - if physical_link != None and len(physical_link) != 0: - remote_telemeter.synthesize("physical_link") - if "rssi" in physical_link: remote_telemeter.sensors["physical_link"].rssi = physical_link["rssi"] - if "snr" in physical_link: remote_telemeter.sensors["physical_link"].snr = physical_link["snr"] - if "q" in physical_link: remote_telemeter.sensors["physical_link"].q = physical_link["q"] - remote_telemeter.sensors["physical_link"].update_data() - telemetry = remote_telemeter.packed() - - if source_dest != None: - remote_telemeter.synthesize("received") - remote_telemeter.sensors["received"].by = self.lxmf_destination.hash - remote_telemeter.sensors["received"].via = source_dest - - rl = remote_telemeter.read("location") - if rl and "latitude" in rl and "longitude" in rl and "altitude" in rl: - if self.latest_telemetry != None and "location" in self.latest_telemetry: - ol = self.latest_telemetry["location"] - if ol != None: - if "latitude" in ol and "longitude" in ol and "altitude" in ol: - olat = ol["latitude"]; olon = ol["longitude"]; oalt = ol["altitude"] - rlat = rl["latitude"]; rlon = rl["longitude"]; ralt = rl["altitude"] - if olat != None and olon != None and oalt != None: - if rlat != None and rlon != None and ralt != None: - remote_telemeter.sensors["received"].set_distance( - (olat, olon, oalt), (rlat, rlon, ralt) - ) - - remote_telemeter.sensors["received"].update_data() - telemetry = remote_telemeter.packed() - - if via != None: - if not "received" in remote_telemeter.sensors: + if source_dest != None: remote_telemeter.synthesize("received") + remote_telemeter.sensors["received"].by = self.lxmf_destination.hash + remote_telemeter.sensors["received"].via = source_dest - if "by" in remote_telemeter.sensors["received"].data: - remote_telemeter.sensors["received"].by = remote_telemeter.sensors["received"].data["by"] - if "distance" in remote_telemeter.sensors["received"].data: - remote_telemeter.sensors["received"].geodesic_distance = remote_telemeter.sensors["received"].data["distance"]["geodesic"] - remote_telemeter.sensors["received"].euclidian_distance = remote_telemeter.sensors["received"].data["distance"]["euclidian"] + rl = remote_telemeter.read("location") + if rl and "latitude" in rl and "longitude" in rl and "altitude" in rl: + if self.latest_telemetry != None and "location" in self.latest_telemetry: + ol = self.latest_telemetry["location"] + if ol != None: + if "latitude" in ol and "longitude" in ol and "altitude" in ol: + olat = ol["latitude"]; olon = ol["longitude"]; oalt = ol["altitude"] + rlat = rl["latitude"]; rlon = rl["longitude"]; ralt = rl["altitude"] + if olat != None and olon != None and oalt != None: + if rlat != None and rlon != None and ralt != None: + remote_telemeter.sensors["received"].set_distance( + (olat, olon, oalt), (rlat, rlon, ralt) + ) - remote_telemeter.sensors["received"].via = via - remote_telemeter.sensors["received"].update_data() - telemetry = remote_telemeter.packed() - - query = "INSERT INTO telemetry (dest_context, ts, data) values (?, ?, ?)" - data = (context_dest, telemetry_timestamp, telemetry) - dbc.execute(query, data) - db.commit() - self.setstate("app.flags.last_telemetry", time.time()) + remote_telemeter.sensors["received"].update_data() + telemetry = remote_telemeter.packed() - return telemetry + if via != None: + if not "received" in remote_telemeter.sensors: + remote_telemeter.synthesize("received") - except Exception as e: - import traceback - exception_info = "".join(traceback.TracebackException.from_exception(e).format()) - RNS.log(f"A {str(type(e))} occurred while saving telemetry to database: {str(e)}", RNS.LOG_ERROR) - RNS.log(exception_info, RNS.LOG_ERROR) - self.db = None + if "by" in remote_telemeter.sensors["received"].data: + remote_telemeter.sensors["received"].by = remote_telemeter.sensors["received"].data["by"] + if "distance" in remote_telemeter.sensors["received"].data: + remote_telemeter.sensors["received"].geodesic_distance = remote_telemeter.sensors["received"].data["distance"]["geodesic"] + remote_telemeter.sensors["received"].euclidian_distance = remote_telemeter.sensors["received"].data["distance"]["euclidian"] + + remote_telemeter.sensors["received"].via = via + remote_telemeter.sensors["received"].update_data() + telemetry = remote_telemeter.packed() + + query = "INSERT INTO telemetry (dest_context, ts, data) values (?, ?, ?)" + data = (context_dest, telemetry_timestamp, telemetry) + dbc.execute(query, data) + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while commiting telemetry to database: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_save_telemetry(context_dest, telemetry, physical_link, source_dest, via, is_retry = True) + return + + self.setstate("app.flags.last_telemetry", time.time()) + + if self.config["telemetry_to_mqtt"] == True: + def mqtt_job(): + self.mqtt_handle_telemetry(context_dest, telemetry) + threading.Thread(target=mqtt_job, daemon=True).start() + + return telemetry + + except Exception as e: + import traceback + exception_info = "".join(traceback.TracebackException.from_exception(e).format()) + RNS.log(f"A {str(type(e))} occurred while saving telemetry to database: {str(e)}", RNS.LOG_ERROR) + RNS.log(exception_info, RNS.LOG_ERROR) + self.db = None def _db_update_appearance(self, context_dest, timestamp, appearance, from_bulk_telemetry=False): conv = self._db_conversation(context_dest) @@ -1844,29 +2409,30 @@ class SidebandCore(): self.setpersistent("temp.peer_appearance."+RNS.hexrep(context_dest, delimit=False), ae) else: - data_dict = conv["data"] - if data_dict == None: - data_dict = {} + with self.db_lock: + data_dict = conv["data"] + if data_dict == None: + data_dict = {} - if not "appearance" in data_dict: - data_dict["appearance"] = None + if not "appearance" in data_dict: + data_dict["appearance"] = None - if from_bulk_telemetry and data_dict["appearance"] != SidebandCore.DEFAULT_APPEARANCE: - RNS.log("Aborting appearance update from bulk transfer, since conversation already has appearance set: "+str(appearance)+" / "+str(data_dict["appearance"]), RNS.LOG_DEBUG) - return + 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 - if data_dict["appearance"] != appearance: - data_dict["appearance"] = appearance - packed_dict = msgpack.packb(data_dict) - - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE conv set data = ? where dest_context = ?" - data = (packed_dict, context_dest) - dbc.execute(query, data) - result = dbc.fetchall() - db.commit() + if data_dict["appearance"] != appearance: + data_dict["appearance"] = appearance + packed_dict = msgpack.packb(data_dict) + + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set data = ? where dest_context = ?" + data = (packed_dict, context_dest) + dbc.execute(query, data) + result = dbc.fetchall() + db.commit() def _db_get_appearance(self, context_dest, conv = None, raw=False): if context_dest == self.lxmf_destination.hash: @@ -1914,7 +2480,7 @@ class SidebandCore(): return None - def _db_conversation_set_telemetry(self, context_dest, send_telemetry=False): + def _db_conversation_set_telemetry(self, context_dest, send_telemetry=False, is_retry = False): conv = self._db_conversation(context_dest) data_dict = conv["data"] if data_dict == None: @@ -1923,16 +2489,25 @@ class SidebandCore(): data_dict["telemetry"] = send_telemetry packed_dict = msgpack.packb(data_dict) - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE conv set data = ? where dest_context = ?" - data = (packed_dict, context_dest) - dbc.execute(query, data) - result = dbc.fetchall() - db.commit() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set data = ? where dest_context = ?" + data = (packed_dict, context_dest) + dbc.execute(query, data) + result = dbc.fetchall() - def _db_conversation_set_requests(self, context_dest, allow_requests=False): + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation telemetry options: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_set_telemetry(context_dest, send_telemetry, is_retry=True) + + def _db_conversation_set_requests(self, context_dest, allow_requests=False, is_retry=False): conv = self._db_conversation(context_dest) data_dict = conv["data"] if data_dict == None: @@ -1941,171 +2516,289 @@ class SidebandCore(): data_dict["allow_requests"] = allow_requests packed_dict = msgpack.packb(data_dict) - db = self.__db_connect() - dbc = db.cursor() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set data = ? where dest_context = ?" + data = (packed_dict, context_dest) + dbc.execute(query, data) + result = dbc.fetchall() + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation request options: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + if not is_retry: + RNS.log("Retrying operation...", RNS.LOG_ERROR) + self._db_conversation_set_requests(context_dest, allow_requests, is_retry=True) + + def _db_conversation_set_object(self, context_dest, is_object=False): + conv = self._db_conversation(context_dest) + data_dict = conv["data"] + if data_dict == None: + data_dict = {} + + data_dict["is_object"] = is_object + packed_dict = msgpack.packb(data_dict) - query = "UPDATE conv set data = ? where dest_context = ?" - data = (packed_dict, context_dest) - dbc.execute(query, data) - result = dbc.fetchall() - db.commit() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set data = ? where dest_context = ?" + data = (packed_dict, context_dest) + dbc.execute(query, data) + result = dbc.fetchall() + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation object option: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_set_object(context_dest, is_object, is_retry=True) + + def _db_conversation_set_ptt_enabled(self, context_dest, ptt_enabled=False): + conv = self._db_conversation(context_dest) + data_dict = conv["data"] + if data_dict == None: + data_dict = {} + + data_dict["ptt_enabled"] = ptt_enabled + packed_dict = msgpack.packb(data_dict) + + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set data = ? where dest_context = ?" + data = (packed_dict, context_dest) + dbc.execute(query, data) + result = dbc.fetchall() + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation PTT option: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_set_ptt_enabled(context_dest, ptt_enabled, is_retry=True) def _db_conversation_set_trusted(self, context_dest, trusted): - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE conv set trust = ? where dest_context = ?" - data = (trusted, context_dest) - dbc.execute(query, data) - result = dbc.fetchall() - db.commit() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set trust = ? where dest_context = ?" + data = (trusted, context_dest) + dbc.execute(query, data) + result = dbc.fetchall() + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation trusted option: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_set_trusted(context_dest, trusted, is_retry=True) def _db_conversation_set_name(self, context_dest, name): - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE conv set name=:name_data where dest_context=:ctx;" - dbc.execute(query, {"ctx": context_dest, "name_data": name.encode("utf-8")}) - result = dbc.fetchall() - db.commit() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE conv set name=:name_data where dest_context=:ctx;" + dbc.execute(query, {"ctx": context_dest, "name_data": name.encode("utf-8")}) + result = dbc.fetchall() + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while updating conversation name option: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_conversation_set_name(context_dest, name, is_retry=True) - def _db_conversations(self): - db = self.__db_connect() - dbc = db.cursor() - - dbc.execute("select * from conv") - result = dbc.fetchall() + def _db_conversations(self, conversations=True, objects=False): + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + dbc.execute("select * from conv") + result = dbc.fetchall() - if len(result) < 1: - return None - else: - convs = [] - for entry in result: - last_rx = entry[1] - last_tx = entry[2] - last_activity = max(last_rx, last_tx) - data = None - try: - data = msgpack.unpackb(entry[7]) - except: - pass + if len(result) < 1: + return None + else: + convs = [] + for entry in result: + is_object = False + last_rx = entry[1] + last_tx = entry[2] + last_activity = max(last_rx, last_tx) + data = None + try: + data = msgpack.unpackb(entry[7]) + if "is_object" in data: + is_object = data["is_object"] + except: + pass - conv = { - "dest": entry[0], - "unread": entry[3], - "last_rx": last_rx, - "last_tx": last_tx, - "last_activity": last_activity, - "trust": entry[5], - "data": data, - } - convs.append(conv) + conv = { + "dest": entry[0], + "unread": entry[3], + "last_rx": last_rx, + "last_tx": last_tx, + "last_activity": last_activity, + "type": entry[4], + "trust": entry[5], + "data": data, + } + should_add = False + if conversations and not is_object: + should_add = True + if objects and is_object: + should_add = True - return sorted(convs, key=lambda c: c["last_activity"], reverse=True) + if should_add: + convs.append(conv) + + return sorted(convs, key=lambda c: c["last_activity"], reverse=True) def _db_announces(self): - db = self.__db_connect() - dbc = db.cursor() - - dbc.execute("select * from announce order by received desc") - result = dbc.fetchall() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + dbc.execute("select * from announce order by received desc") + result = dbc.fetchall() - if len(result) < 1: - return None - else: - announces = [] - added_dests = [] - for entry in result: - try: - if not entry[2] in added_dests: - announce = { - "dest": entry[2], - "data": entry[3].decode("utf-8"), - "time": entry[1], - "type": entry[4] - } - added_dests.append(entry[2]) - announces.append(announce) - except Exception as e: - RNS.log("Exception while fetching announce from DB: "+str(e), RNS.LOG_ERROR) + if len(result) < 1: + return None + else: + announces = [] + added_dests = [] + for entry in result: + try: + if not entry[2] in added_dests: + app_data = entry[3] + dest_type = entry[4] + if entry[5] != None: + try: + extras = msgpack.unpackb(entry[5]) + except Exception as e: + RNS.log(f"Error while unpacking extras from announce: {e}", RNS.LOG_ERROR) + extras = None + else: + extras = None + if dest_type == "lxmf.delivery": + announced_name = LXMF.display_name_from_app_data(app_data) + announced_cost = self.message_router.get_outbound_stamp_cost(entry[2]) + else: + 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, + "cost" : announced_cost, + "time" : entry[1], + "type" : dest_type, + "extras": extras, + } + added_dests.append(entry[2]) + announces.append(announce) + except Exception as e: + RNS.log("Exception while fetching announce from DB: "+str(e), RNS.LOG_ERROR) - announces.reverse() - return announces + announces.reverse() + return announces def _db_conversation(self, context_dest): - db = self.__db_connect() - dbc = db.cursor() - - query = "select * from conv where dest_context=:ctx" - dbc.execute(query, {"ctx": context_dest}) - result = dbc.fetchall() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "select * from conv where dest_context=:ctx" + dbc.execute(query, {"ctx": context_dest}) + result = dbc.fetchall() - if len(result) < 1: - return None - else: - c = result[0] - conv = {} - conv["dest"] = c[0] - conv["last_tx"] = c[1] - conv["last_rx"] = c[2] - conv["unread"] = c[3] - conv["type"] = c[4] - conv["trust"] = c[5] - conv["name"] = c[6].decode("utf-8") - conv["data"] = msgpack.unpackb(c[7]) - conv["last_activity"] = max(c[1], c[2]) - return conv + if len(result) < 1: + return None + else: + c = result[0] + conv = {} + conv["dest"] = c[0] + conv["last_tx"] = c[1] + conv["last_rx"] = c[2] + conv["unread"] = c[3] + conv["type"] = c[4] + conv["trust"] = c[5] + conv["name"] = c[6].decode("utf-8") + conv["data"] = msgpack.unpackb(c[7]) + conv["last_activity"] = max(c[1], c[2]) + return conv def _db_clear_conversation(self, context_dest): RNS.log("Clearing conversation with "+RNS.prettyhexrep(context_dest), RNS.LOG_DEBUG) - db = self.__db_connect() - dbc = db.cursor() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() - query = "delete from lxm where (dest=:ctx_dst or source=:ctx_dst);" - dbc.execute(query, {"ctx_dst": context_dest}) - db.commit() + query = "delete from lxm where (dest=:ctx_dst or source=:ctx_dst);" + dbc.execute(query, {"ctx_dst": context_dest}) + db.commit() def _db_clear_telemetry(self, context_dest): RNS.log("Clearing telemetry for "+RNS.prettyhexrep(context_dest), RNS.LOG_DEBUG) - db = self.__db_connect() - dbc = db.cursor() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() - query = "delete from telemetry where dest_context=:ctx_dst;" - dbc.execute(query, {"ctx_dst": context_dest}) - db.commit() + query = "delete from telemetry where dest_context=:ctx_dst;" + dbc.execute(query, {"ctx_dst": context_dest}) + db.commit() self.setstate("app.flags.last_telemetry", time.time()) def _db_delete_conversation(self, context_dest): RNS.log("Deleting conversation with "+RNS.prettyhexrep(context_dest), RNS.LOG_DEBUG) - db = self.__db_connect() - dbc = db.cursor() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() - query = "delete from conv where (dest_context=:ctx_dst);" - dbc.execute(query, {"ctx_dst": context_dest}) - db.commit() + query = "delete from conv where (dest_context=:ctx_dst);" + dbc.execute(query, {"ctx_dst": context_dest}) + db.commit() def _db_delete_announce(self, context_dest): RNS.log("Deleting announce with "+RNS.prettyhexrep(context_dest), RNS.LOG_DEBUG) - db = self.__db_connect() - dbc = db.cursor() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() - query = "delete from announce where (source=:ctx_dst);" - dbc.execute(query, {"ctx_dst": context_dest}) - db.commit() + query = "delete from announce where (source=:ctx_dst);" + dbc.execute(query, {"ctx_dst": context_dest}) + db.commit() def _db_create_conversation(self, context_dest, name = None, trust = False): RNS.log("Creating conversation for "+RNS.prettyhexrep(context_dest), RNS.LOG_DEBUG) - db = self.__db_connect() - dbc = db.cursor() + 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 = (context_dest, 0, time.time(), 0, SidebandCore.CONV_P2P, 0, def_name, msgpack.packb(None)) + def_name = "".encode("utf-8") + query = "INSERT INTO conv (dest_context, last_tx, last_rx, unread, type, trust, name, data) values (?, ?, ?, ?, ?, ?, ?, ?)" + data = (context_dest, 0, time.time(), 0, SidebandCore.CONV_P2P, 0, def_name, msgpack.packb(None)) - dbc.execute(query, data) - db.commit() + dbc.execute(query, data) + db.commit() if trust: self._db_conversation_set_trusted(context_dest, True) @@ -2115,125 +2808,142 @@ 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)) - db = self.__db_connect() - dbc = db.cursor() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() - query = "delete from lxm where (lxm_hash=:mhash);" - dbc.execute(query, {"mhash": msg_hash}) - db.commit() + query = "delete from lxm where (lxm_hash=:mhash);" + dbc.execute(query, {"mhash": msg_hash}) + db.commit() def _db_clean_messages(self): - RNS.log("Purging stale messages... "+str(self.db_path)) - db = self.__db_connect() - dbc = db.cursor() + RNS.log("Purging stale messages... ", RNS.LOG_DEBUG) + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() - query = "delete from lxm where (state=:outbound_state or state=:sending_state);" - dbc.execute(query, {"outbound_state": LXMF.LXMessage.OUTBOUND, "sending_state": LXMF.LXMessage.SENDING}) - db.commit() + query = "delete from lxm where (state=:outbound_state or state=:sending_state);" + dbc.execute(query, {"outbound_state": LXMF.LXMessage.OUTBOUND, "sending_state": LXMF.LXMessage.SENDING}) + db.commit() - def _db_message_set_state(self, lxm_hash, state): - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE lxm set state = ? where lxm_hash = ?" - data = (state, lxm_hash) - dbc.execute(query, data) - db.commit() - result = dbc.fetchall() + 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: + try: + msg = self._db_message(lxm_hash) + if msg != None: + msg_extras = msg["extras"] + + if ratchet_id: + msg_extras["ratchet_id"] = ratchet_id + + if originator_stamp: + msg_extras["stamp_checked"] = False + msg_extras["stamp_raw"] = originator_stamp[0] + msg_extras["stamp_valid"] = originator_stamp[1] + msg_extras["stamp_value"] = originator_stamp[2] + + except Exception as e: + RNS.log("An error occurred while getting message extras: "+str(e)) + + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + if msg_extras != None: + extras = msgpack.packb(msg_extras) + query = "UPDATE lxm set state = ?, extra = ? where lxm_hash = ?" + data = (state, extras, lxm_hash) + + else: + query = "UPDATE lxm set state = ? where lxm_hash = ?" + data = (state, lxm_hash) + + dbc.execute(query, data) + + try: + db.commit() + result = dbc.fetchall() + except Exception as e: + RNS.log("An error occurred while updating message state: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_message_set_state(lxm_hash, state, is_retry=True) def _db_message_set_method(self, lxm_hash, method): - db = self.__db_connect() - dbc = db.cursor() - - query = "UPDATE lxm set method = ? where lxm_hash = ?" - data = (method, lxm_hash) - dbc.execute(query, data) - db.commit() - result = dbc.fetchall() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "UPDATE lxm set method = ? where lxm_hash = ?" + data = (method, lxm_hash) + dbc.execute(query, data) + + try: + db.commit() + result = dbc.fetchall() + except Exception as e: + RNS.log("An error occurred while updating message method: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_message_set_method(lxm_hash, method, is_retry=True) def message(self, msg_hash): return self._db_message(msg_hash) def _db_message(self, msg_hash): - db = self.__db_connect() - dbc = db.cursor() - - query = "select * from lxm where lxm_hash=:mhash" - dbc.execute(query, {"mhash": msg_hash}) - result = dbc.fetchall() + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "select * from lxm where lxm_hash=:mhash" + dbc.execute(query, {"mhash": msg_hash}) + result = dbc.fetchall() - if len(result) < 1: - return None - else: - entry = result[0] - - lxm_method = entry[7] - if lxm_method == LXMF.LXMessage.PAPER: - lxm_data = msgpack.unpackb(entry[10]) - packed_lxm = lxm_data[0] - paper_packed_lxm = lxm_data[1] + if len(result) < 1: + return None else: - packed_lxm = entry[10] + entry = result[0] - lxm = LXMF.LXMessage.unpack_from_bytes(packed_lxm, original_method = lxm_method) - - if lxm.desired_method == LXMF.LXMessage.PAPER: - lxm.paper_packed = paper_packed_lxm - - message = { - "hash": lxm.hash, - "dest": lxm.destination_hash, - "source": lxm.source_hash, - "title": lxm.title, - "content": lxm.content, - "received": entry[5], - "sent": lxm.timestamp, - "state": entry[6], - "method": entry[7], - "lxm": lxm - } - return message - - def _db_message_count(self, context_dest): - db = self.__db_connect() - dbc = db.cursor() - - query = "select count(*) from lxm where dest=:context_dest or source=:context_dest" - dbc.execute(query, {"context_dest": context_dest}) - - result = dbc.fetchall() - - if len(result) < 1: - return None - else: - return result[0][0] - - def _db_messages(self, context_dest, after = None, before = None, limit = None): - db = self.__db_connect() - dbc = db.cursor() - - 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}) - 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}) - 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}) - else: - query = "select * from lxm where dest=:context_dest or source=:context_dest" - dbc.execute(query, {"context_dest": context_dest}) - - result = dbc.fetchall() - - if len(result) < 1: - return None - else: - messages = [] - for entry in result: lxm_method = entry[7] if lxm_method == LXMF.LXMessage.PAPER: lxm_data = msgpack.unpackb(entry[10]) @@ -2242,17 +2952,17 @@ class SidebandCore(): else: packed_lxm = entry[10] - lxm = LXMF.LXMessage.unpack_from_bytes(packed_lxm, original_method = lxm_method) - - if lxm.desired_method == LXMF.LXMessage.PAPER: - lxm.paper_packed = paper_packed_lxm - extras = None try: extras = msgpack.unpackb(entry[11]) except: pass - + + lxm = LXMF.LXMessage.unpack_from_bytes(packed_lxm, original_method = lxm_method) + + if lxm.desired_method == LXMF.LXMessage.PAPER: + lxm.paper_packed = paper_packed_lxm + message = { "hash": lxm.hash, "dest": lxm.destination_hash, @@ -2266,13 +2976,99 @@ class SidebandCore(): "lxm": lxm, "extras": extras, } + return message - messages.append(message) - if len(messages) > limit: - messages = messages[-limit:] - return messages + def _db_message_count(self, context_dest): + with self.db_lock: + db = self.__db_connect() + dbc = db.cursor() + + query = "select count(*) from lxm where dest=:context_dest or source=:context_dest" + dbc.execute(query, {"context_dest": context_dest}) - def _db_save_lxm(self, lxm, context_dest, originator = False, own_command = False): + result = dbc.fetchall() + + if len(result) < 1: + return None + else: + return result[0][0] + + def _db_messages(self, context_dest, after = None, before = None, limit = None): + 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 = 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 = 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 = 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 = 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() + + if len(result) < 1: + return None + else: + messages = [] + for entry in result: + lxm_method = entry[7] + if lxm_method == LXMF.LXMessage.PAPER: + lxm_data = msgpack.unpackb(entry[10]) + packed_lxm = lxm_data[0] + paper_packed_lxm = lxm_data[1] + else: + packed_lxm = entry[10] + + lxm = LXMF.LXMessage.unpack_from_bytes(packed_lxm, original_method = lxm_method) + + if lxm.desired_method == LXMF.LXMessage.PAPER: + lxm.paper_packed = paper_packed_lxm + + extras = None + try: extras = msgpack.unpackb(entry[11]) + except: pass + + message = { + "hash": lxm.hash, + "dest": lxm.destination_hash, + "source": lxm.source_hash, + "title": lxm.title, + "content": lxm.content, + "received": entry[5], + "sent": lxm.timestamp, + "state": entry[6], + "method": entry[7], + "lxm": lxm, + "extras": extras, + } + + messages.append(message) + + 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): state = lxm.state packed_telemetry = None @@ -2300,6 +3096,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: @@ -2311,84 +3108,123 @@ 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() + + if not lxm.packed: + lxm.pack() + + if lxm.method == LXMF.LXMessage.PAPER: + packed_lxm = msgpack.packb([lxm.packed, lxm.paper_packed]) + else: + packed_lxm = lxm.packed + + extras = {} + if lxm.rssi or lxm.snr or lxm.q: + extras["rssi"] = lxm.rssi + extras["snr"] = lxm.snr + extras["q"] = lxm.q + + if lxm.stamp_checked: + extras["stamp_checked"] = True + extras["stamp_valid"] = lxm.stamp_valid + extras["stamp_value"] = lxm.stamp_value + extras["stamp_raw"] = lxm.stamp + + if lxm.ratchet_id: + extras["ratchet_id"] = lxm.ratchet_id + + if packed_telemetry != None: + extras["packed_telemetry"] = packed_telemetry + + extras = msgpack.packb(extras) + + query = "INSERT INTO lxm (lxm_hash, dest, source, title, tx_ts, rx_ts, state, method, t_encrypted, t_encryption, data, extra) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + data = ( + lxm.hash, + lxm.destination_hash, + lxm.source_hash, + lxm.title, + lxm.timestamp, + time.time(), + state, + lxm.method, + lxm.transport_encrypted, + lxm.transport_encryption, + packed_lxm, + extras + ) + + dbc.execute(query, data) + + try: + db.commit() + except Exception as e: + RNS.log("An error occurred while saving message to database: "+str(e), RNS.LOG_ERROR) + self.__db_reconnect() + # if not is_retry: + # RNS.log("Retrying operation...", RNS.LOG_ERROR) + # self._db_save_lxm(lxm, context_dest, originator = originator, own_command = own_command, is_retry = True) + # return + + self.__event_conversation_changed(context_dest) + + def _db_save_announce(self, destination_hash, app_data, dest_type="lxmf.delivery", link_stats = None): + with self.db_lock: db = self.__db_connect() dbc = db.cursor() - if not lxm.packed: - lxm.pack() + query = "delete from announce where id is NULL or id not in (select id from announce order by received desc limit "+str(self.MAX_ANNOUNCES)+")" + dbc.execute(query) - if lxm.method == LXMF.LXMessage.PAPER: - packed_lxm = msgpack.packb([lxm.packed, lxm.paper_packed]) - else: - packed_lxm = lxm.packed + query = "delete from announce where (source=:source);" + dbc.execute(query, {"source": destination_hash}) - extras = {} - if lxm.rssi or lxm.snr or lxm.q: - extras["rssi"] = lxm.rssi - extras["snr"] = lxm.snr - extras["q"] = lxm.q + now = time.time() + hash_material = str(time).encode("utf-8")+destination_hash+app_data+dest_type.encode("utf-8") + announce_hash = RNS.Identity.full_hash(hash_material) + extras = msgpack.packb({"link_stats": link_stats}) - if packed_telemetry != None: - extras["packed_telemetry"] = packed_telemetry - - extras = msgpack.packb(extras) - - query = "INSERT INTO lxm (lxm_hash, dest, source, title, tx_ts, rx_ts, state, method, t_encrypted, t_encryption, data, extra) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + query = "INSERT INTO announce (id, received, source, data, dest_type, extra) values (?, ?, ?, ?, ?, ?)" data = ( - lxm.hash, - lxm.destination_hash, - lxm.source_hash, - lxm.title, - lxm.timestamp, - time.time(), - state, - lxm.method, - lxm.transport_encrypted, - lxm.transport_encryption, - packed_lxm, - extras + announce_hash, + now, + destination_hash, + app_data, + dest_type, + extras, ) dbc.execute(query, data) db.commit() - self.__event_conversation_changed(context_dest) - - def _db_save_announce(self, destination_hash, app_data, dest_type="lxmf.delivery"): - db = self.__db_connect() - dbc = db.cursor() - - query = "delete from announce where id is NULL or id not in (select id from announce order by received desc limit "+str(self.MAX_ANNOUNCES)+")" - dbc.execute(query) - - query = "delete from announce where (source=:source);" - dbc.execute(query, {"source": destination_hash}) - - now = time.time() - hash_material = str(time).encode("utf-8")+destination_hash+app_data+dest_type.encode("utf-8") - announce_hash = RNS.Identity.full_hash(hash_material) - - query = "INSERT INTO announce (id, received, source, data, dest_type) values (?, ?, ?, ?, ?)" - data = ( - announce_hash, - now, - destination_hash, - app_data, - dest_type, - ) - - dbc.execute(query, data) - db.commit() - def lxmf_announce(self, attached_interface=None): if self.is_standalone or self.is_service: - self.lxmf_destination.announce(attached_interface=attached_interface) + if self.config["lxmf_require_stamps"]: + self.message_router.set_inbound_stamp_cost(self.lxmf_destination.hash, self.config["lxmf_inbound_stamp_cost"]) + self.message_router.announce(self.lxmf_destination.hash, attached_interface=attached_interface) + else: + self.message_router.set_inbound_stamp_cost(self.lxmf_destination.hash, None) + self.lxmf_destination.announce(attached_interface=attached_interface) self.last_lxmf_announce = time.time() - self.next_auto_announce = time.time() + 60*(random.random()*(SidebandCore.AUTO_ANNOUNCE_RANDOM_MAX-SidebandCore.AUTO_ANNOUNCE_RANDOM_MIN)) + self.next_auto_announce = time.time() + 60*(random.random()*(SidebandCore.AUTO_ANNOUNCE_RANDOM_MAX-SidebandCore.AUTO_ANNOUNCE_RANDOM_MIN)+SidebandCore.AUTO_ANNOUNCE_RANDOM_MIN) RNS.log("Next auto announce in "+RNS.prettytime(self.next_auto_announce-time.time()), RNS.LOG_DEBUG) self.setstate("wants.announce", False) + else: + if self.config["lxmf_require_stamps"]: + self.message_router.set_inbound_stamp_cost(self.lxmf_destination.hash, self.config["lxmf_inbound_stamp_cost"]) + else: + self.message_router.set_inbound_stamp_cost(self.lxmf_destination.hash, None) + self.setstate("wants.announce", True) def run_telemetry(self): @@ -2425,35 +3261,49 @@ class SidebandCore(): self.update_telemeter_config() self.setstate("app.flags.last_telemetry", time.time()) + def mqtt_handle_telemetry(self, context_dest, telemetry): + with self.mqtt_handle_lock: + if hasattr(self, "last_mqtt_recycle") and time.time() > self.last_mqtt_recycle + 60*4: + self.mqtt.stop() + self.mqtt.client = None + self.mqtt = None + gc.collect() + + 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) + def update_telemetry(self): try: + 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 self.latest_telemetry == None or len(telemetry) != len(self.latest_telemetry): - telemetry_changed = True + if latest_telemetry == None or len(telemetry) != len(latest_telemetry): telemetry_changed = True - for sn in telemetry: - if telemetry_changed: - break + if latest_telemetry != None: + if not telemetry_changed: + for sn in telemetry: + if telemetry_changed: break - if sn != "time": - if sn in self.latest_telemetry: - if telemetry[sn] != self.latest_telemetry[sn]: - telemetry_changed = True - else: - telemetry_changed = True + if sn != "time": + if sn in latest_telemetry: + if telemetry[sn] != latest_telemetry[sn]: telemetry_changed = True + else: telemetry_changed = True - if self.latest_telemetry != None: - for sn in self.latest_telemetry: - if telemetry_changed: - break - - if sn != "time": - if not sn in telemetry: - telemetry_changed = True + if not telemetry_changed: + for sn in latest_telemetry: + if telemetry_changed: break + if sn != "time": + if not sn in telemetry: telemetry_changed = True if telemetry_changed: self.telemetry_changes += 1 @@ -2462,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 @@ -2481,7 +3329,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) @@ -2497,7 +3347,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) @@ -2518,7 +3368,7 @@ class SidebandCore(): if self.config["telemetry_s_information"]: self.telemeter.synthesize("information") - self.telemeter.sensors["information"].contents = self.config["telemetry_s_information_text"] + self.telemeter.sensors["information"].set_contents(self.config["telemetry_s_information_text"]) else: self.telemeter = None @@ -2529,6 +3379,10 @@ class SidebandCore(): if self.config["telemetry_enabled"] == True: self.update_telemeter_config() if self.telemeter != None: + 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 {} @@ -2549,14 +3403,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: @@ -2567,6 +3417,19 @@ class SidebandCore(): RNS.log("Error while querying for key: "+str(e), RNS.LOG_ERROR) return False + def _update_delivery_limits(self): + try: + if self.config["lxm_limit_1mb"]: + lxm_limit = 1000 + else: + lxm_limit = self.default_lxm_limit + if self.message_router.delivery_per_transfer_limit != lxm_limit: + self.message_router.delivery_per_transfer_limit = lxm_limit + RNS.log("Updated delivery limit to "+RNS.prettysize(self.message_router.delivery_per_transfer_limit*1000), RNS.LOG_DEBUG) + + except Exception as e: + RNS.log("Error while updating LXMF router delivery limit: "+str(e), RNS.LOG_ERROR) + def _service_jobs(self): if self.is_service: last_usb_discovery = time.time() @@ -2600,8 +3463,18 @@ 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: + if len(self.interface_rnode.hw_errors) > 0: + 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]) + + self.interface_rnode.hw_errors = [] + if (now - last_multicast_lock_check > 120): RNS.log("Checking multicast and wake locks", RNS.LOG_DEBUG) self.owner_service.take_locks() @@ -2627,7 +3500,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: @@ -2668,6 +3540,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() @@ -2742,6 +3615,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() @@ -2761,6 +3646,8 @@ class SidebandCore(): if self.owner_service != None: self.owner_service.update_location_provider() + self._update_delivery_limits() + if self.config["lxmf_periodic_sync"] == True: if self.getpersistent("lxmf.lastsync") == None: self.setpersistent("lxmf.lastsync", time.time()) @@ -2788,6 +3675,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: @@ -2838,13 +3728,35 @@ 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) except Exception as e: RNS.log("An error occurred while requesting scheduled telemetry from collector: "+str(e), RNS.LOG_ERROR) + stale_entries = [] + if len(self.live_tracked_objects) > 0: + now = time.time() + for object_hash in self.live_tracked_objects: + tracking_entry = self.live_tracked_objects[object_hash] + tracking_int = tracking_entry[0] + tracking_last = tracking_entry[1] + tracking_end = tracking_entry[2] + + if now < tracking_end: + if now > tracking_last+tracking_int: + RNS.log("Next live tracking request time reached for "+str(RNS.prettyhexrep(object_hash))) + self.request_latest_telemetry(from_addr=object_hash, is_livetrack=True) + tracking_entry[1] = time.time() + else: + stale_entries.append(object_hash) + + for object_hash in stale_entries: + RNS.log("Terminating live tracking for "+RNS.prettyhexrep(object_hash)+", tracking duration reached", RNS.LOG_DEBUG) + self.live_tracked_objects.pop(object_hash) + + def __start_jobs_deferred(self): if self.is_service: self.service_thread = threading.Thread(target=self._service_jobs, daemon=True) @@ -2855,6 +3767,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() @@ -2862,9 +3775,15 @@ 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"]: + 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): @@ -2889,11 +3808,12 @@ class SidebandCore(): else: ifac_netkey = self.config["connect_local_ifac_passphrase"] - autointerface = RNS.Interfaces.AutoInterface.AutoInterface( - RNS.Transport, - name = "AutoInterface", - group_id = group_id - ) + interface_config = { + "name": "AutoInterface", + "group_id": group_id + } + + autointerface = RNS.Interfaces.AutoInterface.AutoInterface(RNS.Transport, interface_config) autointerface.OUT = True if RNS.Reticulum.transport_enabled(): @@ -2918,25 +3838,290 @@ 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: + time.sleep(delay) + + try: + RNS.log("Adding RNode Interface...", RNS.LOG_DEBUG) + target_device = None + if len(self.owner_app.usb_devices) > 0: + # TODO: Add more intelligent selection here + target_device = self.owner_app.usb_devices[0] + + # if target_device or self.config["hw_rnode_bluetooth"]: + if target_device != None: + target_port = target_device["port"] + else: + target_port = None + + 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) + rnode_allow_bluetooth = True + if self.config["hw_rnode_bt_device"] != None: + bt_device_name = self.config["hw_rnode_bt_device"] + + else: + RNS.log("Disallowing RNode bluetooth since config is disabled", RNS.LOG_DEBUG) + rnode_allow_bluetooth = False + + if self.config["hw_rnode_ble"] and self.getpersistent("permissions.bluetooth"): + RNS.log("Allowing RNode BLE", RNS.LOG_DEBUG) + rnode_allow_ble = True + else: + RNS.log("Disallowing RNode BLE", RNS.LOG_DEBUG) + rnode_allow_ble = False + + else: + RNS.log("Disallowing RNode bluetooth due to missing permission", RNS.LOG_DEBUG) + rnode_allow_bluetooth = False + + 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_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: + 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": True, + "ble_name": bt_device_name, + "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", + "port": target_port, + "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": rnode_allow_bluetooth, + "target_device_name": bt_device_name, + "force_ble": False, + "ble_name": None, + "ble_addr": None, + } + + rnodeinterface = RNS.Interfaces.Android.RNodeInterface.RNodeInterface(RNS.Transport, interface_config) + rnodeinterface.OUT = True + + 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 + + self.reticulum._add_interface(rnodeinterface, mode = if_mode, ifac_netname = ifac_netname, ifac_netkey = ifac_netkey) + self.interface_rnode = rnodeinterface + self.interface_rnode_adding = False + + if rnodeinterface != None: + if len(rnodeinterface.hw_errors) > 0: + self.setpersistent("startup.errors.rnode", rnodeinterface.hw_errors[0]) + + if self.config["hw_rnode_enable_framebuffer"] == True: + if self.interface_rnode.online: + self.interface_rnode.display_image(sideband_fb_data) + self.interface_rnode.enable_external_framebuffer() + else: + self.interface_rnode.last_imagedata = sideband_fb_data + else: + if self.interface_rnode.online: + self.interface_rnode.disable_external_framebuffer() + + except Exception as e: + RNS.log("Error while adding RNode Interface. The contained exception was: "+str(e)) + RNS.trace_exception(e) + self.interface_rnode = None + self.interface_rnode_adding = False + 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: self.service_rpc_set_debug(debug) + def _log_handler(self, message): + self.log_deque.append(message) + print(message) + + # TODO: Get service log on Android + 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_verbose: + if self.log_quiet: + selected_level = 0 + elif self.log_verbose: selected_level = 6 else: selected_level = 2 self.setstate("init.loadingstate", "Substantiating Reticulum") - self.reticulum = RNS.Reticulum(configdir=self.rns_configdir, loglevel=selected_level) + + try: + 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(os.path.join(self.rns_configdir, "config_template_invalid")): + os.unlink(os.path.join(self.rns_configdir, "config_template_invalid")) + else: + pass + + except Exception as e: + RNS.log(f"Error while instantiating Reticulum: {e}", RNS.LOG_ERROR) + RNS.log(f"Local configuration template changes will be ignored on next start", RNS.LOG_ERROR) + exit(255) if self.is_service: self.__start_rpc_listener() @@ -2958,6 +4143,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 @@ -2990,15 +4176,14 @@ class SidebandCore(): else: ifac_size = None - tcpinterface = RNS.Interfaces.TCPInterface.TCPClientInterface( - RNS.Transport, - "TCPClientInterface", - tcp_host, - tcp_port, - kiss_framing = False, - i2p_tunneled = False - ) - + interface_config = { + "name": "TCP Client", + "target_host": tcp_host, + "target_port": tcp_port, + "kiss_framing": False, + "i2p_tunneled": False, + } + tcpinterface = RNS.Interfaces.BackboneInterface.BackboneClientInterface(RNS.Transport, interface_config) tcpinterface.OUT = True if RNS.Reticulum.transport_enabled(): @@ -3042,13 +4227,14 @@ class SidebandCore(): else: ifac_size = None - i2pinterface = RNS.Interfaces.I2PInterface.I2PInterface( - RNS.Transport, - "I2PInterface", - RNS.Reticulum.storagepath, - [self.config["connect_i2p_b32"]], - connectable = False, - ) + interface_config = { + "name": "I2PInterface", + "storagepath": RNS.Reticulum.storagepath, + "peers": [self.config["connect_i2p_b32"]], + "connectable": False, + } + + i2pinterface = RNS.Interfaces.I2PInterface.I2PInterface(RNS.Transport, interface_config) i2pinterface.OUT = True @@ -3078,108 +4264,11 @@ class SidebandCore(): if self.config["connect_rnode"]: self.setstate("init.loadingstate", "Starting RNode") - try: - RNS.log("Adding RNode Interface...", RNS.LOG_DEBUG) - target_device = None - if len(self.owner_app.usb_devices) > 0: - # TODO: Add more intelligent selection here - target_device = self.owner_app.usb_devices[0] + self.__add_rnodeinterface() - # if target_device or self.config["hw_rnode_bluetooth"]: - if target_device != None: - target_port = target_device["port"] - else: - target_port = None - - bt_device_name = None - rnode_allow_bluetooth = False - if self.getpersistent("permissions.bluetooth"): - if self.config["hw_rnode_bluetooth"]: - RNS.log("Allowing RNode bluetooth", RNS.LOG_DEBUG) - rnode_allow_bluetooth = True - if self.config["hw_rnode_bt_device"] != None: - bt_device_name = self.config["hw_rnode_bt_device"] - - else: - RNS.log("Disallowing RNode bluetooth since config is disabled", RNS.LOG_DEBUG) - rnode_allow_bluetooth = False - else: - 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["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"] - - rnodeinterface = RNS.Interfaces.Android.RNodeInterface.RNodeInterface( - RNS.Transport, - "RNodeInterface", - target_port, - frequency = self.config["hw_rnode_frequency"], - bandwidth = self.config["hw_rnode_bandwidth"], - txpower = self.config["hw_rnode_tx_power"], - sf = self.config["hw_rnode_spreading_factor"], - cr = self.config["hw_rnode_coding_rate"], - flow_control = None, - id_interval = self.config["hw_rnode_beaconinterval"], - id_callsign = self.config["hw_rnode_beacondata"], - allow_bluetooth = rnode_allow_bluetooth, - target_device_name = bt_device_name, - st_alock = atl_short, - lt_alock = atl_long, - ) - - rnodeinterface.OUT = True - - 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 - - self.reticulum._add_interface(rnodeinterface, mode = if_mode, ifac_netname = ifac_netname, ifac_netkey = ifac_netkey) - self.interface_rnode = rnodeinterface - - if rnodeinterface != None: - if len(rnodeinterface.hw_errors) > 0: - self.setpersistent("startup.errors.rnode", rnodeinterface.hw_errors[0]) - - if self.config["hw_rnode_enable_framebuffer"] == True: - if self.interface_rnode.online: - self.interface_rnode.display_image(sideband_fb_data) - self.interface_rnode.enable_external_framebuffer() - else: - self.interface_rnode.last_imagedata = sideband_fb_data - else: - if self.interface_rnode.online: - self.interface_rnode.disable_external_framebuffer() - - except Exception as e: - RNS.log("Error while adding RNode Interface. The contained exception was: "+str(e)) - self.interface_rnode = None + if self.config["connect_weave"]: + self.setstate("init.loadingstate", "Starting Weave") + self.__add_weaveinterface() elif self.config["connect_serial"]: self.setstate("init.loadingstate", "Starting Serial Interface") @@ -3202,16 +4291,15 @@ class SidebandCore(): else: ifac_netkey = self.config["connect_serial_ifac_passphrase"] - serialinterface = RNS.Interfaces.Android.SerialInterface.SerialInterface( - RNS.Transport, - "SerialInterface", - target_device["port"], - self.config["hw_serial_baudrate"], - self.config["hw_serial_databits"], - self.config["hw_serial_parity"], - self.config["hw_serial_stopbits"], - ) - + interface_config = { + "name": "SerialInterface", + "port": target_device["port"], + "speed": self.config["hw_serial_baudrate"], + "databits": self.config["hw_serial_databits"], + "parity": self.config["hw_serial_parity"], + "stopbits": self.config["hw_serial_stopbits"], + } + serialinterface = RNS.Interfaces.Android.SerialInterface.SerialInterface(RNS.Transport, interface_config) serialinterface.OUT = True if RNS.Reticulum.transport_enabled(): @@ -3255,23 +4343,22 @@ class SidebandCore(): else: ifac_netkey = self.config["connect_modem_ifac_passphrase"] - modeminterface = RNS.Interfaces.Android.KISSInterface.KISSInterface( - RNS.Transport, - "ModemInterface", - target_device["port"], - self.config["hw_modem_baudrate"], - self.config["hw_modem_databits"], - self.config["hw_modem_parity"], - self.config["hw_modem_stopbits"], - self.config["hw_modem_preamble"], - self.config["hw_modem_tail"], - self.config["hw_modem_persistence"], - self.config["hw_modem_slottime"], - False, # flow control - self.config["hw_modem_beaconinterval"], - self.config["hw_modem_beacondata"], - ) - + interface_config = { + "name": "ModemInterface", + "port": target_device["port"], + "speed": self.config["hw_modem_baudrate"], + "databits": self.config["hw_modem_databits"], + "parity": self.config["hw_modem_parity"], + "stopbits": self.config["hw_modem_stopbits"], + "preamble": self.config["hw_modem_preamble"], + "txtail": self.config["hw_modem_tail"], + "persistence": self.config["hw_modem_persistence"], + "slottime": self.config["hw_modem_slottime"], + "flow_control": False, + "beacon_interval": self.config["hw_modem_beaconinterval"], + "beacon_data": self.config["hw_modem_beacondata"], + } + modeminterface = RNS.Interfaces.Android.KISSInterface.KISSInterface(RNS.Transport, interface_config) modeminterface.OUT = True if RNS.Reticulum.transport_enabled(): @@ -3300,13 +4387,26 @@ class SidebandCore(): if self.config["lxm_limit_1mb"]: lxm_limit = 1000 else: - lxm_limit = 128*1000 + lxm_limit = self.default_lxm_limit self.message_router = LXMF.LXMRouter(identity = self.identity, storagepath = self.lxmf_storage, autopeer = True, delivery_limit = lxm_limit) self.message_router.register_delivery_callback(self.lxmf_delivery) - self.lxmf_destination = self.message_router.register_delivery_identity(self.identity, display_name=self.config["display_name"]) - self.lxmf_destination.set_default_app_data(self.get_display_name_bytes) + configured_stamp_cost = None + if self.config["lxmf_require_stamps"]: + configured_stamp_cost = self.config["lxmf_inbound_stamp_cost"] + + self.lxmf_destination = self.message_router.register_delivery_identity(self.identity, display_name=self.config["display_name"], stamp_cost=configured_stamp_cost) + if self.config["lxmf_ignore_invalid_stamps"]: + self.message_router.enforce_stamps() + else: + self.message_router.ignore_stamps() + + # TODO: Update to announce call in LXMF when full 0.5.0 support is added (get app data from LXMRouter instead) + # Currently overrides the LXMF routers auto-generated announce data so that Sideband will announce old-format + # LXMF announces if require_stamps is disabled. + # if not self.config["lxmf_require_stamps"]: + # self.lxmf_destination.set_default_app_data(self.get_display_name_bytes) self.rns_dir = RNS.Reticulum.configdir @@ -3321,19 +4421,30 @@ class SidebandCore(): else: self.set_active_propagation_node(None) + def update_ignore_invalid_stamps(self): + if self.config["lxmf_ignore_invalid_stamps"]: + self.message_router.enforce_stamps() + else: + self.message_router.ignore_stamps() + def message_notification_no_display(self, message): self.message_notification(message, no_display=True) def message_notification(self, message, no_display=False): if message.state == LXMF.LXMessage.FAILED and hasattr(message, "try_propagation_on_fail") and message.try_propagation_on_fail: - 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 - 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.message_router.handle_outbound(message) + 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) + 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 + 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: self.lxm_ingest(message, originator=True) @@ -3343,12 +4454,12 @@ class SidebandCore(): try: telemeter = Telemeter.from_packed(message.fields[LXMF.FIELD_TELEMETRY]) telemetry_timebase = telemeter.read_all()["time"]["utc"] - RNS.log("Setting last successul telemetry timebase for "+RNS.prettyhexrep(message.destination_hash)+" to "+str(telemetry_timebase)) + RNS.log("Setting last successul telemetry timebase for "+RNS.prettyhexrep(message.destination_hash)+" to "+str(telemetry_timebase), RNS.LOG_DEBUG) self.setpersistent(f"telemetry.{RNS.hexrep(message.destination_hash, delimit=False)}.last_send_success_timebase", telemetry_timebase) 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 @@ -3356,10 +4467,14 @@ class SidebandCore(): if send_telemetry and self.latest_packed_telemetry != None: telemeter = Telemeter.from_packed(self.latest_packed_telemetry) telemetry_timebase = telemeter.read_all()["time"]["utc"] - if telemetry_timebase > (self.getpersistent(f"telemetry.{RNS.hexrep(context_dest, delimit=False)}.last_send_success_timebase") or 0): + last_success_tb = (self.getpersistent(f"telemetry.{RNS.hexrep(context_dest, delimit=False)}.last_send_success_timebase") or 0) + 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 is not newer than latest successful timebase", RNS.LOG_DEBUG) + 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) send_telemetry = False send_appearance = False if signal_already_sent: @@ -3398,7 +4513,8 @@ class SidebandCore(): source = self.lxmf_destination desired_method = LXMF.LXMessage.PAPER - lxm = LXMF.LXMessage(dest, source, content, title="", desired_method=desired_method, fields = self.get_message_fields(destination_hash)) + # TODO: Should paper messages also include a ticket to trusted peers? + lxm = LXMF.LXMessage(dest, source, content, title="", desired_method=desired_method, fields = self.get_message_fields(destination_hash), include_ticket=self.is_trusted(destination_hash)) self.lxm_ingest(lxm, originator=True) @@ -3408,113 +4524,314 @@ class SidebandCore(): RNS.log("Error while creating paper message: "+str(e), RNS.LOG_ERROR) return False + def _service_get_lxm_progress(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_progress": {"lxm_hash": lxm_hash}}) + + except Exception as e: + RNS.log("Error while getting LXM progress over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + else: + return False + + def get_lxm_progress(self, lxm_hash): try: - return self.message_router.get_outbound_progress(lxm_hash) + prg = self.message_router.get_outbound_progress(lxm_hash) + if not prg and self.is_client: + prg = self._service_get_lxm_progress(lxm_hash) + + return prg except Exception as e: RNS.log("An error occurred while getting message transfer progress: "+str(e), RNS.LOG_ERROR) return None - def send_message(self, content, destination_hash, propagation, skip_fields=False, no_display=False, attachment = None, image = None, audio = None): - try: - if content == "": - raise ValueError("Message content cannot be empty") - - dest_identity = RNS.Identity.recall(destination_hash) - dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") - source = self.lxmf_destination - - if propagation: - desired_method = LXMF.LXMessage.PROPAGATED - else: - desired_method = LXMF.LXMessage.DIRECT - - if skip_fields: - fields = {} - else: - fields = self.get_message_fields(destination_hash) - - if attachment != None: - fields[LXMF.FIELD_FILE_ATTACHMENTS] = [attachment] - if image != None: - fields[LXMF.FIELD_IMAGE] = image - - lxm = LXMF.LXMessage(dest, source, content, title="", desired_method=desired_method, fields = fields) - - if not no_display: - lxm.register_delivery_callback(self.message_notification) - lxm.register_failed_callback(self.message_notification) - else: - lxm.register_delivery_callback(self.message_notification_no_display) - lxm.register_failed_callback(self.message_notification_no_display) - - if self.message_router.get_outbound_propagation_node() != None: - if self.config["lxmf_try_propagation_on_fail"]: - lxm.try_propagation_on_fail = True - - self.message_router.handle_outbound(lxm) - if not no_display: - self.lxm_ingest(lxm, originator=True) - - return True - - except Exception as e: - RNS.log("Error while sending message: "+str(e), RNS.LOG_ERROR) + def _service_get_lxm_stamp_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_stamp_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_stamp_cost(self, lxm_hash): + if self.allow_service_dispatch and self.is_client: + try: + return self._service_get_lxm_stamp_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_stamp_cost(lxm_hash) + except Exception as e: + 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 + else: + if self.is_client: + try: + return self.service_rpc_request({"cancel_message": {"message_id": message_id }}) + + except Exception as e: + RNS.log("Error while cancelling message over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + else: + return False + + def _service_send_message(self, content, destination_hash, propagation, skip_fields=False, no_display=False, attachment = None, image = None, audio = None): + if not RNS.vendor.platformutils.is_android(): + return False + else: + if self.is_client: + try: + return self.service_rpc_request({"send_message": { + "content": content, + "destination_hash": destination_hash, + "propagation": propagation, + "skip_fields": skip_fields, + "no_display": no_display, + "attachment": attachment, + "image": image, + "audio": audio} + }) + + 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 _service_send_command(self, content, destination_hash, propagation): + if not RNS.vendor.platformutils.is_android(): + return False + else: + if self.is_client: + try: + return self.service_rpc_request({"send_command": { + "content": content, + "destination_hash": destination_hash, + "propagation": propagation} + }) + + except Exception as e: + RNS.log("Error while sending command over RPC: "+str(e), RNS.LOG_DEBUG) + RNS.trace_exception(e) + return False + else: + return False + + def cancel_message(self, message_id): + if self.allow_service_dispatch and self.is_client: + try: + return self._service_cancel_message(message_id) + + except Exception as e: + RNS.log("Error while cancelling message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + + else: + try: + self.message_router.cancel_outbound(message_id) + return True + + except Exception as e: + RNS.log("Error while cancelling message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + + def send_message(self, content, destination_hash, propagation, skip_fields=False, no_display=False, attachment = None, image = None, audio = None): + if self.allow_service_dispatch and self.is_client: + try: + return self._service_send_message(content, destination_hash, propagation, skip_fields, no_display, attachment, image, audio) + + except Exception as e: + RNS.log("Error while sending message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False + + else: + try: + if content == "": + raise ValueError("Message content cannot be empty") + + dest_identity = RNS.Identity.recall(destination_hash) + dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") + source = self.lxmf_destination + + if propagation: + desired_method = LXMF.LXMessage.PROPAGATED + else: + if not self.message_router.delivery_link_available(destination_hash) and RNS.Identity.current_ratchet_id(destination_hash) != None: + RNS.log(f"Have ratchet for {RNS.prettyhexrep(destination_hash)}, requesting opportunistic delivery of message", RNS.LOG_DEBUG) + desired_method = LXMF.LXMessage.OPPORTUNISTIC + else: + desired_method = LXMF.LXMessage.DIRECT + + if skip_fields: + fields = {} + else: + fields = self.get_message_fields(destination_hash) + + if attachment != None: + fields[LXMF.FIELD_FILE_ATTACHMENTS] = [attachment] + if image != None: + fields[LXMF.FIELD_IMAGE] = image + if audio != None: + fields[LXMF.FIELD_AUDIO] = audio + md_sig = "#!md\n" + if content.startswith(md_sig): + content = content[len(md_sig):] + fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_MARKDOWN + elif self.config["compose_in_markdown"]: + fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_MARKDOWN + elif self.has_bb_markup(content): + fields[LXMF.FIELD_RENDERER] = LXMF.RENDERER_BBCODE + + lxm = LXMF.LXMessage(dest, source, content, title="", desired_method=desired_method, fields = fields, include_ticket=self.is_trusted(destination_hash)) + + if not no_display: + lxm.register_delivery_callback(self.message_notification) + lxm.register_failed_callback(self.message_notification) + else: + lxm.register_delivery_callback(self.message_notification_no_display) + lxm.register_failed_callback(self.message_notification_no_display) + + if self.message_router.get_outbound_propagation_node() != None: + if self.config["lxmf_try_propagation_on_fail"]: + lxm.try_propagation_on_fail = True + + self.message_router.handle_outbound(lxm) + + if not no_display: + self.lxm_ingest(lxm, originator=True) + + return True + + except Exception as e: + RNS.log("Error while sending message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + return False def send_command(self, content, destination_hash, propagation): - try: - if content == "": + if self.allow_service_dispatch and self.is_client: + try: + return self._service_send_command(content, destination_hash, propagation) + + except Exception as e: + RNS.log("Error while sending message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) return False - commands = [] - if content.startswith("echo "): - echo_content = content.replace("echo ", "").encode("utf-8") - if len(echo_content) > 0: - commands.append({Commands.ECHO: echo_content}) - elif content.startswith("sig"): - commands.append({Commands.SIGNAL_REPORT: True}) - elif content.startswith("ping"): - commands.append({Commands.PING: True}) - else: - commands.append({Commands.PLUGIN_COMMAND: content}) + else: + try: + if content == "": + return False - if len(commands) == 0: + commands = [] + if content.startswith("echo "): + echo_content = content.replace("echo ", "").encode("utf-8") + if len(echo_content) > 0: + commands.append({Commands.ECHO: echo_content}) + elif content.startswith("sig"): + commands.append({Commands.SIGNAL_REPORT: True}) + elif content.startswith("ping"): + commands.append({Commands.PING: True}) + else: + commands.append({Commands.PLUGIN_COMMAND: content}) + + if len(commands) == 0: + return False + + dest_identity = RNS.Identity.recall(destination_hash) + dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") + source = self.lxmf_destination + + if propagation: + desired_method = LXMF.LXMessage.PROPAGATED + else: + if not self.message_router.delivery_link_available(destination_hash) and RNS.Identity.current_ratchet_id(destination_hash) != None: + RNS.log(f"Have ratchet for {RNS.prettyhexrep(destination_hash)}, requesting opportunistic delivery of command", RNS.LOG_DEBUG) + desired_method = LXMF.LXMessage.OPPORTUNISTIC + else: + desired_method = LXMF.LXMessage.DIRECT + + lxm = LXMF.LXMessage(dest, source, "", title="", desired_method=desired_method, fields = {LXMF.FIELD_COMMANDS: commands}, include_ticket=self.is_trusted(destination_hash)) + lxm.register_delivery_callback(self.message_notification) + lxm.register_failed_callback(self.message_notification) + + if self.message_router.get_outbound_propagation_node() != None: + if self.config["lxmf_try_propagation_on_fail"]: + lxm.try_propagation_on_fail = True + + self.message_router.handle_outbound(lxm) + self.lxm_ingest(lxm, originator=True) + + return True + + except Exception as e: + RNS.log("Error while sending message: "+str(e), RNS.LOG_ERROR) return False - dest_identity = RNS.Identity.recall(destination_hash) - dest = RNS.Destination(dest_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery") - source = self.lxmf_destination - - if propagation: - desired_method = LXMF.LXMessage.PROPAGATED - else: - desired_method = LXMF.LXMessage.DIRECT - - lxm = LXMF.LXMessage(dest, source, "", title="", desired_method=desired_method, fields = {LXMF.FIELD_COMMANDS: commands}) - lxm.register_delivery_callback(self.message_notification) - lxm.register_failed_callback(self.message_notification) - - if self.message_router.get_outbound_propagation_node() != None: - if self.config["lxmf_try_propagation_on_fail"]: - lxm.try_propagation_on_fail = True - - self.message_router.handle_outbound(lxm) - self.lxm_ingest(lxm, originator=True) - - return True - - except Exception as e: - 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 try: addr_b = bytes.fromhex(dest_str) - self._db_create_conversation(addr_b, name, trusted) + if addr_b == self.lxmf_destination.hash: + RNS.log("Cannot create conversation with own LXMF address", RNS.LOG_ERROR) + return False + else: + 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) @@ -3556,9 +4873,23 @@ class SidebandCore(): self.setstate("lxm_uri_ingest.result", response) + def strip_bb_markup(self, text): + if not hasattr(self, "smr") or self.smr == None: + self.smr = re.compile(r"\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]",re.IGNORECASE | re.MULTILINE ) + return self.smr.sub("", text) + + def has_bb_markup(self, text): + if not hasattr(self, "smr") or self.smr == None: + self.smr = re.compile(r"\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]",re.IGNORECASE | re.MULTILINE ) + if self.smr.match(text): + return True + else: + return False + def lxm_ingest(self, message, originator = False): should_notify = False is_trusted = False + ptt_enabled = False telemetry_only = False own_command = False unread_reason_tx = False @@ -3569,13 +4900,17 @@ class SidebandCore(): else: context_dest = message.source_hash is_trusted = self.is_trusted(context_dest) + ptt_enabled = self.ptt_enabled(context_dest) if originator and LXMF.FIELD_COMMANDS in message.fields: own_command = True if self._db_message(message.hash): RNS.log("Message exists, setting state to: "+str(message.state), RNS.LOG_DEBUG) - self._db_message_set_state(message.hash, message.state) + stamp = None + if originator and message.stamp != None: + stamp = [message.stamp, message.stamp_valid, message.stamp_value] + self._db_message_set_state(message.hash, message.state, ratchet_id=message.ratchet_id, originator_stamp=stamp) else: RNS.log("Message does not exist, saving", RNS.LOG_DEBUG) self._db_save_lxm(message, context_dest, originator, own_command=own_command) @@ -3588,6 +4923,11 @@ class SidebandCore(): RNS.log("Squelching notification due to telemetry-only message", RNS.LOG_DEBUG) telemetry_only = True + if LXMF.FIELD_TICKET in message.fields: + if self.is_service: + RNS.log("Notifying UI of newly arrived delivery ticket", RNS.LOG_DEBUG) + self.setstate("app.flags.new_ticket", True) + if not telemetry_only: if self._db_conversation(context_dest) == None: self._db_create_conversation(context_dest) @@ -3611,6 +4951,14 @@ class SidebandCore(): if self.gui_display() == "conversations_screen" and self.gui_foreground(): should_notify = False + if not originator and LXMF.FIELD_AUDIO in message.fields and ptt_enabled: + self.ptt_event(message) + if self.gui_conversation() != context_dest: + if not RNS.vendor.platformutils.is_android(): + should_notify = True + else: + should_notify = False + if self.is_client: should_notify = False @@ -3620,14 +4968,97 @@ class SidebandCore(): if should_notify: nlen = 128 text = message.content.decode("utf-8") - notification_content = text[:nlen] + notification_content = self.strip_bb_markup(text[:nlen]) if len(text) > nlen: - text += "..." + notification_content += " [...]" - self.notify(title=self.peer_display_name(context_dest), content=notification_content, group="LXM", context_id=RNS.hexrep(context_dest, delimit=False)) + if len(text) < 2 and LXMF.FIELD_AUDIO in message.fields: + notification_content = "Audio message" + if len(text) < 2 and LXMF.FIELD_IMAGE in message.fields: + notification_content = "Image" + if len(text) < 2 and LXMF.FIELD_FILE_ATTACHMENTS in message.fields: + notification_content = "File attachment" + + try: + self.notify(title=self.peer_display_name(context_dest), content=notification_content, group="LXM", context_id=RNS.hexrep(context_dest, delimit=False)) + except Exception as e: + RNS.log("Could not post notification for received message: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + + def ptt_playback(self, message): + ptt_timeout = 60 + event_time = time.time() + with self.ptt_player_lock: + time.sleep(0.2) + + 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 = 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 = os.path.join(self.rec_cache, "ptt_msg.ogg") + from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2 + + 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 + else: pass + + 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) + + self.ptt_player.set_source(temp_path) + + 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(): + 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() + + def ui_started_recording(self): + self.ui_recording = True + self.service_rpc_set_ui_recording(True) + + def ui_stopped_recording(self): + self.ui_recording = False + self.service_rpc_set_ui_recording(False) def start(self): self._db_clean_messages() + self._db_clean_telemetry() self.__start_jobs_immediate() thread = threading.Thread(target=self.__start_jobs_deferred) @@ -3635,7 +5066,7 @@ class SidebandCore(): thread.start() self.setstate("core.started", True) - RNS.log("Sideband Core "+str(self)+" started") + RNS.log("Sideband Core "+str(self)+" "+str(self.version_str)+"started") def stop_webshare(self): if self.webshare_server != None: @@ -3648,6 +5079,7 @@ class SidebandCore(): from http import server import socketserver import json + import ssl webshare_dir = self.webshare_dir port = 4444 @@ -3668,7 +5100,7 @@ class SidebandCore(): self.send_response(200) self.send_header("Content-type", "text/json") self.end_headers() - json_result = json.dumps(os.listdir(serve_root+"/pkg")) + json_result = json.dumps(sorted(os.listdir(serve_root+"/pkg"))) self.wfile.write(json_result.encode("utf-8")) except Exception as e: self.send_response(500) @@ -3678,11 +5110,12 @@ 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") + elif path.lower().endswith(".js"): + self.send_header("Content-type", "text/javascript") self.end_headers() self.wfile.write(data) except Exception as e: @@ -3692,7 +5125,36 @@ class SidebandCore(): es = "Error" self.wfile.write(es.encode("utf-8")) - with socketserver.TCPServer(("", port), RequestHandler) as webserver: + ####################################################### + # Override BaseHTTPRequestHandler method to squelch + # excessive exception logging when client signals + # invalid certificate to the server. This will always + # happen from some clients when using a self-signed + # certificate, so we don't care. + if not hasattr(server.BaseHTTPRequestHandler, "handle_orig"): + server.BaseHTTPRequestHandler.handle_orig = server.BaseHTTPRequestHandler.handle + def handle(self): + try: + self.handle_orig() + except ssl.SSLError: + pass + except Exception as e: + RNS.log("HTTP server exception: "+str(e), RNS.LOG_ERROR) + server.BaseHTTPRequestHandler.handle = handle + ####################################################### + + socketserver.TCPServer.allow_reuse_address = True + class ThreadedHTTPServer(socketserver.ThreadingMixIn, server.HTTPServer): + daemon_threads = True + + with ThreadedHTTPServer(("", port), RequestHandler) as webserver: + from sideband.certgen import ensure_certificate + + ensure_certificate(self.webshare_ssl_key_path, self.webshare_ssl_cert_path) + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ssl_context.load_cert_chain(certfile=self.webshare_ssl_cert_path, keyfile=self.webshare_ssl_key_path) + webserver.socket = ssl_context.wrap_socket(webserver.socket, do_handshake_on_connect=False, server_side=True) + self.webshare_server = webserver webserver.serve_forever() self.webshare_server = None @@ -3780,11 +5242,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) @@ -3820,7 +5290,11 @@ 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" + added_sources = {} sources = self.list_telemetry(after=timebase) only_latest = self.config["telemetry_requests_only_send_latest"] @@ -3828,20 +5302,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) @@ -3849,7 +5326,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, ) @@ -3884,28 +5362,141 @@ 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)+" new 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" 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: + if not self.voice_running: + RNS.log("Starting voice service", RNS.LOG_DEBUG) + self.voice_running = True + self.setstate("voice.running", self.voice_running) + 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 + + 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 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) + if self.telephone: + self.telephone.stop() + del self.telephone + + 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) + self.setstate("voice.incoming_call", display_name) + 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.missed_call", display_name) + 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 +# or addition here may cause Sideband to +# fail starting up or working properly. +# +# If Sideband detects that Reticulum +# aborts at startup, due to an error in +# configuration, any template changes +# will be reset to this default. -rns_config = """ [reticulum] -enable_transport = TRANSPORT_IS_ENABLED -share_instance = Yes -shared_instance_port = 37428 -instance_control_port = 37429 -panic_on_interface_error = No + # Don't change this line, use the UI + # setting for selecting whether RNS + # transport is enabled or disabled + enable_transport = TRANSPORT_IS_ENABLED + # Changing this setting will cause + # Sideband to not work. + share_instance = Yes + + # Changing these options should only + # be done if you know what you're doing. + shared_instance_port = 37428 + instance_control_port = 37429 + panic_on_interface_error = No + +# Logging is controlled by settings +# in the UI, so this section is mostly +# not relevant in Sideband. [logging] -loglevel = 3 + loglevel = 3 +# No additional interfaces are currently +# defined, but you can use this section +# to add additional custom interfaces. +[interfaces] """ diff --git a/sbapp/sideband/mqtt.py b/sbapp/sideband/mqtt.py new file mode 100644 index 0000000..57efe00 --- /dev/null +++ b/sbapp/sideband/mqtt.py @@ -0,0 +1,133 @@ +import RNS +import time +import threading +from collections import deque +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 + + 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.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) + if self.process_queue(): + RNS.log("All MQTT messages processed", RNS.LOG_DEBUG) + + except Exception as e: + RNS.log(f"An error occurred while running MQTT scheduler jobs: {e}", RNS.LOG_ERROR) + RNS.trace_exception(e) + + 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): + 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): + try: + port = int(port) + except: + port = None + + 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): + RNS.log("Disconnecting from MQTT server", RNS.LOG_EXTREME) # TODO: Remove debug + if self.client: + 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.waiting_telemetry.add(mqtt_msg) + + def process_queue(self): + with self.queue_lock: + 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: + 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() + 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) + + self.disconnect() + return True + + def handle(self, context_dest, telemetry): + remote_telemeter = Telemeter.from_packed(telemetry) + read_telemetry = remote_telemeter.read_all() + telemetry_timestamp = read_telemetry["time"]["utc"] + 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() + if topics != None: + for topic in topics: + topic_path = f"{root_path}/{topic}" + data = topics[topic] + self.waiting_msgs.append((topic_path, data)) \ No newline at end of file diff --git a/sbapp/sideband/sense.py b/sbapp/sideband/sense.py index cd6cc1c..0a22767 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,7 +54,10 @@ 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_RNS_TRANSPORT: RNSTransport, Sensor.SID_LXMF_PROPAGATION: LXMFPropagation, + Sensor.SID_CONNECTION_MAP: ConnectionMap} + self.available = { "time": Sensor.SID_TIME, "information": Sensor.SID_INFORMATION, "received": Sensor.SID_RECEIVED, @@ -65,7 +69,14 @@ 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, + "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: + self.names[self.available[name]] = name + self.from_packed = from_packed self.sensors = {} if not self.from_packed: @@ -75,6 +86,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: @@ -103,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: @@ -120,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): @@ -191,6 +217,12 @@ class Sensor(): SID_PROCESSOR = 0x13 SID_RAM = 0x14 SID_NVM = 0x15 + SID_TANK = 0x16 + 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): self._telemeter = None @@ -263,6 +295,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) @@ -314,6 +355,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 @@ -331,6 +385,10 @@ class Information(Sensor): def update_data(self): self.data = {"contents":str(self.contents)} + def set_contents(self, contents): + self.contents = contents + self.update_data() + def pack(self): if self.data == None: return None @@ -355,6 +413,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 @@ -421,6 +492,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 @@ -457,7 +544,7 @@ class Battery(Sensor): if RNS.vendor.platformutils.is_android(): self.battery.get_state() b = self.battery.status - self.data = {"charge_percent": b["percentage"], "charging": b["isCharging"]} + self.data = {"charge_percent": b["percentage"], "charging": b["isCharging"], "temperature": None} elif RNS.vendor.platformutils.is_linux(): if self.battery_node_name: @@ -476,7 +563,7 @@ class Battery(Sensor): is_charging = output['POWER_SUPPLY_STATUS'] == 'Charging' charge_percent = float(output['POWER_SUPPLY_CAPACITY']) - self.data = {"charge_percent": round(charge_percent, 1), "charging": is_charging} + self.data = {"charge_percent": round(charge_percent, 1), "charging": is_charging, "temperature": None} except: self.data = None @@ -486,14 +573,20 @@ class Battery(Sensor): if d == None: return None else: - return [round(d["charge_percent"],1), d["charging"]] + return [round(d["charge_percent"],1), d["charging"], d["temperature"]] def unpack(self, packed): try: if packed == None: return None else: - return {"charge_percent": round(packed[0], 1), "charging": packed[1]} + unpacked = {"charge_percent": round(packed[0], 1), "charging": packed[1]} + if len(packed) > 2: + unpacked["temperature"] = packed[2] + else: + unpacked["temperature"] = None + + return unpacked except: return None @@ -503,6 +596,7 @@ class Battery(Sensor): d = self.data p = d["charge_percent"] + t = d["temperature"] if d["charging"]: charge_string = "charging" else: @@ -511,7 +605,7 @@ class Battery(Sensor): rendered = { "icon": "battery-outline", "name": "Battery", - "values": {"percent": p, "_meta": charge_string}, + "values": {"percent": p, "temperature": t, "_meta": charge_string}, } if d["charging"]: @@ -539,6 +633,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 @@ -591,7 +701,7 @@ class Pressure(Sensor): delta = None if relative_to and "pressure" in relative_to.sensors: rs = relative_to.sensors["pressure"] - if "mbar" in rs.data and rs.data["mbar"] != None: + if rs.data != None and "mbar" in rs.data and rs.data["mbar"] != None: if self.data["mbar"] != None: delta = round(rs.data["mbar"] - self.data["mbar"], 1) @@ -605,6 +715,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 @@ -728,7 +852,8 @@ class Location(Sensor): if "altitude" in self._raw: self.altitude = self._raw["altitude"] if "speed" in self._raw: - self.speed = self._raw["speed"] + # Android GPS reports speed in m/s, convert to km/h + self.speed = self._raw["speed"]*3.6 if self.speed < 0: self.speed = 0 if "bearing" in self._raw: @@ -761,9 +886,9 @@ class Location(Sensor): return [ struct.pack("!i", int(round(d["latitude"], 6)*1e6)), struct.pack("!i", int(round(d["longitude"], 6)*1e6)), - struct.pack("!I", int(round(d["altitude"], 2)*1e2)), + struct.pack("!i", int(round(d["altitude"], 2)*1e2)), struct.pack("!I", int(round(d["speed"], 2)*1e2)), - struct.pack("!I", int(round(d["bearing"], 2)*1e2)), + struct.pack("!i", int(round(d["bearing"], 2)*1e2)), struct.pack("!H", int(round(d["accuracy"], 2)*1e2)), d["last_update"], ] @@ -779,9 +904,9 @@ class Location(Sensor): return { "latitude": struct.unpack("!i", packed[0])[0]/1e6, "longitude": struct.unpack("!i", packed[1])[0]/1e6, - "altitude": struct.unpack("!I", packed[2])[0]/1e2, + "altitude": struct.unpack("!i", packed[2])[0]/1e2, "speed": struct.unpack("!I", packed[3])[0]/1e2, - "bearing": struct.unpack("!I", packed[4])[0]/1e2, + "bearing": struct.unpack("!i", packed[4])[0]/1e2, "accuracy": struct.unpack("!H", packed[5])[0]/1e2, "last_update": packed[6], } @@ -796,7 +921,7 @@ class Location(Sensor): obj_rh = None aamsl = None if self.data["altitude"] != None and self.data["latitude"] != None and self.data["longitude"] != None: - aamsl = self.get_aamsl() + aamsl = max(0, self.get_aamsl()) coords = (self.data["latitude"], self.data["longitude"], aamsl) obj_ath = angle_to_horizon(coords) obj_rh = radio_horizon(aamsl) @@ -825,7 +950,7 @@ class Location(Sensor): s = relative_to.sensors["location"] d = s.data if d != None and "latitude" in d and "longitude" in d and "altitude" in d: - lat = d["latitude"]; lon = d["longitude"]; alt = altitude_to_aamsl(d["altitude"], lat, lon) + lat = d["latitude"]; lon = d["longitude"]; alt = max(0, altitude_to_aamsl(d["altitude"], lat, lon)) if lat != None and lon != None: if alt == None: alt = 0 cs = (slat, slon, salt); cr = (lat, lon, alt) @@ -859,6 +984,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 @@ -915,6 +1079,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 @@ -971,6 +1151,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 @@ -1027,6 +1221,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 @@ -1073,6 +1281,33 @@ class MagneticField(Sensor): except: return None + def render(self, relative_to=None): + if self.data == None: + return None + + rendered = { + "icon": "magnet", + "name": "Magnetic Field", + "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 AmbientLight(Sensor): SID = Sensor.SID_AMBIENT_LIGHT STALE_TIME = 1 @@ -1125,7 +1360,7 @@ class AmbientLight(Sensor): delta = None if relative_to and "ambient_light" in relative_to.sensors: rs = relative_to.sensors["ambient_light"] - if "lux" in rs.data and rs.data["lux"] != None: + if rs.data != None and "lux" in rs.data and rs.data["lux"] != None: if self.data["lux"] != None: delta = round(rs.data["lux"] - self.data["lux"], 2) @@ -1139,6 +1374,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 @@ -1185,6 +1436,33 @@ class Gravity(Sensor): except: return None + def render(self, relative_to=None): + if self.data == None: + return None + + rendered = { + "icon": "arrow-down-thin-circle-outline", + "name": "Gravity", + "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 AngularVelocity(Sensor): SID = Sensor.SID_ANGULAR_VELOCITY STALE_TIME = 1 @@ -1231,6 +1509,33 @@ class AngularVelocity(Sensor): except: return None + def render(self, relative_to=None): + if self.data == None: + return None + + rendered = { + "icon": "orbit", + "name": "Angular Velocity", + "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 Acceleration(Sensor): SID = Sensor.SID_ACCELERATION STALE_TIME = 1 @@ -1277,6 +1582,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 @@ -1322,6 +1654,31 @@ class Proximity(Sensor): except: return None + def render(self, relative_to=None): + if self.data == None: + return None + + rendered = { + "icon": "signal-distance-variant", + "name": "Proximity", + "values": { "triggered": self.data }, + } + 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 @@ -1335,7 +1692,7 @@ class PowerConsumption(Sensor): def teardown_sensor(self): self.data = None - def update_consumer(self, power, type_label=None): + def update_consumer(self, power, type_label=None, custom_icon=None): if type_label == None: type_label = 0x00 elif type(type_label) != str: @@ -1344,7 +1701,7 @@ class PowerConsumption(Sensor): if self.data == None: self.data = {} - self.data[type_label] = power + self.data[type_label] = [power, custom_icon] return True def remove_consumer(self, type_label=None): @@ -1393,7 +1750,7 @@ class PowerConsumption(Sensor): label = "Power consumption" else: label = type_label - consumers.append({"label": label, "w": self.data[type_label]}) + consumers.append({"label": label, "w": self.data[type_label][0], "custom_icon": self.data[type_label][1]}) rendered = { "icon": "power-plug-outline", @@ -1403,6 +1760,23 @@ 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"]: + cl = consumer["label"] + rendered[f"{topic}/{cl}/w"] = consumer["w"] + rendered[f"{topic}/{cl}/icon"] = consumer["custom_icon"] + else: + rendered = None + + return rendered + class PowerProduction(Sensor): SID = Sensor.SID_POWER_PRODUCTION STALE_TIME = 5 @@ -1416,7 +1790,7 @@ class PowerProduction(Sensor): def teardown_sensor(self): self.data = None - def update_producer(self, power, type_label=None): + def update_producer(self, power, type_label=None, custom_icon=None): if type_label == None: type_label = 0x00 elif type(type_label) != str: @@ -1425,7 +1799,7 @@ class PowerProduction(Sensor): if self.data == None: self.data = {} - self.data[type_label] = power + self.data[type_label] = [power, custom_icon] return True def remove_producer(self, type_label=None): @@ -1474,7 +1848,7 @@ class PowerProduction(Sensor): label = "Power Production" else: label = type_label - producers.append({"label": label, "w": self.data[type_label]}) + producers.append({"label": label, "w": self.data[type_label][0], "custom_icon": self.data[type_label][1]}) rendered = { "icon": "lightning-bolt", @@ -1484,12 +1858,1294 @@ class PowerProduction(Sensor): return rendered -# TODO: Implement + 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"]: + pl = producer["label"] + rendered[f"{topic}/{pl}/w"] = producer["w"] + rendered[f"{topic}/{pl}/icon"] = producer["custom_icon"] + else: + rendered = None + + return rendered + class Processor(Sensor): - pass + SID = Sensor.SID_PROCESSOR + 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.data = None + + def update_entry(self, current_load=0, load_avgs=None, clock=None, type_label=None): + if type_label == None: + type_label = 0x00 + elif type(type_label) != str: + return False + + if self.data == None: + self.data = {} + + self.data[type_label] = [current_load, load_avgs, clock] + return True + + def remove_entry(self, type_label=None): + if type_label == None: + type_label = 0x00 + + if type_label in self.data: + self.data.pop(type_label) + return True + + return False + + def update_data(self): + pass + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = [] + for type_label in self.data: + packed.append([type_label, self.data[type_label]]) + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + unpacked = {} + for entry in packed: + unpacked[entry[0]] = entry[1] + return unpacked + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + entries = [] + for type_label in self.data: + if type_label == 0x00: + label = "Storage" + else: + label = type_label + entries.append({ + "label": label, + "current_load": self.data[type_label][0], + "load_avgs": self.data[type_label][1], + "clock": self.data[type_label][2], + }) + + rendered = { + "icon": "chip", + "name": "Processor", + "values": entries, + } + + 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"]: + 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 + + return rendered class RandomAccessMemory(Sensor): - pass + SID = Sensor.SID_RAM + 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.data = None + + def update_entry(self, capacity=0, used=0, type_label=None): + if type_label == None: + type_label = 0x00 + elif type(type_label) != str: + return False + + if self.data == None: + self.data = {} + + self.data[type_label] = [capacity, used] + return True + + def remove_entry(self, type_label=None): + if type_label == None: + type_label = 0x00 + + if type_label in self.data: + self.data.pop(type_label) + return True + + return False + + def update_data(self): + pass + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = [] + for type_label in self.data: + packed.append([type_label, self.data[type_label]]) + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + unpacked = {} + for entry in packed: + unpacked[entry[0]] = entry[1] + return unpacked + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + entries = [] + for type_label in self.data: + if type_label == 0x00: + label = "Storage" + else: + label = type_label + entries.append({ + "label": label, + "capacity": self.data[type_label][0], + "used": self.data[type_label][1], + "free": self.data[type_label][0]-self.data[type_label][1], + "percent": (self.data[type_label][1]/self.data[type_label][0])*100, + }) + + rendered = { + "icon": "memory", + "name": "Random Access Memory", + "values": entries, + } + + 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"]: + 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 + + return rendered class NonVolatileMemory(Sensor): - pass \ No newline at end of file + SID = Sensor.SID_NVM + 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.data = None + + def update_entry(self, capacity=0, used=0, type_label=None): + if type_label == None: + type_label = 0x00 + elif type(type_label) != str: + return False + + if self.data == None: + self.data = {} + + self.data[type_label] = [capacity, used] + return True + + def remove_entry(self, type_label=None): + if type_label == None: + type_label = 0x00 + + if type_label in self.data: + self.data.pop(type_label) + return True + + return False + + def update_data(self): + pass + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = [] + for type_label in self.data: + packed.append([type_label, self.data[type_label]]) + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + unpacked = {} + for entry in packed: + unpacked[entry[0]] = entry[1] + return unpacked + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + entries = [] + for type_label in self.data: + if type_label == 0x00: + label = "Storage" + else: + label = type_label + entries.append({ + "label": label, + "capacity": self.data[type_label][0], + "used": self.data[type_label][1], + "free": self.data[type_label][0]-self.data[type_label][1], + "percent": (self.data[type_label][1]/self.data[type_label][0])*100, + }) + + rendered = { + "icon": "harddisk", + "name": "Non-Volatile Memory", + "values": entries, + } + + 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"]: + 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 + + return rendered + +class Custom(Sensor): + SID = Sensor.SID_CUSTOM + 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.data = None + + def update_entry(self, value=None, type_label=None, custom_icon=None): + if type_label == None: + type_label = 0x00 + elif type(type_label) != str: + return False + + if self.data == None: + self.data = {} + + self.data[type_label] = [value, custom_icon] + return True + + def remove_entry(self, type_label=None): + if type_label == None: + type_label = 0x00 + + if type_label in self.data: + self.data.pop(type_label) + return True + + return False + + def update_data(self): + pass + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = [] + for type_label in self.data: + packed.append([type_label, self.data[type_label]]) + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + unpacked = {} + for entry in packed: + unpacked[entry[0]] = entry[1] + return unpacked + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + entries = [] + for type_label in self.data: + if type_label == 0x00: + label = "Custom" + else: + label = type_label + entries.append({ + "label": label, + "value": self.data[type_label][0], + "custom_icon": self.data[type_label][1], + }) + + rendered = { + "icon": "ruler", + "name": "Custom", + "values": entries, + } + + 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"]: + cl = custom["label"] + rendered[f"{topic}/{cl}/value"] = custom["value"] + rendered[f"{topic}/{cl}/icon"] = custom["custom_icon"] + else: + rendered = None + + return rendered + +class Tank(Sensor): + SID = Sensor.SID_TANK + 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.data = None + + def update_entry(self, capacity=0, level=0, unit=None, type_label=None, custom_icon=None): + if type_label == None: + type_label = 0x00 + elif type(type_label) != str: + return False + + if unit != None and type(unit) != str: + return False + + if self.data == None: + self.data = {} + + self.data[type_label] = [capacity, level, unit, custom_icon] + return True + + def remove_entry(self, type_label=None): + if type_label == None: + type_label = 0x00 + + if type_label in self.data: + self.data.pop(type_label) + return True + + return False + + def update_data(self): + pass + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = [] + for type_label in self.data: + packed.append([type_label, self.data[type_label]]) + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + unpacked = {} + for entry in packed: + unpacked[entry[0]] = entry[1] + return unpacked + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + entries = [] + for type_label in self.data: + if type_label == 0x00: + label = "Tank" + else: + label = type_label + set_unit = self.data[type_label][2] if self.data[type_label][2] != None else "L" + entries.append({ + "label": label, + "unit": set_unit, + "capacity": self.data[type_label][0], + "level": self.data[type_label][1], + "free": self.data[type_label][0]-self.data[type_label][1], + "percent": (self.data[type_label][1]/self.data[type_label][0])*100, + "custom_icon": self.data[type_label][3], + }) + + rendered = { + "icon": "storage-tank", + "name": "Tank", + "values": entries, + } + + 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"]: + 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 + + return rendered + +class Fuel(Sensor): + SID = Sensor.SID_FUEL + 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.data = None + + def update_entry(self, capacity=0, level=0, unit=None, type_label=None, custom_icon=None): + if type_label == None: + type_label = 0x00 + elif type(type_label) != str: + return False + + if unit != None and type(unit) != str: + return False + + if self.data == None: + self.data = {} + + self.data[type_label] = [capacity, level, unit, custom_icon] + return True + + def remove_entry(self, type_label=None): + if type_label == None: + type_label = 0x00 + + if type_label in self.data: + self.data.pop(type_label) + return True + + return False + + def update_data(self): + pass + + def pack(self): + d = self.data + if d == None: + return None + else: + packed = [] + for type_label in self.data: + packed.append([type_label, self.data[type_label]]) + return packed + + def unpack(self, packed): + try: + if packed == None: + return None + else: + unpacked = {} + for entry in packed: + unpacked[entry[0]] = entry[1] + return unpacked + + except: + return None + + def render(self, relative_to=None): + if self.data == None: + return None + + entries = [] + for type_label in self.data: + if type_label == 0x00: + label = "Fuel" + else: + label = type_label + set_unit = self.data[type_label][2] if self.data[type_label][2] != None else "L" + entries.append({ + "label": label, + "unit": set_unit, + "capacity": self.data[type_label][0], + "level": self.data[type_label][1], + "free": self.data[type_label][0]-self.data[type_label][1], + "percent": (self.data[type_label][1]/self.data[type_label][0])*100, + "custom_icon": self.data[type_label][3], + }) + + rendered = { + "icon": "fuel", + "name": "Fuel", + "values": entries, + } + + 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"]: + 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 + + return rendered + +class RNSTransport(Sensor): + SID = Sensor.SID_RNS_TRANSPORT + STALE_TIME = 60 + + 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): + self.update_data() + + def teardown_sensor(self): + self.identity = None + self.data = None + + def update_data(self): + 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: + 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 + + 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": transport_enabled, + "transport_identity": RNS.Transport.identity.hash, + "transport_uptime": transport_uptime, + "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 + 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"], + "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, + "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}/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"], + } + + 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 + STALE_TIME = 300 + + def __init__(self): + self.identity = None + self.lxmd = None + self._last_update = 0 + self._update_interval = 18 + self._update_lock = threading.Lock() + self._running = False + 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) + + 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() + 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): + # 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() + + 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 + 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 + 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(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"], + "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": {} + } + + 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"], + "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"], + } + + values["active_peers"] = active_peers + values["unreachable_peers"] = values["total_peers"] - active_peers + + 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): + 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}/active_peers": v["active_peers"], + f"{topic}/unreachable_peers": v["unreachable_peers"], + 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"] + 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"] = 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 + + 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 + +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) + 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 diff --git a/sbapp/sideband/voice.py b/sbapp/sideband/voice.py new file mode 100644 index 0000000..9e39ced --- /dev/null +++ b/sbapp/sideband/voice.py @@ -0,0 +1,297 @@ +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 +import RNS.vendor.umsgpack as msgpack + +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 + + 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 + self.service = service + self.owner = owner + 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.user_hung_up = False + self.ringtone_path = None + 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 = {} + + 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) + self.telephone.set_allowed(self.__is_allowed) + 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) + + 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 + + @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 + + @property + def active_profile(self): return self.telephone.active_profile + + def start(self): + if not self.should_run: + self.should_run = True + self.run() + + def stop(self): + self.should_run = False + self.telephone.teardown() + self.telephone = None + + 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) + + 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: + 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): + if 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, 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): + 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, 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, 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, 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 + 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): + 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) + 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 + + if call_was_connecting: + self.log_call("outgoing-failure", remote_identity) + 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) + 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) + 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 + while (timeout == None or time.time() timeout: + 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 })) + + @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, 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 }) + 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}) + 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/announces.py b/sbapp/ui/announces.py index bd620d5..52ed461 100644 --- a/sbapp/ui/announces.py +++ b/sbapp/ui/announces.py @@ -18,9 +18,9 @@ from kivy.lang.builder import Builder from kivy.utils import escape_markup if RNS.vendor.platformutils.get_platform() == "android": - from ui.helpers import multilingual_markup + from ui.helpers import multilingual_markup, sig_icon_for_q else: - from .helpers import multilingual_markup + from .helpers import multilingual_markup, sig_icon_for_q if RNS.vendor.platformutils.get_platform() == "android": from ui.helpers import ts_format @@ -89,8 +89,28 @@ class Announces(): for announce in self.announces: context_dest = announce["dest"] ts = announce["time"] - a_data = announce["data"] + a_name = announce["name"] + a_cost = announce["cost"] dest_type = announce["type"] + a_rssi = None + a_snr = None + a_q = None + + link_extras_str = "" + link_extras_full = "" + if "extras" in announce and announce["extras"] != None: + extras = announce["extras"] + if "link_stats" in extras: + link_stats = extras["link_stats"] + if "rssi" in link_stats and "snr" in link_stats and "q" in link_stats: + a_rssi = link_stats["rssi"] + a_snr = link_stats["snr"] + a_q = link_stats["q"] + if a_rssi != None and a_snr != None and a_q != None: + link_extras_str = f" ([b]RSSI[/b] {a_rssi} [b]SNR[/b] {a_snr})" + link_extras_full = f"\n[b]Link Quality[/b] {a_q}%[/b]\n[b]RSSI[/b] {a_rssi}\n[b]SNR[/b] {a_snr}" + + sig_icon = multilingual_markup(sig_icon_for_q(a_q).encode("utf-8")).decode("utf-8") if not context_dest in self.added_item_dests: if self.app.sideband.is_trusted(context_dest): @@ -98,15 +118,25 @@ class Announces(): else: trust_icon = "account-question" - def gen_info(ts, dest, name, dtype): + def gen_info(ts, dest, name, cost, dtype, link_extras): name = multilingual_markup(escape_markup(str(name)).encode("utf-8")).decode("utf-8") + cost = str(cost) def x(sender): yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18)) if dtype == "lxmf.delivery": - ad_text = "[size=22dp]LXMF Peer[/size]\n\nReceived: "+ts+"\nAnnounced Name: "+name+"\nAddress: "+RNS.prettyhexrep(dest) + 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\nReceived: "+ts+"\nAddress: "+RNS.prettyhexrep(dest) + 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, @@ -121,21 +151,24 @@ class Announces(): dialog.open() return x - time_string = time.strftime(ts_format, time.localtime(ts)) + time_string = sig_icon + " " + time.strftime(ts_format, time.localtime(ts)) + link_extras_str + time_string_plain = time.strftime(ts_format, time.localtime(ts)) if dest_type == "lxmf.delivery": disp_name = multilingual_markup(escape_markup(str(self.app.sideband.peer_display_name(context_dest))).encode("utf-8")).decode("utf-8") 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: disp_name = "Unknown Announce" iconl = IconLeftWidget(icon="progress-question") - item = TwoLineAvatarIconListItem(text=time_string, secondary_text=disp_name, on_release=gen_info(time_string, context_dest, a_data, dest_type)) + item = TwoLineAvatarIconListItem(text=time_string, secondary_text=disp_name, on_release=gen_info(time_string_plain, context_dest, a_name, a_cost, dest_type, link_extras_full)) item.add_widget(iconl) item.sb_uid = context_dest item.ts = ts diff --git a/sbapp/ui/conversations.py b/sbapp/ui/conversations.py index 6f7f207..54694a2 100644 --- a/sbapp/ui/conversations.py +++ b/sbapp/ui/conversations.py @@ -3,9 +3,11 @@ 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 from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock @@ -17,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 @@ -35,6 +46,204 @@ class ConvSettings(BoxLayout): trusted = BooleanProperty() telemetry = BooleanProperty() allow_requests = BooleanProperty() + 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): @@ -42,6 +251,7 @@ class Conversations(): self.context_dests = [] self.added_item_dests = [] self.list = None + self.conversation_list = None self.ids = None if not self.app.root.ids.screen_manager.has_screen("conversations_screen"): @@ -51,28 +261,24 @@ 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 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): - # 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) - self.context_dests = self.app.sideband.list_conversations() + view_title = "Conversations" + if self.app.include_conversations: + if self.app.include_objects: + view_title = "Conversations & Objects" + elif self.app.include_objects: + view_title = "Objects" + self.screen.ids.conversations_bar.title = view_title + self.update_widget() self.app.sideband.setstate("app.flags.unread_conversations", False) @@ -80,40 +286,44 @@ 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) - # is_trusted = self.app.sideband.is_trusted(context_dest) is_trusted = conv["trust"] == 1 + appearance_from_all = self.app.sideband.config["display_style_from_all"] trust_icon = "account-question" da = self.app.sideband.DEFAULT_APPEARANCE - if is_trusted and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: + if (is_trusted or appearance_from_all) and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: if unread: trust_icon = "email" else: 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 @@ -122,314 +332,105 @@ class Conversations(): unread = conv["unread"] last_activity = conv["last_activity"] 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) + is_object = self.app.sideband.is_object(context_dest, conv_data=conv) da = self.app.sideband.DEFAULT_APPEARANCE ic_s = 24; ic_p = 14 conv_icon = self.trust_icon(conv) fg = None; bg = None; ti_color = None - if trusted and self.app.sideband.config["display_style_in_contact_list"] and appearance != None and appearance != da: + 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 + if is_object: + def gen_rel_func(): + def x(ws): + self.app.object_details_action(sender=ws, from_objects=True) + return x + + rel_func = gen_rel_func() + else: + rel_func = self.app.conversation_action + iconl = IconLeftWidget( icon=conv_icon, theme_icon_color=ti_color, icon_color=fg, md_bg_color=bg, - on_release=self.app.conversation_action) + on_release=rel_func) + iconl.source_dest = context_dest iconl._default_icon_pad = dp(ic_p) iconl.icon_size = dp(ic_s) + iconl.conv_type = conv["type"] 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]: - RNS.log("Should remove "+RNS.prettyhexrep(w.sb_uid)+" from list") - remove_widgets.append(w) - self.added_item_dests.remove(w.sb_uid) - - for w in remove_widgets: - RNS.log("Removing "+str(w)) - 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: - 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 + 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: - disp_name = self.app.sideband.raw_display_name(dest) - is_trusted = self.app.sideband.is_trusted(dest) - send_telemetry = self.app.sideband.should_send_telemetry(dest) - allow_requests = self.app.sideband.requests_allowed_from(dest) + 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) - if self.app.sideband.config["input_language"] != None: - dialog_content.ids.name_field.font_name = self.app.sideband.config["input_language"] - else: - dialog_content.ids.name_field.font_name = "" + 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 - 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) - - 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) - item.dmenu.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) - - item.dmenu.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) - - item.dmenu.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) - - item.dmenu.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)) - item.dmenu.dismiss() - return x - - item.iconr = IconRightWidget(icon="dots-vertical"); - - if self.conversation_dropdown == None: - dmi_h = 40 - dm_items = [ - { - "viewclass": "OneLineListItem", - "text": "Edit", - "height": dp(dmi_h), - "on_release": gen_edit(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 - - item.dmenu = self.conversation_dropdown - - def callback_factory(ref, dest): - def x(sender): - self.conversation_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) - - 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 update_widget(self): + 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() def get_widget(self): - return self.list + return self.conversation_list conv_screen_kv = """ MDScreen: @@ -440,6 +441,7 @@ MDScreen: MDTopAppBar: title: "Conversations" + id: conversations_bar anchor_title: "left" elevation: 0 left_action_items: @@ -455,23 +457,51 @@ MDScreen: ['account-plus', lambda x: root.app.new_conversation_action(self)], ] - 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" + +: + id: conversations_scrollview + 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" size_hint_y: None - height: dp(250) + height: dp(260) MDTextField: id: n_address_field max_text_length: 32 hint_text: "Address" - helper_text: "Error, check your input" - helper_text_mode: "on_error" + helper_text: "" + helper_text_mode: "on_focus" text: "" font_size: dp(24) @@ -485,7 +515,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" @@ -496,6 +526,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" @@ -561,6 +606,36 @@ Builder.load_string(""" pos_hint: {"center_y": 0.43} active: root.allow_requests + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(8),0] + height: dp(32) + MDLabel: + id: ptt_enabled_label + text: "PTT Enabled" + font_style: "H6" + + MDSwitch: + id: ptt_enabled_switch + pos_hint: {"center_y": 0.43} + active: root.ptt_enabled + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(8),0] + height: dp(32) + MDLabel: + id: is_object_label + text: "Is Object" + font_style: "H6" + + MDSwitch: + id: is_object_switch + pos_hint: {"center_y": 0.43} + active: root.is_object + orientation: "vertical" spacing: "24dp" @@ -568,6 +643,10 @@ Builder.load_string(""" padding: [0, 0, 0, dp(16)] height: self.minimum_height+dp(24) + MDLabel: + id: node_info + text: "Unknown propagation node" + MDProgressBar: id: sync_progress type: "determinate" @@ -575,7 +654,6 @@ Builder.load_string(""" MDLabel: id: sync_status - hint_text: "Name" text: "Initiating sync..." 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/hardware.py b/sbapp/ui/hardware.py new file mode 100644 index 0000000..cf0b5c8 --- /dev/null +++ b/sbapp/ui/hardware.py @@ -0,0 +1,1690 @@ +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(): + 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/helpers.py b/sbapp/ui/helpers.py index f6a5f12..3f2f3fc 100644 --- a/sbapp/ui/helpers.py +++ b/sbapp/ui/helpers.py @@ -4,7 +4,9 @@ from kivy.uix.screenmanager import ScreenManager, Screen from kivymd.theming import ThemableBehavior from kivymd.uix.list import OneLineIconListItem, MDList, IconLeftWidget, IconRightWidget 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" @@ -13,14 +15,35 @@ def mdc(color, hue=None): hue = "400" return get_color_from_hex(colors[color][hue]) +color_playing = "Amber" color_received = "LightGreen" color_delivered = "Blue" color_paper = "Indigo" color_propagated = "Indigo" color_failed = "Red" +color_cancelled = "Red" color_unknown = "Gray" intensity_msgs_dark = "800" intensity_msgs_light = "500" +intensity_play_dark = "600" +intensity_play_light = "300" +intensity_cancelled = "900" + + +intensity_msgs_dark_alt = "800" +intensity_msgs_light_alt = "400" +intensity_delivered_alt_dark = "800" +color_received_alt = "BlueGray" +color_received_alt_light = "BlueGray" +color_delivered_alt = "Indigo" +color_propagated_alt = "DeepPurple" +color_paper_alt = "DeepPurple" +color_playing_alt = "Amber" +color_failed_alt = "Red" +color_unknown_alt = "Gray" +color_cancelled_alt = "Red" + +dark_theme_text_color = "ddd" class ContentNavigationDrawer(Screen): pass @@ -34,14 +57,20 @@ class IconListItem(OneLineIconListItem): def is_emoji(unicode_character): return unicode_character in emoji_lookup -def multilingual_markup(data): - # TODO: Remove - # import time - # ts = time.time() +def strip_emojis(str_input): + output = "" + for cp in str_input: + if not is_emoji(cp): + output += cp + return output +def multilingual_markup(data): do = "" rfont = "default" ds = data.decode("utf-8") + di = 0 + persistent_regions = [(m.start(), m.end()) for m in re.finditer("(?s)\[font=(?:nf|term)\].*?\[/font\]", ds)] + for cp in ds: match = False switch = False @@ -53,6 +82,10 @@ def multilingual_markup(data): switch = True rfont = "emoji" + in_persistent = False + if any(x[0] < di and x[1] > di for x in persistent_regions): + in_persistent = True + if not match: for range_start in codepoint_map: range_end = codepoint_map[range_start][0] @@ -61,8 +94,9 @@ def multilingual_markup(data): if range_end >= ord(cp) >= range_start: match = True if rfont != mapped_font: - rfont = mapped_font - switch = True + if not in_persistent: + rfont = mapped_font + switch = True break if (not match) and rfont != "default": @@ -76,15 +110,32 @@ def multilingual_markup(data): do += "[font="+str(rfont)+"]" do += cp + di += 1 if rfont != "default": do += "[/font]" - # TODO: Remove - # print(do+"\n\n"+str(time.time()-ts)) - return do.encode("utf-8") +def sig_icon_for_q(q): + if q == None: + return "є░┤╜" + elif q > 90: + return "є░г║" + elif q > 70: + return "є░г╕" + elif q > 50: + return "є░г╢" + elif q > 20: + return "є░г┤" + elif q > 5: + return "є░г╛" + else: + return "є░г╜" + +persistent_fonts = ["nf", "term"] +nf_mapped = "nf" + codepoint_map = { 0x0590: [0x05ff, "hebrew"], 0x2e3a: [0x2e3b, "chinese"], @@ -117,7 +168,138 @@ codepoint_map = { 0xa960: [0xa97f, "korean"], 0xac00: [0xd7af, "korean"], 0xd7b0: [0xd7ff, "korean"], - 0x0900: [0x097f, "combined"], # Devangari + 0x0900: [0x097f, "combined"], # Devanagari + 0xe5fa: [0xe6b7, nf_mapped], # Seti-UI + Custom + 0xe700: [0xe8ef, nf_mapped], # Devicons + 0xed00: [0xf2ff, nf_mapped], # Font Awesome + 0xe200: [0xe2a9, nf_mapped], # Font Awesome Extension + 0xf0001: [0xf1af0, nf_mapped], # Material Design Icons + 0xe300: [0xe3e3, nf_mapped], # Weather + 0xf400: [0xf533, nf_mapped], # Octicons + 0x2665: [0x2665, nf_mapped], # Octicons + 0x26a1: [0x26a1, nf_mapped], # Octicons + 0xe0a0: [0xe0a2, nf_mapped], # Powerline Symbols + 0xe0b0: [0xe0b3, nf_mapped], # Powerline Symbols + 0xe0a3: [0xe0a3, nf_mapped], # Powerline Extra Symbols + 0xe0b4: [0xe0c8, nf_mapped], # Powerline Extra Symbols + 0xe0ca: [0xe0ca, nf_mapped], # Powerline Extra Symbols + 0xe0cc: [0xe0d7, nf_mapped], # Powerline Extra Symbols + 0x23fb: [0x23fe, nf_mapped], # IEC Power Symbols + 0x2b58: [0x2b58, nf_mapped], # IEC Power Symbols + 0xf300: [0xf381, nf_mapped], # Font logos + 0xe000: [0xe00a, nf_mapped], # Pomicons + 0xea60: [0xec1e, nf_mapped], # Codicons + 0x276c: [0x2771, nf_mapped], # Heavy Angle Brackets + 0x2500: [0x259f, nf_mapped], # Box Drawing + 0xee00: [0xee0b, nf_mapped], # Progress } -emoji_lookup = ['тМЪ','тМЫ','','тПк','тПл','тПм','тП░','тП│','тЧ╜','тЧ╛','тШФ','тШХ','тЩИ','тЩЙ','тЩК','тЩЛ','тЩМ','тЩН','тЩО','тЩП','тЩР','тЩС','тЩТ','тЩУ','тЩ┐','тЪУ','тЪб','тЪк','тЪл','тЪ╜','тЪ╛','тЫД','тЫЕ','тЫО','тЫФ','тЫк','тЫ▓','тЫ│','тЫ╡','тЫ║','тЫ╜','тЬЕ','тЬК','тЬЛ','тЬи','тЭМ','тЭО','тЭУ','тЭФ','тЭХ','тЭЧ','тЮХ','тЮЦ','тЮЧ','тЮ░','тЮ┐','тмЫ','тмЬ','тнР','тнХ','ЁЯАД','ЁЯГП','ЁЯЖО','ЁЯЖС','ЁЯЖТ','ЁЯЖУ','ЁЯЖФ','ЁЯЖХ','ЁЯЖЦ','ЁЯЖЧ','ЁЯЖШ','ЁЯЖЩ','ЁЯЖЪ','ЁЯИБ','ЁЯИЪ','ЁЯИп','ЁЯИ▓','ЁЯИ│','ЁЯИ┤','ЁЯИ╡','ЁЯИ╢','ЁЯИ╕','ЁЯИ╣','ЁЯИ║','ЁЯЙР','ЁЯЙС','ЁЯМА','ЁЯМБ','ЁЯМВ','ЁЯМГ','ЁЯМД','ЁЯМЕ','ЁЯМЖ','ЁЯМЗ','ЁЯМИ','ЁЯМЙ','ЁЯМК','ЁЯМЛ','ЁЯММ','ЁЯМН','ЁЯМО','ЁЯМП','ЁЯМР','ЁЯМС','ЁЯМТ','ЁЯМУ','ЁЯМФ','ЁЯМХ','ЁЯМЦ','ЁЯМЧ','ЁЯМШ','ЁЯМЩ','ЁЯМЪ','ЁЯМЫ','ЁЯМЬ','ЁЯМЭ','ЁЯМЮ','ЁЯМЯ','ЁЯМа','ЁЯМн','ЁЯМо','ЁЯМп','ЁЯМ░','ЁЯМ▒','ЁЯМ▓','ЁЯМ│','ЁЯМ┤','ЁЯМ╡','ЁЯМ╖','ЁЯМ╕','ЁЯМ╣','ЁЯМ║','ЁЯМ╗','ЁЯМ╝','ЁЯМ╜','ЁЯМ╛','ЁЯМ┐','ЁЯНА','ЁЯНБ','ЁЯНВ','ЁЯНГ','ЁЯНД','ЁЯНЕ','ЁЯНЖ','ЁЯНЗ','ЁЯНИ','ЁЯНЙ','ЁЯНК','ЁЯНЛ','ЁЯНМ','ЁЯНН','ЁЯНО','ЁЯНП','ЁЯНР','ЁЯНС','ЁЯНТ','ЁЯНУ','ЁЯНФ','ЁЯНХ','ЁЯНЦ','ЁЯНЧ','ЁЯНШ','ЁЯНЩ','ЁЯНЪ','ЁЯНЫ','ЁЯНЬ','ЁЯНЭ','ЁЯНЮ','ЁЯНЯ','ЁЯНа','ЁЯНб','ЁЯНв','ЁЯНг','ЁЯНд','ЁЯНе','ЁЯНж','ЁЯНз','ЁЯНи','ЁЯНй','ЁЯНк','ЁЯНл','ЁЯНм','ЁЯНн','ЁЯНо','ЁЯНп','ЁЯН░','ЁЯН▒','ЁЯН▓','ЁЯН│','ЁЯН┤','ЁЯН╡','ЁЯН╢','ЁЯН╖','ЁЯН╕','ЁЯН╣','ЁЯН║','ЁЯН╗','ЁЯН╝','ЁЯН╛','ЁЯН┐','ЁЯОА','ЁЯОБ','ЁЯОВ','ЁЯОГ','ЁЯОД','ЁЯОЕ','ЁЯОЖ','ЁЯОЗ','ЁЯОИ','ЁЯОЙ','ЁЯОК','ЁЯОЛ','ЁЯОМ','ЁЯОН','ЁЯОО','ЁЯОП','ЁЯОР','ЁЯОС','ЁЯОТ','ЁЯОУ','ЁЯОа','ЁЯОб','ЁЯОв','ЁЯОг','ЁЯОд','ЁЯОе','ЁЯОж','ЁЯОз','ЁЯОи','ЁЯОй','ЁЯОк','ЁЯОл','ЁЯОм','ЁЯОн','ЁЯОо','ЁЯОп','ЁЯО░','ЁЯО▒','ЁЯО▓','ЁЯО│','ЁЯО┤','ЁЯО╡','ЁЯО╢','ЁЯО╖','ЁЯО╕','ЁЯО╣','ЁЯО║','ЁЯО╗','ЁЯО╝','ЁЯО╜','ЁЯО╛','ЁЯО┐','ЁЯПА','ЁЯПБ','ЁЯПВ','ЁЯПГ','ЁЯПД','ЁЯПЕ','ЁЯПЖ','ЁЯПЗ','ЁЯПИ','ЁЯПЙ','ЁЯПК','ЁЯПП','ЁЯПР','ЁЯПС','ЁЯПТ','ЁЯПУ','ЁЯПа','ЁЯПб','ЁЯПв','ЁЯПг','ЁЯПд','ЁЯПе','ЁЯПж','ЁЯПз','ЁЯПи','ЁЯПй','ЁЯПк','ЁЯПл','ЁЯПм','ЁЯПн','ЁЯПо','ЁЯПп','ЁЯП░','ЁЯП┤','ЁЯП╕','ЁЯП╣','ЁЯП║','ЁЯП╗','ЁЯП╝','ЁЯП╜','ЁЯП╛','ЁЯП┐','ЁЯРА','ЁЯРБ','ЁЯРВ','ЁЯРГ','ЁЯРД','ЁЯРЕ','ЁЯРЖ','ЁЯРЗ','ЁЯРИ','ЁЯРЙ','ЁЯРК','ЁЯРЛ','ЁЯРМ','ЁЯРН','ЁЯРО','ЁЯРП','ЁЯРР','ЁЯРС','ЁЯРТ','ЁЯРУ','ЁЯРФ','ЁЯРХ','ЁЯРЦ','ЁЯРЧ','ЁЯРШ','ЁЯРЩ','ЁЯРЪ','ЁЯРЫ','ЁЯРЬ','ЁЯРЭ','ЁЯРЮ','ЁЯРЯ','ЁЯРа','ЁЯРб','ЁЯРв','ЁЯРг','ЁЯРд','ЁЯРе','ЁЯРж','ЁЯРз','ЁЯРи','ЁЯРй','ЁЯРк','ЁЯРл','ЁЯРм','ЁЯРн','ЁЯРо','ЁЯРп','ЁЯР░','ЁЯР▒','ЁЯР▓','ЁЯР│','ЁЯР┤','ЁЯР╡','ЁЯР╢','ЁЯР╖','ЁЯР╕','ЁЯР╣','ЁЯР║','ЁЯР╗','ЁЯР╝','ЁЯР╜','ЁЯР╛','ЁЯСА','ЁЯСВ','ЁЯСГ','ЁЯСД','ЁЯСЕ','ЁЯСЖ','ЁЯСЗ','ЁЯСИ','ЁЯСЙ','ЁЯСК','ЁЯСЛ','ЁЯСМ','ЁЯСН','ЁЯСО','ЁЯСП','ЁЯСР','ЁЯСС','ЁЯСТ','ЁЯСУ','ЁЯСФ','ЁЯСХ','ЁЯСЦ','ЁЯСЧ','ЁЯСШ','ЁЯСЩ','ЁЯСЪ','ЁЯСЫ','ЁЯСЬ','ЁЯСЭ','ЁЯСЮ','ЁЯСЯ','ЁЯСа','ЁЯСб','ЁЯСв','ЁЯСг','ЁЯСд','ЁЯСе','ЁЯСж','ЁЯСз','ЁЯСи','ЁЯСй','ЁЯСк','ЁЯСл','ЁЯСм','ЁЯСн','ЁЯСо','ЁЯСп','ЁЯС░','ЁЯС▒','ЁЯС▓','ЁЯС│','ЁЯС┤','ЁЯС╡','ЁЯС╢','ЁЯС╖','ЁЯС╕','ЁЯС╣','ЁЯС║','ЁЯС╗','ЁЯС╝','ЁЯС╜','ЁЯС╛','ЁЯС┐','ЁЯТА','ЁЯТБ','ЁЯТВ','ЁЯТГ','ЁЯТД','ЁЯТЕ','ЁЯТЖ','ЁЯТЗ','ЁЯТИ','ЁЯТЙ','ЁЯТК','ЁЯТЛ','ЁЯТМ','ЁЯТН','ЁЯТО','ЁЯТП','ЁЯТР','ЁЯТС','ЁЯТТ','ЁЯТУ','ЁЯТФ','ЁЯТХ','ЁЯТЦ','ЁЯТЧ','ЁЯТШ','ЁЯТЩ','ЁЯТЪ','ЁЯТЫ','ЁЯТЬ','ЁЯТЭ','ЁЯТЮ','ЁЯТЯ','ЁЯТа','ЁЯТб','ЁЯТв','ЁЯТг','ЁЯТд','ЁЯТе','ЁЯТж','ЁЯТз','ЁЯТи','ЁЯТй','ЁЯТк','ЁЯТл','ЁЯТм','ЁЯТн','ЁЯТо','ЁЯТп','ЁЯТ░','ЁЯТ▒','ЁЯТ▓','ЁЯТ│','ЁЯТ┤','ЁЯТ╡','ЁЯТ╢','ЁЯТ╖','ЁЯТ╕','ЁЯТ╣','ЁЯТ║','ЁЯТ╗','ЁЯТ╝','ЁЯТ╜','ЁЯТ╛','ЁЯТ┐','ЁЯУА','ЁЯУБ','ЁЯУВ','ЁЯУГ','ЁЯУД','ЁЯУЕ','ЁЯУЖ','ЁЯУЗ','ЁЯУИ','ЁЯУЙ','ЁЯУК','ЁЯУЛ','ЁЯУМ','ЁЯУН','ЁЯУО','ЁЯУП','ЁЯУР','ЁЯУС','ЁЯУТ','ЁЯУУ','ЁЯУФ','ЁЯУХ','ЁЯУЦ','ЁЯУЧ','ЁЯУШ','ЁЯУЩ','ЁЯУЪ','ЁЯУЫ','ЁЯУЬ','ЁЯУЭ','ЁЯУЮ','ЁЯУЯ','ЁЯУа','ЁЯУб','ЁЯУв','ЁЯУг','ЁЯУд','ЁЯУе','ЁЯУж','ЁЯУз','ЁЯУи','ЁЯУй','ЁЯУк','ЁЯУл','ЁЯУм','ЁЯУн','ЁЯУо','ЁЯУп','ЁЯУ░','ЁЯУ▒','ЁЯУ▓','ЁЯУ│','ЁЯУ┤','ЁЯУ╡','ЁЯУ╢','ЁЯУ╖','ЁЯУ╕','ЁЯУ╣','ЁЯУ║','ЁЯУ╗','ЁЯУ╝','ЁЯУ┐','ЁЯФА','ЁЯФБ','ЁЯФВ','ЁЯФГ','ЁЯФД','ЁЯФЕ','ЁЯФЖ','ЁЯФЗ','ЁЯФИ','ЁЯФЙ','ЁЯФК','ЁЯФЛ','ЁЯФМ','ЁЯФН','ЁЯФО','ЁЯФП','ЁЯФР','ЁЯФС','ЁЯФТ','ЁЯФУ','ЁЯФФ','ЁЯФХ','ЁЯФЦ','ЁЯФЧ','ЁЯФШ','ЁЯФЩ','ЁЯФЪ','ЁЯФЫ','ЁЯФЬ','ЁЯФЭ','ЁЯФЮ','ЁЯФЯ','ЁЯФа','ЁЯФб','ЁЯФв','ЁЯФг','ЁЯФд','ЁЯФе','ЁЯФж','ЁЯФз','ЁЯФи','ЁЯФй','ЁЯФк','ЁЯФл','ЁЯФм','ЁЯФн','ЁЯФо','ЁЯФп','ЁЯФ░','ЁЯФ▒','ЁЯФ▓','ЁЯФ│','ЁЯФ┤','ЁЯФ╡','ЁЯФ╢','ЁЯФ╖','ЁЯФ╕','ЁЯФ╣','ЁЯФ║','ЁЯФ╗','ЁЯФ╝','ЁЯФ╜','ЁЯХЛ','ЁЯХМ','ЁЯХН','ЁЯХО','ЁЯХР','ЁЯХС','ЁЯХТ','ЁЯХУ','ЁЯХФ','ЁЯХХ','ЁЯХЦ','ЁЯХЧ','ЁЯХШ','ЁЯХЩ','ЁЯХЪ','ЁЯХЫ','ЁЯХЬ','ЁЯХЭ','ЁЯХЮ','ЁЯХЯ','ЁЯХа','ЁЯХб','ЁЯХв','ЁЯХг','ЁЯХд','ЁЯХе','ЁЯХж','ЁЯХз','ЁЯЦХ','ЁЯЦЦ','ЁЯЧ╗','ЁЯЧ╝','ЁЯЧ╜','ЁЯЧ╛','ЁЯЧ┐','ЁЯША','ЁЯШБ','ЁЯШВ','ЁЯШГ','ЁЯШД','ЁЯШЕ','ЁЯШЖ','ЁЯШЗ','ЁЯШИ','ЁЯШЙ','ЁЯШК','ЁЯШЛ','ЁЯШМ','ЁЯШН','ЁЯШО','ЁЯШП','ЁЯШР','ЁЯШС','ЁЯШТ','ЁЯШУ','ЁЯШФ','ЁЯШХ','ЁЯШЦ','ЁЯШЧ','ЁЯШШ','ЁЯШЩ','ЁЯШЪ','ЁЯШЫ','ЁЯШЬ','ЁЯШЭ','ЁЯШЮ','ЁЯШЯ','ЁЯШа','ЁЯШб','ЁЯШв','ЁЯШг','ЁЯШд','ЁЯШе','ЁЯШж','ЁЯШз','ЁЯШи','ЁЯШй','ЁЯШк','ЁЯШл','ЁЯШм','ЁЯШн','ЁЯШо','ЁЯШп','ЁЯШ░','ЁЯШ▒','ЁЯШ▓','ЁЯШ│','ЁЯШ┤','ЁЯШ╡','ЁЯШ╢','ЁЯШ╖','ЁЯШ╕','ЁЯШ╣','ЁЯШ║','ЁЯШ╗','ЁЯШ╝','ЁЯШ╜','ЁЯШ╛','ЁЯШ┐','ЁЯЩА','ЁЯЩБ','ЁЯЩВ','ЁЯЩГ','ЁЯЩД','ЁЯЩЕ','ЁЯЩЖ','ЁЯЩЗ','ЁЯЩИ','ЁЯЩЙ','ЁЯЩК','ЁЯЩЛ','ЁЯЩМ','ЁЯЩН','ЁЯЩО','ЁЯЩП','ЁЯЪА','ЁЯЪБ','ЁЯЪВ','ЁЯЪГ','ЁЯЪД','ЁЯЪЕ','ЁЯЪЖ','ЁЯЪЗ','ЁЯЪИ','ЁЯЪЙ','ЁЯЪК','ЁЯЪЛ','ЁЯЪМ','ЁЯЪН','ЁЯЪО','ЁЯЪП','ЁЯЪР','ЁЯЪС','ЁЯЪТ','ЁЯЪУ','ЁЯЪФ','ЁЯЪХ','ЁЯЪЦ','ЁЯЪЧ','ЁЯЪШ','ЁЯЪЩ','ЁЯЪЪ','ЁЯЪЫ','ЁЯЪЬ','ЁЯЪЭ','ЁЯЪЮ','ЁЯЪЯ','ЁЯЪа','ЁЯЪб','ЁЯЪв','ЁЯЪг','ЁЯЪд','ЁЯЪе','ЁЯЪж','ЁЯЪз','ЁЯЪи','ЁЯЪй','ЁЯЪк','ЁЯЪл','ЁЯЪм','ЁЯЪн','ЁЯЪо','ЁЯЪп','ЁЯЪ░','ЁЯЪ▒','ЁЯЪ▓','ЁЯЪ│','ЁЯЪ┤','ЁЯЪ╡','ЁЯЪ╢','ЁЯЪ╖','ЁЯЪ╕','ЁЯЪ╣','ЁЯЪ║','ЁЯЪ╗','ЁЯЪ╝','ЁЯЪ╜','ЁЯЪ╛','ЁЯЪ┐','ЁЯЫА','ЁЯЫБ','ЁЯЫВ','ЁЯЫГ','ЁЯЫД','ЁЯЫЕ','ЁЯЫМ','ЁЯЫР','ЁЯЫл','ЁЯЫм','ЁЯдР','ЁЯдС','ЁЯдТ','ЁЯдУ','ЁЯдФ','ЁЯдХ','ЁЯдЦ','ЁЯдЧ','ЁЯдШ','ЁЯжА','ЁЯжБ','ЁЯжВ','ЁЯжГ','ЁЯжД','ЁЯзА','ЁЯЗжЁЯЗи','ЁЯЗжЁЯЗй','ЁЯЗжЁЯЗк','ЁЯЗжЁЯЗл','ЁЯЗжЁЯЗм','ЁЯЗжЁЯЗо','ЁЯЗжЁЯЗ▒','ЁЯЗжЁЯЗ▓','ЁЯЗжЁЯЗ┤','ЁЯЗжЁЯЗ╢','ЁЯЗжЁЯЗ╖','ЁЯЗжЁЯЗ╕','ЁЯЗжЁЯЗ╣','ЁЯЗжЁЯЗ║','ЁЯЗжЁЯЗ╝','ЁЯЗжЁЯЗ╜','ЁЯЗжЁЯЗ┐','ЁЯЗзЁЯЗж','ЁЯЗзЁЯЗз','ЁЯЗзЁЯЗй','ЁЯЗзЁЯЗк','ЁЯЗзЁЯЗл','ЁЯЗзЁЯЗм','ЁЯЗзЁЯЗн','ЁЯЗзЁЯЗо','ЁЯЗзЁЯЗп','ЁЯЗзЁЯЗ▒','ЁЯЗзЁЯЗ▓','ЁЯЗзЁЯЗ│','ЁЯЗзЁЯЗ┤','ЁЯЗзЁЯЗ╢','ЁЯЗзЁЯЗ╖','ЁЯЗзЁЯЗ╕','ЁЯЗзЁЯЗ╣','ЁЯЗзЁЯЗ╗','ЁЯЗзЁЯЗ╝','ЁЯЗзЁЯЗ╛','ЁЯЗзЁЯЗ┐','ЁЯЗиЁЯЗж','ЁЯЗиЁЯЗи','ЁЯЗиЁЯЗй','ЁЯЗиЁЯЗл','ЁЯЗиЁЯЗм','ЁЯЗиЁЯЗн','ЁЯЗиЁЯЗо','ЁЯЗиЁЯЗ░','ЁЯЗиЁЯЗ▒','ЁЯЗиЁЯЗ▓','ЁЯЗиЁЯЗ│','ЁЯЗиЁЯЗ┤','ЁЯЗиЁЯЗ╡','ЁЯЗиЁЯЗ╖','ЁЯЗиЁЯЗ║','ЁЯЗиЁЯЗ╗','ЁЯЗиЁЯЗ╝','ЁЯЗиЁЯЗ╜','ЁЯЗиЁЯЗ╛','ЁЯЗиЁЯЗ┐','ЁЯЗйЁЯЗк','ЁЯЗйЁЯЗм','ЁЯЗйЁЯЗп','ЁЯЗйЁЯЗ░','ЁЯЗйЁЯЗ▓','ЁЯЗйЁЯЗ┤','ЁЯЗйЁЯЗ┐','ЁЯЗкЁЯЗж','ЁЯЗкЁЯЗи','ЁЯЗкЁЯЗк','ЁЯЗкЁЯЗм','ЁЯЗкЁЯЗн','ЁЯЗкЁЯЗ╖','ЁЯЗкЁЯЗ╕','ЁЯЗкЁЯЗ╣','ЁЯЗкЁЯЗ║','ЁЯЗлЁЯЗо','ЁЯЗлЁЯЗп','ЁЯЗлЁЯЗ░','ЁЯЗлЁЯЗ▓','ЁЯЗлЁЯЗ┤','ЁЯЗлЁЯЗ╖','ЁЯЗмЁЯЗж','ЁЯЗмЁЯЗз','ЁЯЗмЁЯЗй','ЁЯЗмЁЯЗк','ЁЯЗмЁЯЗл','ЁЯЗмЁЯЗм','ЁЯЗмЁЯЗн','ЁЯЗмЁЯЗо','ЁЯЗмЁЯЗ▒','ЁЯЗмЁЯЗ▓','ЁЯЗмЁЯЗ│','ЁЯЗмЁЯЗ╡','ЁЯЗмЁЯЗ╢','ЁЯЗмЁЯЗ╖','ЁЯЗмЁЯЗ╕','ЁЯЗмЁЯЗ╣','ЁЯЗмЁЯЗ║','ЁЯЗмЁЯЗ╝','ЁЯЗмЁЯЗ╛','ЁЯЗнЁЯЗ░','ЁЯЗнЁЯЗ▓','ЁЯЗнЁЯЗ│','ЁЯЗнЁЯЗ╖','ЁЯЗнЁЯЗ╣','ЁЯЗнЁЯЗ║','ЁЯЗоЁЯЗи','ЁЯЗоЁЯЗй','ЁЯЗоЁЯЗк','ЁЯЗоЁЯЗ▒','ЁЯЗоЁЯЗ▓','ЁЯЗоЁЯЗ│','ЁЯЗоЁЯЗ┤','ЁЯЗоЁЯЗ╢','ЁЯЗоЁЯЗ╖','ЁЯЗоЁЯЗ╕','ЁЯЗоЁЯЗ╣','ЁЯЗпЁЯЗк','ЁЯЗпЁЯЗ▓','ЁЯЗпЁЯЗ┤','ЁЯЗпЁЯЗ╡','ЁЯЗ░ЁЯЗк','ЁЯЗ░ЁЯЗм','ЁЯЗ░ЁЯЗн','ЁЯЗ░ЁЯЗо','ЁЯЗ░ЁЯЗ▓','ЁЯЗ░ЁЯЗ│','ЁЯЗ░ЁЯЗ╡','ЁЯЗ░ЁЯЗ╖','ЁЯЗ░ЁЯЗ╝','ЁЯЗ░ЁЯЗ╛','ЁЯЗ░ЁЯЗ┐','ЁЯЗ▒ЁЯЗж','ЁЯЗ▒ЁЯЗз','ЁЯЗ▒ЁЯЗи','ЁЯЗ▒ЁЯЗо','ЁЯЗ▒ЁЯЗ░','ЁЯЗ▒ЁЯЗ╖','ЁЯЗ▒ЁЯЗ╕','ЁЯЗ▒ЁЯЗ╣','ЁЯЗ▒ЁЯЗ║','ЁЯЗ▒ЁЯЗ╗','ЁЯЗ▒ЁЯЗ╛','ЁЯЗ▓ЁЯЗж','ЁЯЗ▓ЁЯЗи','ЁЯЗ▓ЁЯЗй','ЁЯЗ▓ЁЯЗк','ЁЯЗ▓ЁЯЗл','ЁЯЗ▓ЁЯЗм','ЁЯЗ▓ЁЯЗн','ЁЯЗ▓ЁЯЗ░','ЁЯЗ▓ЁЯЗ▒','ЁЯЗ▓ЁЯЗ▓','ЁЯЗ▓ЁЯЗ│','ЁЯЗ▓ЁЯЗ┤','ЁЯЗ▓ЁЯЗ╡','ЁЯЗ▓ЁЯЗ╢','ЁЯЗ▓ЁЯЗ╖','ЁЯЗ▓ЁЯЗ╕','ЁЯЗ▓ЁЯЗ╣','ЁЯЗ▓ЁЯЗ║','ЁЯЗ▓ЁЯЗ╗','ЁЯЗ▓ЁЯЗ╝','ЁЯЗ▓ЁЯЗ╜','ЁЯЗ▓ЁЯЗ╛','ЁЯЗ▓ЁЯЗ┐','ЁЯЗ│ЁЯЗж','ЁЯЗ│ЁЯЗи','ЁЯЗ│ЁЯЗк','ЁЯЗ│ЁЯЗл','ЁЯЗ│ЁЯЗм','ЁЯЗ│ЁЯЗо','ЁЯЗ│ЁЯЗ▒','ЁЯЗ│ЁЯЗ┤','ЁЯЗ│ЁЯЗ╡','ЁЯЗ│ЁЯЗ╖','ЁЯЗ│ЁЯЗ║','ЁЯЗ│ЁЯЗ┐','ЁЯЗ┤ЁЯЗ▓','ЁЯЗ╡ЁЯЗж','ЁЯЗ╡ЁЯЗк','ЁЯЗ╡ЁЯЗл','ЁЯЗ╡ЁЯЗм','ЁЯЗ╡ЁЯЗн','ЁЯЗ╡ЁЯЗ░','ЁЯЗ╡ЁЯЗ▒','ЁЯЗ╡ЁЯЗ▓','ЁЯЗ╡ЁЯЗ│','ЁЯЗ╡ЁЯЗ╖','ЁЯЗ╡ЁЯЗ╕','ЁЯЗ╡ЁЯЗ╣','ЁЯЗ╡ЁЯЗ╝','ЁЯЗ╡ЁЯЗ╛','ЁЯЗ╢ЁЯЗж','ЁЯЗ╖ЁЯЗк','ЁЯЗ╖ЁЯЗ┤','ЁЯЗ╖ЁЯЗ╕','ЁЯЗ╖ЁЯЗ║','ЁЯЗ╖ЁЯЗ╝','ЁЯЗ╕ЁЯЗж','ЁЯЗ╕ЁЯЗз','ЁЯЗ╕ЁЯЗи','ЁЯЗ╕ЁЯЗй','ЁЯЗ╕ЁЯЗк','ЁЯЗ╕ЁЯЗм','ЁЯЗ╕ЁЯЗн','ЁЯЗ╕ЁЯЗо','ЁЯЗ╕ЁЯЗп','ЁЯЗ╕ЁЯЗ░','ЁЯЗ╕ЁЯЗ▒','ЁЯЗ╕ЁЯЗ▓','ЁЯЗ╕ЁЯЗ│','ЁЯЗ╕ЁЯЗ┤','ЁЯЗ╕ЁЯЗ╖','ЁЯЗ╕ЁЯЗ╕','ЁЯЗ╕ЁЯЗ╣','ЁЯЗ╕ЁЯЗ╗','ЁЯЗ╕ЁЯЗ╜','ЁЯЗ╕ЁЯЗ╛','ЁЯЗ╕ЁЯЗ┐','ЁЯЗ╣ЁЯЗж','ЁЯЗ╣ЁЯЗи','ЁЯЗ╣ЁЯЗй','ЁЯЗ╣ЁЯЗл','ЁЯЗ╣ЁЯЗм','ЁЯЗ╣ЁЯЗн','ЁЯЗ╣ЁЯЗп','ЁЯЗ╣ЁЯЗ░','ЁЯЗ╣ЁЯЗ▒','ЁЯЗ╣ЁЯЗ▓','ЁЯЗ╣ЁЯЗ│','ЁЯЗ╣ЁЯЗ┤','ЁЯЗ╣ЁЯЗ╖','ЁЯЗ╣ЁЯЗ╣','ЁЯЗ╣ЁЯЗ╗','ЁЯЗ╣ЁЯЗ╝','ЁЯЗ╣ЁЯЗ┐','ЁЯЗ║ЁЯЗж','ЁЯЗ║ЁЯЗм','ЁЯЗ║ЁЯЗ▓','ЁЯЗ║ЁЯЗ╕','ЁЯЗ║ЁЯЗ╛','ЁЯЗ║ЁЯЗ┐','ЁЯЗ╗ЁЯЗж','ЁЯЗ╗ЁЯЗи','ЁЯЗ╗ЁЯЗк','ЁЯЗ╗ЁЯЗм','ЁЯЗ╗ЁЯЗо','ЁЯЗ╗ЁЯЗ│','ЁЯЗ╗ЁЯЗ║','ЁЯЗ╝ЁЯЗл','ЁЯЗ╝ЁЯЗ╕','ЁЯЗ╜ЁЯЗ░','ЁЯЗ╛ЁЯЗк','ЁЯЗ╛ЁЯЗ╣','ЁЯЗ┐ЁЯЗж','ЁЯЗ┐ЁЯЗ▓','ЁЯЗ┐ЁЯЗ╝']; \ No newline at end of file +emoji_lookup = [ + "тМЪ","тМЫ","","тПк","тПл","тПм","тП░","тП│","тЧ╜","тЧ╛","тШФ","тШХ","тЩИ","тЩЙ","тЩК","тЩЛ","тЩМ","тЩН","тЩО","тЩП","тЩР","тЩС","тЩТ","тЩУ","тЩ┐","тЪУ", + "тЪб","тЪк","тЪл","тЪ╜","тЪ╛","тЫД","тЫЕ","тЫО","тЫФ","тЫк","тЫ▓","тЫ│","тЫ╡","тЫ║","тЫ╜","тЬЕ","тЬК","тЬЛ","тЬи","тЭМ","тЭО","тЭУ","тЭФ","тЭХ","тЭЧ","тЮХ", + "тЮЦ","тЮЧ","тЮ░","тЮ┐","тмЫ","тмЬ","тнР","тнХ","ЁЯАД","ЁЯГП","ЁЯЖО","ЁЯЖС","ЁЯЖТ","ЁЯЖУ","ЁЯЖФ","ЁЯЖХ","ЁЯЖЦ","ЁЯЖЧ","ЁЯЖШ","ЁЯЖЩ","ЁЯЖЪ","ЁЯИБ","ЁЯИЪ","ЁЯИп","ЁЯИ▓","ЁЯИ│", + "ЁЯИ┤","ЁЯИ╡","ЁЯИ╢","ЁЯИ╕","ЁЯИ╣","ЁЯИ║","ЁЯЙР","ЁЯЙС","ЁЯМА","ЁЯМБ","ЁЯМВ","ЁЯМГ","ЁЯМД","ЁЯМЕ","ЁЯМЖ","ЁЯМЗ","ЁЯМИ","ЁЯМЙ","ЁЯМК","ЁЯМЛ","ЁЯММ","ЁЯМН","ЁЯМО","ЁЯМП","ЁЯМР","ЁЯМС", + "ЁЯМТ","ЁЯМУ","ЁЯМФ","ЁЯМХ","ЁЯМЦ","ЁЯМЧ","ЁЯМШ","ЁЯМЩ","ЁЯМЪ","ЁЯМЫ","ЁЯМЬ","ЁЯМЭ","ЁЯМЮ","ЁЯМЯ","ЁЯМа","ЁЯМн","ЁЯМо","ЁЯМп","ЁЯМ░","ЁЯМ▒","ЁЯМ▓","ЁЯМ│","ЁЯМ┤","ЁЯМ╡","ЁЯМ╖","ЁЯМ╕", + "ЁЯМ╣","ЁЯМ║","ЁЯМ╗","ЁЯМ╝","ЁЯМ╜","ЁЯМ╛","ЁЯМ┐","ЁЯНА","ЁЯНБ","ЁЯНВ","ЁЯНГ","ЁЯНД","ЁЯНЕ","ЁЯНЖ","ЁЯНЗ","ЁЯНИ","ЁЯНЙ","ЁЯНК","ЁЯНЛ","ЁЯНМ","ЁЯНН","ЁЯНО","ЁЯНП","ЁЯНР","ЁЯНС","ЁЯНТ", + "ЁЯНУ","ЁЯНФ","ЁЯНХ","ЁЯНЦ","ЁЯНЧ","ЁЯНШ","ЁЯНЩ","ЁЯНЪ","ЁЯНЫ","ЁЯНЬ","ЁЯНЭ","ЁЯНЮ","ЁЯНЯ","ЁЯНа","ЁЯНб","ЁЯНв","ЁЯНг","ЁЯНд","ЁЯНе","ЁЯНж","ЁЯНз","ЁЯНи","ЁЯНй","ЁЯНк","ЁЯНл","ЁЯНм", + "ЁЯНн","ЁЯНо","ЁЯНп","ЁЯН░","ЁЯН▒","ЁЯН▓","ЁЯН│","ЁЯН┤","ЁЯН╡","ЁЯН╢","ЁЯН╖","ЁЯН╕","ЁЯН╣","ЁЯН║","ЁЯН╗","ЁЯН╝","ЁЯН╛","ЁЯН┐","ЁЯОА","ЁЯОБ","ЁЯОВ","ЁЯОГ","ЁЯОД","ЁЯОЕ","ЁЯОЖ","ЁЯОЗ", + "ЁЯОИ","ЁЯОЙ","ЁЯОК","ЁЯОЛ","ЁЯОМ","ЁЯОН","ЁЯОО","ЁЯОП","ЁЯОР","ЁЯОС","ЁЯОТ","ЁЯОУ","ЁЯОа","ЁЯОб","ЁЯОв","ЁЯОг","ЁЯОд","ЁЯОе","ЁЯОж","ЁЯОз","ЁЯОи","ЁЯОй","ЁЯОк","ЁЯОл","ЁЯОм","ЁЯОн", + "ЁЯОо","ЁЯОп","ЁЯО░","ЁЯО▒","ЁЯО▓","ЁЯО│","ЁЯО┤","ЁЯО╡","ЁЯО╢","ЁЯО╖","ЁЯО╕","ЁЯО╣","ЁЯО║","ЁЯО╗","ЁЯО╝","ЁЯО╜","ЁЯО╛","ЁЯО┐","ЁЯПА","ЁЯПБ","ЁЯПВ","ЁЯПГ","ЁЯПД","ЁЯПЕ","ЁЯПЖ","ЁЯПЗ", + "ЁЯПИ","ЁЯПЙ","ЁЯПК","ЁЯПП","ЁЯПР","ЁЯПС","ЁЯПТ","ЁЯПУ","ЁЯПа","ЁЯПб","ЁЯПв","ЁЯПг","ЁЯПд","ЁЯПе","ЁЯПж","ЁЯПз","ЁЯПи","ЁЯПй","ЁЯПк","ЁЯПл","ЁЯПм","ЁЯПн","ЁЯПо","ЁЯПп","ЁЯП░","ЁЯП┤", + "ЁЯП╕","ЁЯП╣","ЁЯП║","ЁЯП╗","ЁЯП╝","ЁЯП╜","ЁЯП╛","ЁЯП┐","ЁЯРА","ЁЯРБ","ЁЯРВ","ЁЯРГ","ЁЯРД","ЁЯРЕ","ЁЯРЖ","ЁЯРЗ","ЁЯРИ","ЁЯРЙ","ЁЯРК","ЁЯРЛ","ЁЯРМ","ЁЯРН","ЁЯРО","ЁЯРП","ЁЯРР","ЁЯРС", + "ЁЯРТ","ЁЯРУ","ЁЯРФ","ЁЯРХ","ЁЯРЦ","ЁЯРЧ","ЁЯРШ","ЁЯРЩ","ЁЯРЪ","ЁЯРЫ","ЁЯРЬ","ЁЯРЭ","ЁЯРЮ","ЁЯРЯ","ЁЯРа","ЁЯРб","ЁЯРв","ЁЯРг","ЁЯРд","ЁЯРе","ЁЯРж","ЁЯРз","ЁЯРи","ЁЯРй","ЁЯРк","ЁЯРл", + "ЁЯРм","ЁЯРн","ЁЯРо","ЁЯРп","ЁЯР░","ЁЯР▒","ЁЯР▓","ЁЯР│","ЁЯР┤","ЁЯР╡","ЁЯР╢","ЁЯР╖","ЁЯР╕","ЁЯР╣","ЁЯР║","ЁЯР╗","ЁЯР╝","ЁЯР╜","ЁЯР╛","ЁЯСА","ЁЯСВ","ЁЯСГ","ЁЯСД","ЁЯСЕ","ЁЯСЖ","ЁЯСЗ", + "ЁЯСИ","ЁЯСЙ","ЁЯСК","ЁЯСЛ","ЁЯСМ","ЁЯСН","ЁЯСО","ЁЯСП","ЁЯСР","ЁЯСС","ЁЯСТ","ЁЯСУ","ЁЯСФ","ЁЯСХ","ЁЯСЦ","ЁЯСЧ","ЁЯСШ","ЁЯСЩ","ЁЯСЪ","ЁЯСЫ","ЁЯСЬ","ЁЯСЭ","ЁЯСЮ","ЁЯСЯ","ЁЯСа","ЁЯСб", + "ЁЯСв","ЁЯСг","ЁЯСд","ЁЯСе","ЁЯСж","ЁЯСз","ЁЯСи","ЁЯСй","ЁЯСк","ЁЯСл","ЁЯСм","ЁЯСн","ЁЯСо","ЁЯСп","ЁЯС░","ЁЯС▒","ЁЯС▓","ЁЯС│","ЁЯС┤","ЁЯС╡","ЁЯС╢","ЁЯС╖","ЁЯС╕","ЁЯС╣","ЁЯС║","ЁЯС╗", + "ЁЯС╝","ЁЯС╜","ЁЯС╛","ЁЯС┐","ЁЯТА","ЁЯТБ","ЁЯТВ","ЁЯТГ","ЁЯТД","ЁЯТЕ","ЁЯТЖ","ЁЯТЗ","ЁЯТИ","ЁЯТЙ","ЁЯТК","ЁЯТЛ","ЁЯТМ","ЁЯТН","ЁЯТО","ЁЯТП","ЁЯТР","ЁЯТС","ЁЯТТ","ЁЯТУ","ЁЯТФ","ЁЯТХ", + "ЁЯТЦ","ЁЯТЧ","ЁЯТШ","ЁЯТЩ","ЁЯТЪ","ЁЯТЫ","ЁЯТЬ","ЁЯТЭ","ЁЯТЮ","ЁЯТЯ","ЁЯТа","ЁЯТб","ЁЯТв","ЁЯТг","ЁЯТд","ЁЯТе","ЁЯТж","ЁЯТз","ЁЯТи","ЁЯТй","ЁЯТк","ЁЯТл","ЁЯТм","ЁЯТн","ЁЯТо","ЁЯТп", + "ЁЯТ░","ЁЯТ▒","ЁЯТ▓","ЁЯТ│","ЁЯТ┤","ЁЯТ╡","ЁЯТ╢","ЁЯТ╖","ЁЯТ╕","ЁЯТ╣","ЁЯТ║","ЁЯТ╗","ЁЯТ╝","ЁЯТ╜","ЁЯТ╛","ЁЯТ┐","ЁЯУА","ЁЯУБ","ЁЯУВ","ЁЯУГ","ЁЯУД","ЁЯУЕ","ЁЯУЖ","ЁЯУЗ","ЁЯУИ","ЁЯУЙ", + "ЁЯУК","ЁЯУЛ","ЁЯУМ","ЁЯУН","ЁЯУО","ЁЯУП","ЁЯУР","ЁЯУС","ЁЯУТ","ЁЯУУ","ЁЯУФ","ЁЯУХ","ЁЯУЦ","ЁЯУЧ","ЁЯУШ","ЁЯУЩ","ЁЯУЪ","ЁЯУЫ","ЁЯУЬ","ЁЯУЭ","ЁЯУЮ","ЁЯУЯ","ЁЯУа","ЁЯУб","ЁЯУв","ЁЯУг", + "ЁЯУд","ЁЯУе","ЁЯУж","ЁЯУз","ЁЯУи","ЁЯУй","ЁЯУк","ЁЯУл","ЁЯУм","ЁЯУн","ЁЯУо","ЁЯУп","ЁЯУ░","ЁЯУ▒","ЁЯУ▓","ЁЯУ│","ЁЯУ┤","ЁЯУ╡","ЁЯУ╢","ЁЯУ╖","ЁЯУ╕","ЁЯУ╣","ЁЯУ║","ЁЯУ╗","ЁЯУ╝","ЁЯУ┐", + "ЁЯФА","ЁЯФБ","ЁЯФВ","ЁЯФГ","ЁЯФД","ЁЯФЕ","ЁЯФЖ","ЁЯФЗ","ЁЯФИ","ЁЯФЙ","ЁЯФК","ЁЯФЛ","ЁЯФМ","ЁЯФН","ЁЯФО","ЁЯФП","ЁЯФР","ЁЯФС","ЁЯФТ","ЁЯФУ","ЁЯФФ","ЁЯФХ","ЁЯФЦ","ЁЯФЧ","ЁЯФШ","ЁЯФЩ", + "ЁЯФЪ","ЁЯФЫ","ЁЯФЬ","ЁЯФЭ","ЁЯФЮ","ЁЯФЯ","ЁЯФа","ЁЯФб","ЁЯФв","ЁЯФг","ЁЯФд","ЁЯФе","ЁЯФж","ЁЯФз","ЁЯФи","ЁЯФй","ЁЯФк","ЁЯФл","ЁЯФм","ЁЯФн","ЁЯФо","ЁЯФп","ЁЯФ░","ЁЯФ▒","ЁЯФ▓","ЁЯФ│", + "ЁЯФ┤","ЁЯФ╡","ЁЯФ╢","ЁЯФ╖","ЁЯФ╕","ЁЯФ╣","ЁЯФ║","ЁЯФ╗","ЁЯФ╝","ЁЯФ╜","ЁЯХЛ","ЁЯХМ","ЁЯХН","ЁЯХО","ЁЯХР","ЁЯХС","ЁЯХТ","ЁЯХУ","ЁЯХФ","ЁЯХХ","ЁЯХЦ","ЁЯХЧ","ЁЯХШ","ЁЯХЩ","ЁЯХЪ","ЁЯХЫ", + "ЁЯХЬ","ЁЯХЭ","ЁЯХЮ","ЁЯХЯ","ЁЯХа","ЁЯХб","ЁЯХв","ЁЯХг","ЁЯХд","ЁЯХе","ЁЯХж","ЁЯХз","ЁЯЦХ","ЁЯЦЦ","ЁЯЧ╗","ЁЯЧ╝","ЁЯЧ╜","ЁЯЧ╛","ЁЯЧ┐","ЁЯША","ЁЯШБ","ЁЯШВ","ЁЯШГ","ЁЯШД","ЁЯШЕ","ЁЯШЖ", + "ЁЯШЗ","ЁЯШИ","ЁЯШЙ","ЁЯШК","ЁЯШЛ","ЁЯШМ","ЁЯШН","ЁЯШО","ЁЯШП","ЁЯШР","ЁЯШС","ЁЯШТ","ЁЯШУ","ЁЯШФ","ЁЯШХ","ЁЯШЦ","ЁЯШЧ","ЁЯШШ","ЁЯШЩ","ЁЯШЪ","ЁЯШЫ","ЁЯШЬ","ЁЯШЭ","ЁЯШЮ","ЁЯШЯ","ЁЯШа", + "ЁЯШб","ЁЯШв","ЁЯШг","ЁЯШд","ЁЯШе","ЁЯШж","ЁЯШз","ЁЯШи","ЁЯШй","ЁЯШк","ЁЯШл","ЁЯШм","ЁЯШн","ЁЯШо","ЁЯШп","ЁЯШ░","ЁЯШ▒","ЁЯШ▓","ЁЯШ│","ЁЯШ┤","ЁЯШ╡","ЁЯШ╢","ЁЯШ╖","ЁЯШ╕","ЁЯШ╣","ЁЯШ║", + "ЁЯШ╗","ЁЯШ╝","ЁЯШ╜","ЁЯШ╛","ЁЯШ┐","ЁЯЩА","ЁЯЩБ","ЁЯЩВ","ЁЯЩГ","ЁЯЩД","ЁЯЩЕ","ЁЯЩЖ","ЁЯЩЗ","ЁЯЩИ","ЁЯЩЙ","ЁЯЩК","ЁЯЩЛ","ЁЯЩМ","ЁЯЩН","ЁЯЩО","ЁЯЩП","ЁЯЪА","ЁЯЪБ","ЁЯЪВ","ЁЯЪГ","ЁЯЪД", + "ЁЯЪЕ","ЁЯЪЖ","ЁЯЪЗ","ЁЯЪИ","ЁЯЪЙ","ЁЯЪК","ЁЯЪЛ","ЁЯЪМ","ЁЯЪН","ЁЯЪО","ЁЯЪП","ЁЯЪР","ЁЯЪС","ЁЯЪТ","ЁЯЪУ","ЁЯЪФ","ЁЯЪХ","ЁЯЪЦ","ЁЯЪЧ","ЁЯЪШ","ЁЯЪЩ","ЁЯЪЪ","ЁЯЪЫ","ЁЯЪЬ","ЁЯЪЭ","ЁЯЪЮ", + "ЁЯЪЯ","ЁЯЪа","ЁЯЪб","ЁЯЪв","ЁЯЪг","ЁЯЪд","ЁЯЪе","ЁЯЪж","ЁЯЪз","ЁЯЪи","ЁЯЪй","ЁЯЪк","ЁЯЪл","ЁЯЪм","ЁЯЪн","ЁЯЪо","ЁЯЪп","ЁЯЪ░","ЁЯЪ▒","ЁЯЪ▓","ЁЯЪ│","ЁЯЪ┤","ЁЯЪ╡","ЁЯЪ╢","ЁЯЪ╖","ЁЯЪ╕", + "ЁЯЪ╣","ЁЯЪ║","ЁЯЪ╗","ЁЯЪ╝","ЁЯЪ╜","ЁЯЪ╛","ЁЯЪ┐","ЁЯЫА","ЁЯЫБ","ЁЯЫВ","ЁЯЫГ","ЁЯЫД","ЁЯЫЕ","ЁЯЫМ","ЁЯЫР","ЁЯЫл","ЁЯЫм","ЁЯдР","ЁЯдС","ЁЯдТ","ЁЯдУ","ЁЯдФ","ЁЯдХ","ЁЯдЦ","ЁЯдЧ","ЁЯдШ", + "ЁЯжА","ЁЯжБ","ЁЯжВ","ЁЯжГ","ЁЯжД","ЁЯзА","ЁЯЗжЁЯЗи","ЁЯЗжЁЯЗй","ЁЯЗжЁЯЗк","ЁЯЗжЁЯЗл","ЁЯЗжЁЯЗм","ЁЯЗжЁЯЗо","ЁЯЗжЁЯЗ▒","ЁЯЗжЁЯЗ▓","ЁЯЗжЁЯЗ┤","ЁЯЗжЁЯЗ╢","ЁЯЗжЁЯЗ╖","ЁЯЗжЁЯЗ╕","ЁЯЗжЁЯЗ╣","ЁЯЗжЁЯЗ║","ЁЯЗжЁЯЗ╝","ЁЯЗжЁЯЗ╜","ЁЯЗжЁЯЗ┐","ЁЯЗзЁЯЗж","ЁЯЗзЁЯЗз","ЁЯЗзЁЯЗй", + "ЁЯЗзЁЯЗк","ЁЯЗзЁЯЗл","ЁЯЗзЁЯЗм","ЁЯЗзЁЯЗн","ЁЯЗзЁЯЗо","ЁЯЗзЁЯЗп","ЁЯЗзЁЯЗ▒","ЁЯЗзЁЯЗ▓","ЁЯЗзЁЯЗ│","ЁЯЗзЁЯЗ┤","ЁЯЗзЁЯЗ╢","ЁЯЗзЁЯЗ╖","ЁЯЗзЁЯЗ╕","ЁЯЗзЁЯЗ╣","ЁЯЗзЁЯЗ╗","ЁЯЗзЁЯЗ╝","ЁЯЗзЁЯЗ╛","ЁЯЗзЁЯЗ┐","ЁЯЗиЁЯЗж","ЁЯЗиЁЯЗи","ЁЯЗиЁЯЗй","ЁЯЗиЁЯЗл","ЁЯЗиЁЯЗм","ЁЯЗиЁЯЗн","ЁЯЗиЁЯЗо","ЁЯЗиЁЯЗ░", + "ЁЯЗиЁЯЗ▒","ЁЯЗиЁЯЗ▓","ЁЯЗиЁЯЗ│","ЁЯЗиЁЯЗ┤","ЁЯЗиЁЯЗ╡","ЁЯЗиЁЯЗ╖","ЁЯЗиЁЯЗ║","ЁЯЗиЁЯЗ╗","ЁЯЗиЁЯЗ╝","ЁЯЗиЁЯЗ╜","ЁЯЗиЁЯЗ╛","ЁЯЗиЁЯЗ┐","ЁЯЗйЁЯЗк","ЁЯЗйЁЯЗм","ЁЯЗйЁЯЗп","ЁЯЗйЁЯЗ░","ЁЯЗйЁЯЗ▓","ЁЯЗйЁЯЗ┤","ЁЯЗйЁЯЗ┐","ЁЯЗкЁЯЗж","ЁЯЗкЁЯЗи","ЁЯЗкЁЯЗк","ЁЯЗкЁЯЗм","ЁЯЗкЁЯЗн","ЁЯЗкЁЯЗ╖","ЁЯЗкЁЯЗ╕", + "ЁЯЗкЁЯЗ╣","ЁЯЗкЁЯЗ║","ЁЯЗлЁЯЗо","ЁЯЗлЁЯЗп","ЁЯЗлЁЯЗ░","ЁЯЗлЁЯЗ▓","ЁЯЗлЁЯЗ┤","ЁЯЗлЁЯЗ╖","ЁЯЗмЁЯЗж","ЁЯЗмЁЯЗз","ЁЯЗмЁЯЗй","ЁЯЗмЁЯЗк","ЁЯЗмЁЯЗл","ЁЯЗмЁЯЗм","ЁЯЗмЁЯЗн","ЁЯЗмЁЯЗо","ЁЯЗмЁЯЗ▒","ЁЯЗмЁЯЗ▓","ЁЯЗмЁЯЗ│","ЁЯЗмЁЯЗ╡","ЁЯЗмЁЯЗ╢","ЁЯЗмЁЯЗ╖","ЁЯЗмЁЯЗ╕","ЁЯЗмЁЯЗ╣","ЁЯЗмЁЯЗ║","ЁЯЗмЁЯЗ╝", + "ЁЯЗмЁЯЗ╛","ЁЯЗнЁЯЗ░","ЁЯЗнЁЯЗ▓","ЁЯЗнЁЯЗ│","ЁЯЗнЁЯЗ╖","ЁЯЗнЁЯЗ╣","ЁЯЗнЁЯЗ║","ЁЯЗоЁЯЗи","ЁЯЗоЁЯЗй","ЁЯЗоЁЯЗк","ЁЯЗоЁЯЗ▒","ЁЯЗоЁЯЗ▓","ЁЯЗоЁЯЗ│","ЁЯЗоЁЯЗ┤","ЁЯЗоЁЯЗ╢","ЁЯЗоЁЯЗ╖","ЁЯЗоЁЯЗ╕","ЁЯЗоЁЯЗ╣","ЁЯЗпЁЯЗк","ЁЯЗпЁЯЗ▓","ЁЯЗпЁЯЗ┤","ЁЯЗпЁЯЗ╡","ЁЯЗ░ЁЯЗк","ЁЯЗ░ЁЯЗм","ЁЯЗ░ЁЯЗн","ЁЯЗ░ЁЯЗо", + "ЁЯЗ░ЁЯЗ▓","ЁЯЗ░ЁЯЗ│","ЁЯЗ░ЁЯЗ╡","ЁЯЗ░ЁЯЗ╖","ЁЯЗ░ЁЯЗ╝","ЁЯЗ░ЁЯЗ╛","ЁЯЗ░ЁЯЗ┐","ЁЯЗ▒ЁЯЗж","ЁЯЗ▒ЁЯЗз","ЁЯЗ▒ЁЯЗи","ЁЯЗ▒ЁЯЗо","ЁЯЗ▒ЁЯЗ░","ЁЯЗ▒ЁЯЗ╖","ЁЯЗ▒ЁЯЗ╕","ЁЯЗ▒ЁЯЗ╣","ЁЯЗ▒ЁЯЗ║","ЁЯЗ▒ЁЯЗ╗","ЁЯЗ▒ЁЯЗ╛","ЁЯЗ▓ЁЯЗж","ЁЯЗ▓ЁЯЗи","ЁЯЗ▓ЁЯЗй","ЁЯЗ▓ЁЯЗк","ЁЯЗ▓ЁЯЗл","ЁЯЗ▓ЁЯЗм","ЁЯЗ▓ЁЯЗн","ЁЯЗ▓ЁЯЗ░", + "ЁЯЗ▓ЁЯЗ▒","ЁЯЗ▓ЁЯЗ▓","ЁЯЗ▓ЁЯЗ│","ЁЯЗ▓ЁЯЗ┤","ЁЯЗ▓ЁЯЗ╡","ЁЯЗ▓ЁЯЗ╢","ЁЯЗ▓ЁЯЗ╖","ЁЯЗ▓ЁЯЗ╕","ЁЯЗ▓ЁЯЗ╣","ЁЯЗ▓ЁЯЗ║","ЁЯЗ▓ЁЯЗ╗","ЁЯЗ▓ЁЯЗ╝","ЁЯЗ▓ЁЯЗ╜","ЁЯЗ▓ЁЯЗ╛","ЁЯЗ▓ЁЯЗ┐","ЁЯЗ│ЁЯЗж","ЁЯЗ│ЁЯЗи","ЁЯЗ│ЁЯЗк","ЁЯЗ│ЁЯЗл","ЁЯЗ│ЁЯЗм","ЁЯЗ│ЁЯЗо","ЁЯЗ│ЁЯЗ▒","ЁЯЗ│ЁЯЗ┤","ЁЯЗ│ЁЯЗ╡","ЁЯЗ│ЁЯЗ╖","ЁЯЗ│ЁЯЗ║", + "ЁЯЗ│ЁЯЗ┐","ЁЯЗ┤ЁЯЗ▓","ЁЯЗ╡ЁЯЗж","ЁЯЗ╡ЁЯЗк","ЁЯЗ╡ЁЯЗл","ЁЯЗ╡ЁЯЗм","ЁЯЗ╡ЁЯЗн","ЁЯЗ╡ЁЯЗ░","ЁЯЗ╡ЁЯЗ▒","ЁЯЗ╡ЁЯЗ▓","ЁЯЗ╡ЁЯЗ│","ЁЯЗ╡ЁЯЗ╖","ЁЯЗ╡ЁЯЗ╕","ЁЯЗ╡ЁЯЗ╣","ЁЯЗ╡ЁЯЗ╝","ЁЯЗ╡ЁЯЗ╛","ЁЯЗ╢ЁЯЗж","ЁЯЗ╖ЁЯЗк","ЁЯЗ╖ЁЯЗ┤","ЁЯЗ╖ЁЯЗ╕","ЁЯЗ╖ЁЯЗ║","ЁЯЗ╖ЁЯЗ╝","ЁЯЗ╕ЁЯЗж","ЁЯЗ╕ЁЯЗз","ЁЯЗ╕ЁЯЗи","ЁЯЗ╕ЁЯЗй", + "ЁЯЗ╕ЁЯЗк","ЁЯЗ╕ЁЯЗм","ЁЯЗ╕ЁЯЗн","ЁЯЗ╕ЁЯЗо","ЁЯЗ╕ЁЯЗп","ЁЯЗ╕ЁЯЗ░","ЁЯЗ╕ЁЯЗ▒","ЁЯЗ╕ЁЯЗ▓","ЁЯЗ╕ЁЯЗ│","ЁЯЗ╕ЁЯЗ┤","ЁЯЗ╕ЁЯЗ╖","ЁЯЗ╕ЁЯЗ╕","ЁЯЗ╕ЁЯЗ╣","ЁЯЗ╕ЁЯЗ╗","ЁЯЗ╕ЁЯЗ╜","ЁЯЗ╕ЁЯЗ╛","ЁЯЗ╕ЁЯЗ┐","ЁЯЗ╣ЁЯЗж","ЁЯЗ╣ЁЯЗи","ЁЯЗ╣ЁЯЗй","ЁЯЗ╣ЁЯЗл","ЁЯЗ╣ЁЯЗм","ЁЯЗ╣ЁЯЗн","ЁЯЗ╣ЁЯЗп","ЁЯЗ╣ЁЯЗ░","ЁЯЗ╣ЁЯЗ▒", + "ЁЯЗ╣ЁЯЗ▓","ЁЯЗ╣ЁЯЗ│","ЁЯЗ╣ЁЯЗ┤","ЁЯЗ╣ЁЯЗ╖","ЁЯЗ╣ЁЯЗ╣","ЁЯЗ╣ЁЯЗ╗","ЁЯЗ╣ЁЯЗ╝","ЁЯЗ╣ЁЯЗ┐","ЁЯЗ║ЁЯЗж","ЁЯЗ║ЁЯЗм","ЁЯЗ║ЁЯЗ▓","ЁЯЗ║ЁЯЗ╕","ЁЯЗ║ЁЯЗ╛","ЁЯЗ║ЁЯЗ┐","ЁЯЗ╗ЁЯЗж","ЁЯЗ╗ЁЯЗи","ЁЯЗ╗ЁЯЗк","ЁЯЗ╗ЁЯЗм","ЁЯЗ╗ЁЯЗо","ЁЯЗ╗ЁЯЗ│","ЁЯЗ╗ЁЯЗ║","ЁЯЗ╝ЁЯЗл","ЁЯЗ╝ЁЯЗ╕","ЁЯЗ╜ЁЯЗ░","ЁЯЗ╛ЁЯЗк","ЁЯЗ╛ЁЯЗ╣", + "ЁЯЗ┐ЁЯЗж","ЁЯЗ┐ЁЯЗ▓","ЁЯЗ┐ЁЯЗ╝","ЁЯЯв"]; + +emoji_extra_1 = [ + "┬й","┬о","тА╝","тБЙ","тДв","тД╣","тЖФ","тЖХ","тЖЦ","тЖЧ","тЖШ","тЖЩ","тЖй","тЖк","тМЪ","тМЫ","тМи","тПП","тПй","тПк","тПл","тПм","тПн","тПо","тПп", + "тП░","тП▒","тП▓","тП│","тП╕","тП╣","тП║","тУВ","тЦк","тЦл","тЦ╢","тЧА","тЧ╗","тЧ╝","тЧ╜","тЧ╛","тША","тШБ","тШВ","тШГ","тШД","тШО","тШС","тШФ", + "тШХ","тШШ","тШЭ","тШа","тШв","тШг","тШж","тШк","тШо","тШп","тШ╕","тШ╣","тШ║","тЩА","тЩВ","тЩИ","тЩЙ","тЩК","тЩЛ","тЩМ","тЩН","тЩО","тЩП","тЩР", + "тЩС","тЩТ","тЩУ","тЩЯ","тЩа","тЩг","тЩе","тЩж","тЩи","тЩ╗","тЩ╛","тЩ┐","тЪТ","тЪУ","тЪФ","тЪХ","тЪЦ","тЪЧ","тЪЩ","тЪЫ","тЪЬ","тЪа","тЪб","тЪз","тЪк", + "тЪл","тЪ░","тЪ▒","тЪ╜","тЪ╛","тЫД","тЫЕ","тЫИ","тЫО","тЫП","тЫС","тЫУ","тЫФ","тЫй","тЫк","тЫ░","тЫ▒","тЫ▓","тЫ│","тЫ┤","тЫ╡","тЫ╖","тЫ╕", + "тЫ╣","тмЖ","тмЗ","тмЫ","тмЬ","тнР","тнХ","уА░","тЫ║","тЫ╜","тЬВ","тЬЕ","тЬИ","тЬЙ","тЬК","тЬЛ","тЬМ","тЬН","тЬП","тЬТ","тЬФ","тЬЦ","тЬЭ","тЬб", + "тЬи","тЬ│","тЬ┤","тЭД","тЭЗ","тЭМ","тЭО","тЭУ","тЭФ","тЭХ","тЭЧ","тЭг","тЭд","тЮХ","тЮЦ","тЮЧ","тЮб","тЮ░","тЮ┐","тд┤","тд╡","тмЕ","уА╜","уКЧ", + "уКЩ","ЁЯАД","ЁЯГП","ЁЯЕ░","ЁЯЕ▒","ЁЯЕ╛","ЁЯЕ┐","ЁЯЖО","ЁЯЖС","ЁЯЖТ","ЁЯЖУ","ЁЯЖФ","ЁЯЖХ","ЁЯЖЦ","ЁЯЖЧ","ЁЯЖШ","ЁЯЖЩ","ЁЯЖЪ","ЁЯИБ","ЁЯИВ","ЁЯИЪ","ЁЯИп","ЁЯИ▓", + "ЁЯИ│","ЁЯИ┤","ЁЯИ╡","ЁЯИ╢","ЁЯИ╖","ЁЯИ╕","ЁЯИ╣","ЁЯИ║","ЁЯЙР","ЁЯЙС","ЁЯМА","ЁЯМБ","ЁЯМВ","ЁЯМГ","ЁЯМД","ЁЯМЕ","ЁЯМЖ","ЁЯМЗ","ЁЯМИ","ЁЯМЙ","ЁЯМК","ЁЯМЛ", + "ЁЯММ","ЁЯМН","ЁЯМО","ЁЯМП","ЁЯМР","ЁЯМС","ЁЯМТ","ЁЯМУ","ЁЯМФ","ЁЯМХ","ЁЯМЦ","ЁЯМЧ","ЁЯМШ","ЁЯМЩ","ЁЯМЪ","ЁЯМЫ","ЁЯМЬ","ЁЯМЭ","ЁЯМЮ","ЁЯМЯ","ЁЯМа","ЁЯМб", + "ЁЯМд","ЁЯМе","ЁЯМж","ЁЯМз","ЁЯМи","ЁЯМй","ЁЯМк","ЁЯМл","ЁЯМм","ЁЯМн","ЁЯМо","ЁЯМп","ЁЯМ░","ЁЯМ▒","ЁЯМ▓","ЁЯМ│","ЁЯМ┤","ЁЯМ╡","ЁЯМ╢","ЁЯМ╖","ЁЯМ╕","ЁЯМ╣", + "ЁЯМ║","ЁЯМ╗","ЁЯМ╝","ЁЯМ╜","ЁЯМ╛","ЁЯМ┐","ЁЯНА","ЁЯНБ","ЁЯНВ","ЁЯНГ","ЁЯНД","ЁЯНЕ","ЁЯНЖ","ЁЯНЗ","ЁЯНИ","ЁЯНЙ","ЁЯНК","ЁЯНЛ","ЁЯНМ","ЁЯНН","ЁЯНО","ЁЯНП", + "ЁЯНР","ЁЯНС","ЁЯНТ","ЁЯНУ","ЁЯНФ","ЁЯНХ","ЁЯНЦ","ЁЯНЧ","ЁЯНШ","ЁЯНЩ","ЁЯНЪ","ЁЯНЫ","ЁЯНЬ","ЁЯНЭ","ЁЯНЮ","ЁЯНЯ","ЁЯНа","ЁЯНб","ЁЯНв","ЁЯНг","ЁЯНд","ЁЯНе", + "ЁЯНж","ЁЯНз","ЁЯНи","ЁЯНй","ЁЯНк","ЁЯНл","ЁЯНм","ЁЯНн","ЁЯНо","ЁЯНп","ЁЯН░","ЁЯН▒","ЁЯН▓","ЁЯН│","ЁЯН┤","ЁЯН╡","ЁЯН╢","ЁЯН╖","ЁЯН╕","ЁЯН╣","ЁЯН║","ЁЯН╗", + "ЁЯН╝","ЁЯН╜","ЁЯН╛","ЁЯН┐","ЁЯОА","ЁЯОБ","ЁЯОВ","ЁЯОГ","ЁЯОД","ЁЯОЕ","ЁЯОЖ","ЁЯОЗ","ЁЯОИ","ЁЯОЙ","ЁЯОК","ЁЯОЛ","ЁЯОМ","ЁЯОН","ЁЯОО","ЁЯОП","ЁЯОР","ЁЯОС", + "ЁЯОТ","ЁЯОУ","ЁЯОЦ","ЁЯОЧ","ЁЯОЩ","ЁЯОЪ","ЁЯОЫ","ЁЯОЮ","ЁЯОЯ","ЁЯОа","ЁЯОб","ЁЯОв","ЁЯОг","ЁЯОд","ЁЯОе","ЁЯОж","ЁЯОз","ЁЯОи","ЁЯОй","ЁЯОк","ЁЯОл","ЁЯОм","ЁЯОн", + "ЁЯОо","ЁЯОп","ЁЯО░","ЁЯО▒","ЁЯО▓","ЁЯО│","ЁЯО┤","ЁЯО╡","ЁЯО╢","ЁЯО╖","ЁЯО╕","ЁЯО╣","ЁЯО║","ЁЯО╗","ЁЯО╝","ЁЯО╜","ЁЯО╛","ЁЯО┐","ЁЯПА","ЁЯПБ","ЁЯПВ","ЁЯПГ", + "ЁЯПД","ЁЯПЕ","ЁЯПЖ","ЁЯПЗ","ЁЯПИ","ЁЯПЙ","ЁЯПК","ЁЯПЛ","ЁЯПМ","ЁЯПН","ЁЯПО","ЁЯПП","ЁЯПР","ЁЯПС","ЁЯПТ","ЁЯПУ","ЁЯПФ","ЁЯПХ","ЁЯПЦ","ЁЯПЧ","ЁЯПШ","ЁЯПЩ", + "ЁЯПЪ","ЁЯПЫ","ЁЯПЬ","ЁЯПЭ","ЁЯПЮ","ЁЯПЯ","ЁЯПа","ЁЯПб","ЁЯПв","ЁЯПг","ЁЯПд","ЁЯПе","ЁЯПж","ЁЯПз","ЁЯПи","ЁЯПй","ЁЯПк","ЁЯПл","ЁЯПм","ЁЯПн","ЁЯПо","ЁЯПп", + "ЁЯП░","ЁЯП│","ЁЯП┤","ЁЯП╡","ЁЯП╖","ЁЯП╕","ЁЯП╣","ЁЯП║","ЁЯП╗","ЁЯП╝","ЁЯП╜","ЁЯП╛","ЁЯП┐","ЁЯРА","ЁЯРБ","ЁЯРВ","ЁЯРГ","ЁЯРД","ЁЯРЕ","ЁЯРЖ","ЁЯРЗ","ЁЯРИ", + "ЁЯРЙ","ЁЯРК","ЁЯРЛ","ЁЯРМ","ЁЯРН","ЁЯРО","ЁЯРП","ЁЯРР","ЁЯРС","ЁЯРТ","ЁЯРУ","ЁЯРФ","ЁЯРХ","ЁЯРЦ","ЁЯРЧ","ЁЯРШ","ЁЯРЩ","ЁЯРЪ","ЁЯРЫ","ЁЯРЬ","ЁЯРЭ","ЁЯРЮ", + "ЁЯРЯ","ЁЯРа","ЁЯРб","ЁЯРв","ЁЯРг","ЁЯРд","ЁЯРе","ЁЯРж","ЁЯРз","ЁЯРи","ЁЯРй","ЁЯРк","ЁЯРл","ЁЯРм","ЁЯРн","ЁЯРо","ЁЯРп","ЁЯР░","ЁЯР▒","ЁЯР▓","ЁЯР│","ЁЯР┤", + "ЁЯР╡","ЁЯР╢","ЁЯР╖","ЁЯР╕","ЁЯР╣","ЁЯР║","ЁЯР╗","ЁЯР╝","ЁЯР╜","ЁЯР╛","ЁЯР┐","ЁЯСА","ЁЯСБ","ЁЯСВ","ЁЯСГ","ЁЯСД","ЁЯСЕ","ЁЯСЖ","ЁЯСЗ","ЁЯСИ","ЁЯСЙ","ЁЯСК", + "ЁЯСЛ","ЁЯСМ","ЁЯСН","ЁЯСО","ЁЯСП","ЁЯСР","ЁЯСС","ЁЯСТ","ЁЯСУ","ЁЯСФ","ЁЯСХ","ЁЯСЦ","ЁЯСЧ","ЁЯСШ","ЁЯСЩ","ЁЯСЪ","ЁЯСЫ","ЁЯСЬ","ЁЯСЭ","ЁЯСЮ","ЁЯСЯ","ЁЯСа", + "ЁЯСб","ЁЯСв","ЁЯСг","ЁЯСд","ЁЯСе","ЁЯСж","ЁЯСз","ЁЯСи","ЁЯСй","ЁЯСк","ЁЯСл","ЁЯСм","ЁЯСн","ЁЯСо","ЁЯСп","ЁЯС░","ЁЯС▒","ЁЯС▓","ЁЯС│","ЁЯС┤","ЁЯС╡","ЁЯС╢", + "ЁЯС╖","ЁЯС╕","ЁЯС╣","ЁЯС║","ЁЯС╗","ЁЯС╝","ЁЯС╜","ЁЯС╛","ЁЯС┐","ЁЯТА","ЁЯТБ","ЁЯТВ","ЁЯТГ","ЁЯТД","ЁЯТЕ","ЁЯТЖ","ЁЯТЗ","ЁЯТИ","ЁЯТЙ","ЁЯТК","ЁЯТЛ","ЁЯТМ", + "ЁЯТН","ЁЯТО","ЁЯТП","ЁЯТР","ЁЯТС","ЁЯТТ","ЁЯТУ","ЁЯТФ","ЁЯТХ","ЁЯТЦ","ЁЯТЧ","ЁЯТШ","ЁЯТЩ","ЁЯТЪ","ЁЯТЫ","ЁЯТЬ","ЁЯТЭ","ЁЯТЮ","ЁЯТЯ","ЁЯТа","ЁЯТб","ЁЯТв", + "ЁЯТг","ЁЯТд","ЁЯТе","ЁЯТж","ЁЯТз","ЁЯТи","ЁЯТй","ЁЯТк","ЁЯТл","ЁЯТм","ЁЯТн","ЁЯТо","ЁЯТп","ЁЯТ░","ЁЯТ▒","ЁЯТ▓","ЁЯТ│","ЁЯТ┤","ЁЯТ╡","ЁЯТ╢","ЁЯТ╖","ЁЯТ╕", + "ЁЯТ╣","ЁЯТ║","ЁЯТ╗","ЁЯТ╝","ЁЯТ╜","ЁЯТ╛","ЁЯТ┐","ЁЯУА","ЁЯУБ","ЁЯУВ","ЁЯУГ","ЁЯУД","ЁЯУЕ","ЁЯУЖ","ЁЯУЗ","ЁЯУИ","ЁЯУЙ","ЁЯУК","ЁЯУЛ","ЁЯУМ","ЁЯУН","ЁЯУО", + "ЁЯУП","ЁЯУР","ЁЯУС","ЁЯУТ","ЁЯУУ","ЁЯУФ","ЁЯУХ","ЁЯУЦ","ЁЯУЧ","ЁЯУШ","ЁЯУЩ","ЁЯУЪ","ЁЯУЫ","ЁЯУЬ","ЁЯУЭ","ЁЯУЮ","ЁЯУЯ","ЁЯУа","ЁЯУб","ЁЯУв","ЁЯУг","ЁЯУд", + "ЁЯУе","ЁЯУж","ЁЯУз","ЁЯУи","ЁЯУй","ЁЯУк","ЁЯУл","ЁЯУм","ЁЯУн","ЁЯУо","ЁЯУп","ЁЯУ░","ЁЯУ▒","ЁЯУ▓","ЁЯУ│","ЁЯУ┤","ЁЯУ╡","ЁЯУ╢","ЁЯУ╖","ЁЯУ╕","ЁЯУ╣","ЁЯУ║", + "ЁЯУ╗","ЁЯУ╝","ЁЯУ╜","ЁЯУ┐","ЁЯФА","ЁЯФБ","ЁЯФВ","ЁЯФГ","ЁЯФД","ЁЯФЕ","ЁЯФЖ","ЁЯФЗ","ЁЯФИ","ЁЯФЙ","ЁЯФК","ЁЯФЛ","ЁЯФМ","ЁЯФН","ЁЯФО","ЁЯФП","ЁЯФР","ЁЯФС", + "ЁЯФТ","ЁЯФУ","ЁЯФФ","ЁЯФХ","ЁЯФЦ","ЁЯФЧ","ЁЯФШ","ЁЯФЩ","ЁЯФЪ","ЁЯФЫ","ЁЯФЬ","ЁЯФЭ","ЁЯФЮ","ЁЯФЯ","ЁЯФа","ЁЯФб","ЁЯФв","ЁЯФг","ЁЯФд","ЁЯФе","ЁЯФж","ЁЯФз", + "ЁЯФи","ЁЯФй","ЁЯФк","ЁЯФл","ЁЯФм","ЁЯФн","ЁЯФо","ЁЯФп","ЁЯФ░","ЁЯФ▒","ЁЯФ▓","ЁЯФ│","ЁЯФ┤","ЁЯФ╡","ЁЯФ╢","ЁЯФ╖","ЁЯФ╕","ЁЯФ╣","ЁЯФ║","ЁЯФ╗","ЁЯФ╝","ЁЯФ╜", + "ЁЯХЙ","ЁЯХК","ЁЯХЛ","ЁЯХМ","ЁЯХН","ЁЯХО","ЁЯХР","ЁЯХС","ЁЯХТ","ЁЯХУ","ЁЯХФ","ЁЯХХ","ЁЯХЦ","ЁЯХЧ","ЁЯХШ","ЁЯХЩ","ЁЯХЪ","ЁЯХЫ","ЁЯХЬ","ЁЯХЭ","ЁЯХЮ","ЁЯХЯ", + "ЁЯХа","ЁЯХб","ЁЯХв","ЁЯХг","ЁЯХд","ЁЯХе","ЁЯХж","ЁЯХз","ЁЯХп","ЁЯХ░","ЁЯХ│","ЁЯХ┤","ЁЯХ╡","ЁЯХ╢","ЁЯХ╖","ЁЯХ╕","ЁЯХ╣","ЁЯХ║","ЁЯЦЗ","ЁЯЦК","ЁЯЦЛ","ЁЯЦМ","ЁЯЦН", + "ЁЯЦР","ЁЯЦХ","ЁЯЦЦ","ЁЯЦд","ЁЯЦе","ЁЯЦи","ЁЯЦ▒","ЁЯЦ▓","ЁЯЦ╝","ЁЯЧВ","ЁЯЧГ","ЁЯЧД","ЁЯЧС","ЁЯЧТ","ЁЯЧУ","ЁЯЧЬ","ЁЯЧЭ","ЁЯЧЮ","ЁЯЧб","ЁЯЧг","ЁЯЧи","ЁЯЧп","ЁЯЧ│","ЁЯЧ║", + "ЁЯЧ╗","ЁЯЧ╝","ЁЯЧ╜","ЁЯЧ╛","ЁЯЧ┐","ЁЯША","ЁЯШБ","ЁЯШВ","ЁЯШГ","ЁЯШД","ЁЯШЕ","ЁЯШЖ","ЁЯШЗ","ЁЯШИ","ЁЯШЙ","ЁЯШК","ЁЯШЛ","ЁЯШМ","ЁЯШН","ЁЯШО","ЁЯШП","ЁЯШР", + "ЁЯШС","ЁЯШТ","ЁЯШУ","ЁЯШФ","ЁЯШХ","ЁЯШЦ","ЁЯШЧ","ЁЯШШ","ЁЯШЩ","ЁЯШЪ","ЁЯШЫ","ЁЯШЬ","ЁЯШЭ","ЁЯШЮ","ЁЯШЯ","ЁЯШа","ЁЯШб","ЁЯШв","ЁЯШг","ЁЯШд","ЁЯШе","ЁЯШж", + "ЁЯШз","ЁЯШи","ЁЯШй","ЁЯШк","ЁЯШл","ЁЯШм","ЁЯШн","ЁЯШо","ЁЯШп","ЁЯШ░","ЁЯШ▒","ЁЯШ▓","ЁЯШ│","ЁЯШ┤","ЁЯШ╡","ЁЯШ╢","ЁЯШ╖","ЁЯШ╕","ЁЯШ╣","ЁЯШ║","ЁЯШ╗","ЁЯШ╝", + "ЁЯШ╜","ЁЯШ╛","ЁЯШ┐","ЁЯЩА","ЁЯЩБ","ЁЯЩВ","ЁЯЩГ","ЁЯЩД","ЁЯЩЕ","ЁЯЩЖ","ЁЯЩЗ","ЁЯЩИ","ЁЯЩЙ","ЁЯЩК","ЁЯЩЛ","ЁЯЩМ","ЁЯЩН","ЁЯЩО","ЁЯЩП","ЁЯЪА","ЁЯЪБ","ЁЯЪВ", + "ЁЯЪГ","ЁЯЪД","ЁЯЪЕ","ЁЯЪЖ","ЁЯЪЗ","ЁЯЪИ","ЁЯЪЙ","ЁЯЪК","ЁЯЪЛ","ЁЯЪМ","ЁЯЪН","ЁЯЪО","ЁЯЪП","ЁЯЪР","ЁЯЪС","ЁЯЪТ","ЁЯЪУ","ЁЯЪФ","ЁЯЪХ","ЁЯЪЦ","ЁЯЪЧ","ЁЯЪШ", + "ЁЯЪЩ","ЁЯЪЪ","ЁЯЪЫ","ЁЯЪЬ","ЁЯЪЭ","ЁЯЪЮ","ЁЯЪЯ","ЁЯЪа","ЁЯЪб","ЁЯЪв","ЁЯЪг","ЁЯЪд","ЁЯЪе","ЁЯЪж","ЁЯЪз","ЁЯЪи","ЁЯЪй","ЁЯЪк","ЁЯЪл","ЁЯЪм","ЁЯЪн","ЁЯЪо", + "ЁЯЪп","ЁЯЪ░","ЁЯЪ▒","ЁЯЪ▓","ЁЯЪ│","ЁЯЪ┤","ЁЯЪ╡","ЁЯЪ╢","ЁЯЪ╖","ЁЯЪ╕","ЁЯЪ╣","ЁЯЪ║","ЁЯЪ╗","ЁЯЪ╝","ЁЯЪ╜","ЁЯЪ╛","ЁЯЪ┐","ЁЯЫА","ЁЯЫБ","ЁЯЫВ","ЁЯЫГ","ЁЯЫД", + "ЁЯЫЕ","ЁЯЫЛ","ЁЯЫМ","ЁЯЫН","ЁЯЫО","ЁЯЫП","ЁЯЫР","ЁЯЫС","ЁЯЫТ","ЁЯЫХ","ЁЯЫЦ","ЁЯЫЧ","ЁЯЫа","ЁЯЫб","ЁЯЫв","ЁЯЫг","ЁЯЫд","ЁЯЫе","ЁЯЫй","ЁЯЫл","ЁЯЫм","ЁЯЫ░","ЁЯЫ│", + "ЁЯЫ┤","ЁЯЫ╡","ЁЯЫ╢","ЁЯЫ╖","ЁЯЫ╕","ЁЯЫ╣","ЁЯЫ║","ЁЯЫ╗","ЁЯЫ╝","ЁЯЯа","ЁЯЯб","ЁЯЯв","ЁЯЯг","ЁЯЯд","ЁЯЯе","ЁЯЯж","ЁЯЯз","ЁЯЯи","ЁЯЯй","ЁЯЯк","ЁЯЯл","ЁЯдМ", + "ЁЯдН","ЁЯдО","ЁЯдП","ЁЯдР","ЁЯдС","ЁЯдТ","ЁЯдУ","ЁЯдФ","ЁЯдХ","ЁЯдЦ","ЁЯдЧ","ЁЯдШ","ЁЯдЩ","ЁЯдЪ","ЁЯдЫ","ЁЯдЬ","ЁЯдЭ","ЁЯдЮ","ЁЯдЯ","ЁЯда","ЁЯдб","ЁЯдв", + "ЁЯдг","ЁЯдд","ЁЯде","ЁЯдж","ЁЯдз","ЁЯди","ЁЯдй","ЁЯдк","ЁЯдл","ЁЯдм","ЁЯдн","ЁЯдо","ЁЯдп","ЁЯд░","ЁЯд▒","ЁЯд▓","ЁЯд│","ЁЯд┤","ЁЯд╡","ЁЯд╢","ЁЯд╖","ЁЯд╕", + "ЁЯд╣","ЁЯд║","ЁЯд╝","ЁЯд╜","ЁЯд╛","ЁЯд┐","ЁЯеА","ЁЯеБ","ЁЯеВ","ЁЯеГ","ЁЯеД","ЁЯеЕ","ЁЯеЗ","ЁЯеИ","ЁЯеЙ","ЁЯеК","ЁЯеЛ","ЁЯеМ","ЁЯеН","ЁЯеО","ЁЯеП","ЁЯеР", + "ЁЯеС","ЁЯеТ","ЁЯеУ","ЁЯеФ","ЁЯеХ","ЁЯеЦ","ЁЯеЧ","ЁЯеШ","ЁЯеЩ","ЁЯеЪ","ЁЯеЫ","ЁЯеЬ","ЁЯеЭ","ЁЯеЮ","ЁЯеЯ","ЁЯеа","ЁЯеб","ЁЯев","ЁЯег","ЁЯед","ЁЯее","ЁЯеж", + "ЁЯез","ЁЯеи","ЁЯей","ЁЯек","ЁЯел","ЁЯем","ЁЯен","ЁЯео","ЁЯеп","ЁЯе░","ЁЯе▒","ЁЯе▓","ЁЯе│","ЁЯе┤","ЁЯе╡","ЁЯе╢","ЁЯе╖","ЁЯе╕","ЁЯе║","ЁЯе╗","ЁЯе╝","ЁЯе╜", + "ЁЯе╛","ЁЯе┐","ЁЯжА","ЁЯжБ","ЁЯжВ","ЁЯжГ","ЁЯжД","ЁЯжЕ","ЁЯжЖ","ЁЯжЗ","ЁЯжИ","ЁЯжЙ","ЁЯжК","ЁЯжЛ","ЁЯжМ","ЁЯжН","ЁЯжО","ЁЯжП","ЁЯжР","ЁЯжС","ЁЯжТ","ЁЯжУ", + "ЁЯжФ","ЁЯжХ","ЁЯжЦ","ЁЯжЧ","ЁЯжШ","ЁЯжЩ","ЁЯжЪ","ЁЯжЫ","ЁЯжЬ","ЁЯжЭ","ЁЯжЮ","ЁЯжЯ","ЁЯжа","ЁЯжб","ЁЯжв","ЁЯжг","ЁЯжд","ЁЯже","ЁЯжж","ЁЯжз","ЁЯжи","ЁЯжй", + "ЁЯжк","ЁЯжл","ЁЯжм","ЁЯжн","ЁЯжо","ЁЯжп","ЁЯж░","ЁЯж▒","ЁЯж▓","ЁЯж│","ЁЯж┤","ЁЯж╡","ЁЯж╢","ЁЯж╖","ЁЯж╕","ЁЯж╣","ЁЯж║","ЁЯж╗","ЁЯж╝","ЁЯж╜","ЁЯж╛","ЁЯж┐", + "ЁЯзА","ЁЯзБ","ЁЯзВ","ЁЯзГ","ЁЯзД","ЁЯзЕ","ЁЯзЖ","ЁЯзЗ","ЁЯзИ","ЁЯзЙ","ЁЯзК","ЁЯзЛ","ЁЯзН","ЁЯзО","ЁЯзП","ЁЯзР","ЁЯзС","ЁЯзТ","ЁЯзУ","ЁЯзФ","ЁЯзХ","ЁЯзЦ", + "ЁЯзЧ","ЁЯзШ","ЁЯзЩ","ЁЯзЪ","ЁЯзЫ","ЁЯзЬ","ЁЯзЭ","ЁЯзЮ","ЁЯзЯ","ЁЯза","ЁЯзб","ЁЯзв","ЁЯзг","ЁЯзд","ЁЯзе","ЁЯзж","ЁЯзз","ЁЯзи","ЁЯзй","ЁЯзк","ЁЯзл","ЁЯзм", + "ЁЯзн","ЁЯзо","ЁЯзп","ЁЯз░","ЁЯз▒","ЁЯз▓","ЁЯз│","ЁЯз┤","ЁЯз╡","ЁЯз╢","ЁЯз╖","ЁЯз╕","ЁЯз╣","ЁЯз║","ЁЯз╗","ЁЯз╝","ЁЯз╜","ЁЯз╛","ЁЯз┐","ЁЯй░","ЁЯй▒","ЁЯй▓", + "ЁЯй│","ЁЯй┤","ЁЯй╕","ЁЯй╣","ЁЯй║","ЁЯкА","ЁЯкБ","ЁЯкВ","ЁЯкГ","ЁЯкД","ЁЯкЕ","ЁЯкЖ","ЁЯкР","ЁЯкС","ЁЯкТ","ЁЯкУ","ЁЯкФ","ЁЯкХ","ЁЯкЦ","ЁЯкЧ","ЁЯкШ","ЁЯкЩ", + "ЁЯкЪ","ЁЯкЫ","ЁЯкЬ","ЁЯкЭ","ЁЯкЮ","ЁЯкЯ","ЁЯка","ЁЯкб","ЁЯкв","ЁЯкг","ЁЯкд","ЁЯке","ЁЯкж","ЁЯкз","ЁЯки","ЁЯк░","ЁЯк▒","ЁЯк▓","ЁЯк│","ЁЯк┤","ЁЯк╡","ЁЯк╢", + "ЁЯлА","ЁЯлБ","ЁЯлВ","ЁЯлР","ЁЯлС","ЁЯлТ","ЁЯлУ","ЁЯлФ","ЁЯлХ","ЁЯлЦ"] + +for e in emoji_extra_1: + if not e in emoji_lookup: + emoji_lookup.append(e) diff --git a/sbapp/ui/keys.py b/sbapp/ui/keys.py new file mode 100644 index 0000000..cd62b9c --- /dev/null +++ b/sbapp/ui/keys.py @@ -0,0 +1,274 @@ +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 test_a(self, sender): + RNS.log("TEST ACTION"); + RNS.log(self) + RNS.log(self.app) + + 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.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['close', lambda x: root.app.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 69db515..7faf7a4 100644 --- a/sbapp/ui/layouts.py +++ b/sbapp/ui/layouts.py @@ -61,6 +61,16 @@ MDNavigationLayout: on_release: root.ids.screen_manager.app.conversations_action(self) + OneLineIconListItem: + text: "Objects & Devices" + on_release: root.ids.screen_manager.app.objects_action(self) + # _no_ripple_effect: True + + IconLeftWidget: + icon: "devices" + on_release: root.ids.screen_manager.app.objects_action(self) + + OneLineIconListItem: text: "Situation Map" on_release: root.ids.screen_manager.app.map_action(self) @@ -70,6 +80,15 @@ MDNavigationLayout: on_release: root.ids.screen_manager.app.map_action(self) + # OneLineIconListItem: + # text: "Overview" + # on_release: root.ids.screen_manager.app.overview_action(self) + + # IconLeftWidget: + # icon: "view-dashboard-outline" + # on_release: root.ids.screen_manager.app.overview_action(self) + + OneLineIconListItem: text: "Announce Stream" on_release: root.ids.screen_manager.app.announces_action(self) @@ -77,15 +96,25 @@ MDNavigationLayout: IconLeftWidget: icon: "account-voice" on_release: root.ids.screen_manager.app.announces_action(self) + - OneLineIconListItem: - text: "Local Broadcasts" - on_release: root.ids.screen_manager.app.broadcasts_action(self) + text: "Voice" + on_release: root.ids.screen_manager.app.voice_action(self) + # _no_ripple_effect: True IconLeftWidget: - icon: "radio-tower" - on_release: root.ids.screen_manager.app.broadcasts_action(self) + icon: "phone-in-talk" + on_release: root.ids.screen_manager.app.voice_action(self) + + + # OneLineIconListItem: + # text: "Local Broadcasts" + # on_release: root.ids.screen_manager.app.broadcasts_action(self) + + # IconLeftWidget: + # icon: "radio-tower" + # on_release: root.ids.screen_manager.app.broadcasts_action(self) OneLineIconListItem: @@ -97,6 +126,15 @@ MDNavigationLayout: on_release: root.ids.screen_manager.app.telemetry_action(self) + OneLineIconListItem: + text: "Utilities" + on_release: root.ids.screen_manager.app.utilities_action(self) + + IconLeftWidget: + icon: "tools" + on_release: root.ids.screen_manager.app.utilities_action(self) + + OneLineIconListItem: text: "Preferences" on_release: root.ids.screen_manager.app.settings_action(self) @@ -125,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) @@ -322,6 +360,23 @@ MDScreen: text_size: self.width, None height: self.texture_size[1] + MDBoxLayout: + id: connectivity_service_restart_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] @@ -571,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] @@ -603,15 +696,33 @@ MDScreen: # font_size: dp(24) # # disabled: True - MDLabel: - text: "Shared Instance Access\\n" - id: connectivity_shared_access_label - font_style: "H6" + # 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_access_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] @@ -738,106 +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_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" @@ -1042,98 +1053,6 @@ MDScreen: id: map_layout """ -layout_keys_screen = """ -MDScreen: - name: "keys_screen" - - BoxLayout: - orientation: "vertical" - - MDTopAppBar: - title: "Encryption 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: 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" @@ -1166,7 +1085,7 @@ MDScreen: padding: [0,dp(0),dp(0),dp(0)] text: "Plugin Settings" id: plugins_active_heading - font_style: "H6" + font_style: "H5" size_hint_y: None height: self.texture_size[1] @@ -1242,6 +1161,28 @@ MDScreen: """ layout_settings_screen = """ + + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height+dp(0) + + MDLabel: + id: scaling_info + markup: True + text: "You can scale the entire Sideband UI by specifying a scaling factor in the field below. After setting it, restart sideband for the scaling to take effect.\\n\\nSet to 0.0 to disable scaling adjustments.\\n\\n[b]Please note![/b] On some devices, the default scaling factor will be higher than 1.0, and setting a smaller value will result in miniscule UI elements." + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] + + MDTextField: + id: scaling_factor + hint_text: "Scaling Factor" + helper_text: "From 0.3 to 5.0" + helper_text_mode: "on_focus" + text: "" + font_size: dp(24) + MDScreen: name: "settings_screen" @@ -1276,7 +1217,7 @@ MDScreen: MDLabel: text: "User Options" - font_style: "H6" + font_style: "H5" size_hint_y: None height: self.texture_size[1] @@ -1316,8 +1257,17 @@ MDScreen: height: dp(64) MDLabel: - text: "Address & Identity" + text: "тАв" font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2), 0, dp(22)] + + MDLabel: + text: "Address & Identity" + font_style: "H5" size_hint_y: None height: self.texture_size[1] @@ -1350,11 +1300,43 @@ MDScreen: font_size: dp(24) height: dp(64) + MDLabel: + text: "тАв" + font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(2), 0, dp(22)] + + MDLabel: + text: "Appearance" + font_style: "H5" + size_hint_y: None + height: self.texture_size[1] + + MDLabel: + id: settings_info3 + markup: True + text: "\\nThis section lets you configure the appearance of the application to suit your preferences, such as themes and what levels of information to display. When user icons are enabled, the contact list will display icons other users have configured in their [b]Telemetry[/b] settings.\\n" + size_hint_y: None + height: self.texture_size[1] + + MDRectangleFlatIconButton: + id: appearance_ui_scaling + icon: "relative-scale" + text: "Configure UI Scaling" + 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.configure_ui_scaling_action(self) + MDBoxLayout: orientation: "horizontal" size_hint_y: None - padding: [0,0,dp(24),dp(0)] - height: dp(48) + padding: [0,dp(14),dp(24),dp(0)] + height: dp(62) MDLabel: text: "Notifications" @@ -1402,7 +1384,22 @@ MDScreen: height: dp(48) MDLabel: - text: "Display styles in conversation list" + text: "Classic message colors" + font_style: "H6" + + MDSwitch: + id: settings_classic_message_colors + 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: "Show user icons in conversation list" font_style: "H6" MDSwitch: @@ -1410,6 +1407,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: "Only show user icons from trusted" + font_style: "H6" + + MDSwitch: + id: display_style_from_trusted_only + pos_hint: {"center_y": 0.3} + active: False + MDBoxLayout: orientation: "horizontal" size_hint_y: None @@ -1432,7 +1444,44 @@ MDScreen: height: dp(48) MDLabel: - text: "Announce Automatically" + 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" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(22), 0, dp(2)] + + MDLabel: + text: "\\nBehaviour" + font_style: "H5" + size_hint_y: None + height: self.texture_size[1] + + MDLabel: + id: settings_info3 + markup: True + text: "\\nThis section configures various automated actions and default behaviours. Sync intervals can be configured, and you can control what kind of peers can send you messages.\\n" + size_hint_y: 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: "Announce automatically" font_style: "H6" MDSwitch: @@ -1447,7 +1496,7 @@ MDScreen: height: dp(48) MDLabel: - text: "Try Propagation Node on direct delivery failure" + text: "Try propagation automatically" font_style: "H6" MDSwitch: @@ -1488,6 +1537,38 @@ MDScreen: disabled: False active: False + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Only render markup from trusted" + font_style: "H6" + + MDSwitch: + id: settings_trusted_markup_only + pos_hint: {"center_y": 0.3} + disabled: False + active: False + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Compose messages in markdown" + font_style: "H6" + + MDSwitch: + id: settings_compose_in_markdown + pos_hint: {"center_y": 0.3} + disabled: False + active: False + MDBoxLayout: orientation: "horizontal" size_hint_y: None @@ -1559,14 +1640,94 @@ MDScreen: height: dp(48) MDLabel: - text: "Use Home Node as Broadcast Repeater" + id: settings_lxmf_require_stamps_label + text: "Require stamps for incoming" font_style: "H6" MDSwitch: - id: settings_home_node_as_broadcast_repeater + id: settings_lxmf_require_stamps pos_hint: {"center_y": 0.3} + disabled: False active: False - disabled: True + + MDBoxLayout: + id: lxmf_costslider_container + orientation: "vertical" + size_hint_y: None + padding: [0,0,dp(0),0] + height: dp(68) + + MDSlider + min: 1 + max: 32 + value: 8 + id: settings_lxmf_require_stamps_cost + sensitivity: "all" + hint: False + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "Ignore messages with invalid stamps" + font_style: "H6" + + MDSwitch: + id: settings_ignore_invalid_stamps + pos_hint: {"center_y": 0.3} + disabled: False + active: False + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) + + MDLabel: + text: "High-quality codec for LXMF PTT" + font_style: "H6" + + MDSwitch: + id: settings_hq_ptt + pos_hint: {"center_y": 0.3} + 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 + # padding: [0,0,dp(24),dp(0)] + # height: dp(48) + + # MDLabel: + # text: "Use Home Node as Broadcast Repeater" + # font_style: "H6" + + # MDSwitch: + # id: settings_home_node_as_broadcast_repeater + # pos_hint: {"center_y": 0.3} + # active: False + # disabled: True MDBoxLayout: orientation: "horizontal" @@ -1585,8 +1746,17 @@ MDScreen: active: False MDLabel: - text: "Input Options & Localisation" + text: "тАв" font_style: "H6" + text_size: self.size + halign: "center" + size_hint_y: None + height: self.texture_size[1] + padding: [0, dp(0), 0, dp(30)] + + MDLabel: + text: "Input Options & Localisation" + font_style: "H5" size_hint_y: None height: self.texture_size[1] @@ -1687,20 +1857,20 @@ 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) + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + padding: [0,0,dp(24),dp(0)] + height: dp(48) - # MDLabel: - # text: "Allow Predictive Text" - # font_style: "H6" + MDLabel: + text: "Block Predictive Text" + font_style: "H6" - # MDSwitch: - # id: settings_allow_predictive_text - # pos_hint: {"center_y": 0.3} - # active: False + MDSwitch: + id: settings_block_predictive_text + pos_hint: {"center_y": 0.3} + active: False # MDBoxLayout: # orientation: "vertical" @@ -1709,7 +1879,7 @@ MDScreen: # padding: [0, dp(24), 0, dp(24)] # MDRectangleFlatIconButton: - # id: hardware_rnode_button + # id: input_language_button # icon: "translate" # text: "Input Languages" # padding: [dp(0), dp(14), dp(0), dp(14)] @@ -1808,563 +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(35)] - - 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" - 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,0,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 - - 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 - - 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" - 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 - - MDTextField: - id: hardware_rnode_bt_device - hint_text: "Preferred RNode Device Name" - text: "" - font_size: dp(24) -""" - -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) -""" diff --git a/sbapp/ui/messages.py b/sbapp/ui/messages.py index e802366..5e2026b 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 @@ -25,37 +26,67 @@ else: import io import os -import plyer import subprocess import shlex from kivy.graphics.opengl import glGetIntegerv, GL_MAX_TEXTURE_SIZE if RNS.vendor.platformutils.get_platform() == "android": + import plyer from sideband.sense import Telemeter, Commands from ui.helpers import ts_format, file_ts_format, mdc - from ui.helpers import color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light + from ui.helpers import color_playing, color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light, intensity_play_dark, intensity_play_light, color_cancelled, intensity_cancelled + from ui.helpers import color_received_alt, color_received_alt_light, color_delivered_alt, color_propagated_alt, color_paper_alt, color_failed_alt, color_unknown_alt, color_playing_alt, intensity_msgs_dark_alt, intensity_msgs_light_alt, intensity_delivered_alt_dark, color_cancelled_alt else: + import sbapp.plyer as plyer from sbapp.sideband.sense import Telemeter, Commands from .helpers import ts_format, file_ts_format, mdc - from .helpers import color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light + from .helpers import color_playing, color_received, color_delivered, color_propagated, color_paper, color_failed, color_unknown, intensity_msgs_dark, intensity_msgs_light, intensity_play_dark, intensity_play_light, color_cancelled, intensity_cancelled + from .helpers import color_received_alt, color_received_alt_light, color_delivered_alt, color_propagated_alt, color_paper_alt, color_failed_alt, color_unknown_alt, color_playing_alt, intensity_msgs_dark_alt, intensity_msgs_light_alt, intensity_delivered_alt_dark, color_cancelled_alt if RNS.vendor.platformutils.is_darwin(): from PIL import Image as PilImage 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: + 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() + 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 self.context_dest = context_dest self.source_dest = context_dest self.is_trusted = self.app.sideband.is_trusted(self.context_dest) + self.ptt_enabled = self.app.sideband.ptt_enabled(self.context_dest) self.screen = self.app.root.ids.screen_manager.get_screen("messages_screen") self.ids = self.screen.ids @@ -71,6 +102,7 @@ class Messages(): self.widgets = [] self.send_error_dialog = None self.load_more_button = None + self.details_dialog = None self.update() def reload(self): @@ -93,7 +125,125 @@ class Messages(): self.loading_earlier_messages = True self.list.remove_widget(self.load_more_button) + def message_details_dialog(self, lxm_hash): + ss = int(dp(16)) + ms = int(dp(14)) + + msg = self.app.sideband.message(lxm_hash) + if msg: + close_button = MDRectangleFlatButton(text="Close", font_size=dp(18)) + + d_text = "" + + if "lxm" in msg and msg["lxm"] != None: + size_str = RNS.prettysize(msg["lxm"].packed_size) + d_text += f"[size={ss}][b]Message size[/b] {size_str}[/size]\n" + + if msg["lxm"].signature_validated: + d_text += f"[size={ss}][b]Signature[/b] validated successfully[/size]\n" + else: + d_text += f"[size={ss}][b]Signature[/b] is invalid[/size]\n" + + ratchet_method = "" + if "method" in msg: + if msg["method"] == LXMF.LXMessage.UNKNOWN: + d_text += f"[size={ss}][b]Delivered[/b] via unknown method[/size]\n" + if msg["method"] == LXMF.LXMessage.OPPORTUNISTIC: + ratchet_method = "with ratchet" + d_text += f"[size={ss}][b]Delivered[/b] opportunistically[/size]\n" + if msg["method"] == LXMF.LXMessage.DIRECT: + ratchet_method = "by link" + d_text += f"[size={ss}][b]Delivered[/b] over direct link[/size]\n" + if msg["method"] == LXMF.LXMessage.PROPAGATED: + ratchet_method = "with ratchet" + d_text += f"[size={ss}][b]Delivered[/b] to propagation network[/size]\n" + + if msg["extras"] != None and "ratchet_id" in msg["extras"]: + r_str = RNS.prettyhexrep(msg["extras"]["ratchet_id"]) + d_text += f"[size={ss}][b]Encrypted[/b] {ratchet_method} {r_str}[/size]\n" + else: + if msg["method"] == LXMF.LXMessage.OPPORTUNISTIC or msg["method"] == LXMF.LXMessage.PROPAGATED: + d_text += f"[size={ss}][b]Encrypted[/b] with destination identity key[/size]\n" + else: + d_text += f"[size={ss}][b]Encryption[/b] status unknown[/size]\n" + + if msg["extras"] != None and "stamp_checked" in msg["extras"]: + valid_str = " is not valid" + if msg["extras"]["stamp_valid"] == True: + valid_str = " is valid" + sv = msg["extras"]["stamp_value"] + if sv == None: + if "stamp_raw" in msg["extras"]: + sv_str = "" + valid_str = "is not valid" + else: + sv_str = "" + valid_str = "was not included in the message" + elif sv > 255: + sv_str = "generated from ticket" + else: + sv_str = f"with value {sv}" + + if msg["extras"]["stamp_checked"] == True: + d_text += f"[size={ss}][b]Stamp[/b] {sv_str}{valid_str}[/size]\n" + + else: + sv = msg["extras"]["stamp_value"] + if sv == None: + pass + elif sv > 255: + d_text += f"[size={ss}][b]Stamp[/b] generated from ticket[/size]\n" + else: + d_text += f"[size={ss}][b]Value[/b] of stamp is {sv}[/size]\n" + + # Stamp details + if "stamp_raw" in msg["extras"] and type(msg["extras"]["stamp_raw"]) == bytes: + sstr = RNS.hexrep(msg["extras"]["stamp_raw"]) + sstr1 = RNS.hexrep(msg["extras"]["stamp_raw"][:16]) + sstr2 = RNS.hexrep(msg["extras"]["stamp_raw"][16:]) + d_text += f"[size={ss}]\n[b]Raw stamp[/b]\n[/size][size={ms}][font=RobotoMono-Regular]{sstr1}\n{sstr2}[/font][/size]\n" + + self.details_dialog = MDDialog( + title="Message Details", + type="simple", + text=d_text, + # items=d_items, + buttons=[ close_button ], + width_offset=dp(32), + ) + + close_button.bind(on_release=self.details_dialog.dismiss) + self.details_dialog.open() + def update(self, limit=8): + if self.app.sideband.config["block_predictive_text"]: + if self.ids.message_text.input_type != "null": + self.ids.message_text.input_type = "null" + self.ids.message_text.keyboard_suggestions = False + else: + if self.ids.message_text.input_type != "text": + self.ids.message_text.input_type = "text" + self.ids.message_text.keyboard_suggestions = True + + if not self.app.sideband.config["classic_message_colors"]: + c_delivered = color_delivered_alt + c_received = color_received_alt + c_propagated = color_propagated_alt + c_playing = color_playing_alt + c_paper = color_paper_alt + c_unknown = color_unknown_alt + c_failed = color_failed_alt + c_cancelled = color_cancelled_alt + else: + c_delivered = color_delivered + c_received = color_received + c_propagated = color_propagated + c_playing = color_playing + c_paper = color_paper + c_unknown = color_unknown + c_failed = color_failed + c_cancelled = color_cancelled + for new_message in self.app.sideband.list_messages(self.context_dest, after=self.latest_message_timestamp,limit=limit): self.new_messages.append(new_message) @@ -116,18 +266,34 @@ 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 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: - 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)) - if self.app.sideband.config["dark_ui"]: - intensity_msgs = intensity_msgs_dark + if self.app.sideband.config["classic_message_colors"]: + if self.app.sideband.config["dark_ui"]: + intensity_msgs = intensity_msgs_dark + intensity_play = intensity_play_dark + intensity_delivered = intensity_msgs + else: + intensity_msgs = intensity_msgs_light + intensity_play = intensity_play_light + intensity_delivered = intensity_msgs else: - intensity_msgs = intensity_msgs_light + if self.app.sideband.config["dark_ui"]: + intensity_msgs = intensity_msgs_dark_alt + intensity_play = intensity_play_dark + intensity_delivered = intensity_delivered_alt_dark + else: + intensity_msgs = intensity_msgs_light_alt + intensity_play = intensity_play_light + intensity_delivered = intensity_msgs for w in self.widgets: m = w.m @@ -136,77 +302,223 @@ class Messages(): else: w.line_color = (1.0, 1.0, 1.0, 0.5) - if m["state"] == LXMF.LXMessage.SENDING or m["state"] == LXMF.LXMessage.OUTBOUND: + if m["state"] == LXMF.LXMessage.SENDING or m["state"] == LXMF.LXMessage.OUTBOUND or m["state"] == LXMF.LXMessage.SENT: msg = self.app.sideband.message(m["hash"]) - if msg["state"] == LXMF.LXMessage.OUTBOUND or msg["state"] == LXMF.LXMessage.SENDING: - w.md_bg_color = msg_color = mdc(color_unknown, intensity_msgs) - txstr = time.strftime(ts_format, time.localtime(msg["sent"])) - titlestr = "" - prgstr = "" - sphrase = "Sending" - prg = self.app.sideband.get_lxm_progress(msg["hash"]) - if prg != None: - prgstr = ", "+str(round(prg*100, 1))+"% done" - if prg <= 0.00: - sphrase = "Waiting for path" - elif prg <= 0.03: - sphrase = "Establishing link" - elif prg <= 0.05: - sphrase = "Link established" - elif prg >= 0.05: - sphrase = "Sending" - - if msg["title"]: - titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" - w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] "+sphrase+prgstr+" " - m["state"] = msg["state"] + if msg != None: + delivery_syms = "" + # if msg["extras"] != None and "ratchet_id" in m["extras"]: + # delivery_syms += " тЪЩя╕П" + if msg["method"] == LXMF.LXMessage.OPPORTUNISTIC: + delivery_syms += " ЁЯУи" + if msg["method"] == LXMF.LXMessage.DIRECT: + delivery_syms += " ЁЯФЧ" + if msg["method"] == LXMF.LXMessage.PROPAGATED: + delivery_syms += " ЁЯУж" + delivery_syms = multilingual_markup(delivery_syms.encode("utf-8")).decode("utf-8") - if msg["state"] == LXMF.LXMessage.DELIVERED: - w.md_bg_color = msg_color = mdc(color_delivered, intensity_msgs) - txstr = time.strftime(ts_format, time.localtime(msg["sent"])) - titlestr = "" - if msg["title"]: - titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" - w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Delivered" - m["state"] = msg["state"] + if msg["state"] > LXMF.LXMessage.SENT: + if hasattr(w, "dmenu"): + if hasattr(w.dmenu, "items"): + remove_item = None + for item in w.dmenu.items: + if item["text"] == "Cancel message": + remove_item = item + break + if remove_item != None: + w.dmenu.items.remove(remove_item) - if msg["method"] == LXMF.LXMessage.PAPER: - w.md_bg_color = msg_color = mdc(color_paper, intensity_msgs) - txstr = time.strftime(ts_format, time.localtime(msg["sent"])) - titlestr = "" - if msg["title"]: - titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" - w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Paper Message" - m["state"] = msg["state"] + if msg["state"] == LXMF.LXMessage.OUTBOUND or msg["state"] == LXMF.LXMessage.SENDING or msg["state"] == LXMF.LXMessage.SENT: + w.md_bg_color = msg_color = mdc(c_unknown, intensity_msgs) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + 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 or prg == None or w.last_prg == None: speed = None + else: + bd = prg*size - w.last_prg*size + speed = (bd/td)*8 - if msg["method"] == LXMF.LXMessage.PROPAGATED and msg["state"] == LXMF.LXMessage.SENT: - w.md_bg_color = msg_color = mdc(color_propagated, intensity_msgs) - txstr = time.strftime(ts_format, time.localtime(msg["sent"])) - titlestr = "" - if msg["title"]: - titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" - w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] On Propagation Net" - m["state"] = msg["state"] + if prg != None: + 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 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 PN stamp with cost {prop_cost}" + prgstr = "" + else: + sphrase = "Waiting for path" + elif prg <= 0.01: + sphrase = "Waiting for path" + elif prg <= 0.03: + sphrase = "Establishing link" + elif prg <= 0.05: + 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" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] "+sphrase+prgstr+" " + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + m["state"] = msg["state"] - if msg["state"] == LXMF.LXMessage.FAILED: - w.md_bg_color = msg_color = mdc(color_failed, intensity_msgs) - txstr = time.strftime(ts_format, time.localtime(msg["sent"])) - titlestr = "" - if msg["title"]: - titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" - w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Failed" - m["state"] = msg["state"] - w.dmenu.items.append(w.dmenu.retry_item) + att_heading_str = "" + if hasattr(w, "has_attachment") and w.has_attachment: + att_heading_str = "\n[b]Attachments[/b] " + for attachment in w.attachments_field: + att_heading_str += str(attachment[0])+", " + att_heading_str = att_heading_str[:-2] + if msg["state"] == LXMF.LXMessage.DELIVERED: + w.md_bg_color = msg_color = mdc(c_delivered, intensity_delivered) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] Delivered" + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + m["state"] = msg["state"] + + if msg["method"] == LXMF.LXMessage.PAPER: + w.md_bg_color = msg_color = mdc(c_paper, intensity_msgs) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Paper Message" + m["state"] = msg["state"] + + if msg["method"] == LXMF.LXMessage.PROPAGATED and msg["state"] == LXMF.LXMessage.SENT: + w.md_bg_color = msg_color = mdc(c_propagated, intensity_msgs) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] On Propagation Net" + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + m["state"] = msg["state"] + + if msg["state"] == LXMF.LXMessage.FAILED: + w.md_bg_color = msg_color = mdc(c_failed, intensity_cancelled) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Failed" + m["state"] = msg["state"] + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + w.dmenu.items.append(w.dmenu.retry_item) + + if msg["state"] == LXMF.LXMessage.CANCELLED: + w.md_bg_color = msg_color = mdc(c_cancelled, intensity_cancelled) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Cancelled" + m["state"] = msg["state"] + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + w.dmenu.items.append(w.dmenu.retry_item) + + if msg["state"] == LXMF.LXMessage.REJECTED: + w.md_bg_color = msg_color = mdc(c_cancelled, intensity_cancelled) + txstr = time.strftime(ts_format, time.localtime(msg["sent"])) + titlestr = "" + if msg["title"]: + titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n" + w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Rejected" + m["state"] = msg["state"] + if w.has_audio: + alstr = RNS.prettysize(w.audio_size) + w.heading += f"\n[b]Audio Message[/b] ({alstr})" + w.dmenu.items.append(w.dmenu.retry_item) + + w.heading += att_heading_str + + + def hide_widget(self, wid, dohide=True): + if hasattr(wid, 'saved_attrs'): + if not dohide: + wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs + del wid.saved_attrs + elif dohide: + wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled + wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True def update_widget(self): - if self.app.sideband.config["dark_ui"]: - intensity_msgs = intensity_msgs_dark - mt_color = [1.0, 1.0, 1.0, 0.8] + + if self.app.sideband.config["classic_message_colors"]: + if self.app.sideband.config["dark_ui"]: + intensity_msgs = intensity_msgs_dark + intensity_play = intensity_play_dark + intensity_delivered = intensity_msgs + mt_color = [1.0, 1.0, 1.0, 0.8] + else: + intensity_msgs = intensity_msgs_light + intensity_play = intensity_play_light + intensity_delivered = intensity_msgs + mt_color = [1.0, 1.0, 1.0, 0.95] else: - intensity_msgs = intensity_msgs_light - mt_color = [1.0, 1.0, 1.0, 0.95] + if self.app.sideband.config["dark_ui"]: + intensity_msgs = intensity_msgs_dark_alt + intensity_play = intensity_play_dark + intensity_delivered = intensity_delivered_alt_dark + mt_color = [1.0, 1.0, 1.0, 0.8] + else: + intensity_msgs = intensity_msgs_light_alt + intensity_play = intensity_play_light + intensity_delivered = intensity_msgs + mt_color = [1.0, 1.0, 1.0, 0.95] + + if not self.app.sideband.config["classic_message_colors"]: + if self.app.sideband.config["dark_ui"]: + c_received = color_received_alt + else: + c_received = color_received_alt_light + c_delivered = color_delivered_alt + c_propagated = color_propagated_alt + c_playing = color_playing_alt + c_paper = color_paper_alt + c_unknown = color_unknown_alt + c_failed = color_failed_alt + c_cancelled = color_cancelled_alt + else: + c_delivered = color_delivered + c_received = color_received + c_propagated = color_propagated + c_playing = color_playing + c_paper = color_paper + c_unknown = color_unknown + c_failed = color_failed + c_cancelled = color_cancelled self.ids.message_text.font_name = self.app.input_font @@ -215,12 +527,37 @@ class Messages(): for m in self.new_messages: if not m["hash"] in self.added_item_hashes: - if not self.is_trusted: - message_input = str( escape_markup(m["content"].decode("utf-8")) ).encode("utf-8") - else: - message_input = m["content"] + renderer = None + message_source = m["content"] + if "lxm" in m and m["lxm"] and m["lxm"].fields != None and LXMF.FIELD_RENDERER in m["lxm"].fields: + renderer = m["lxm"].fields[LXMF.FIELD_RENDERER] - message_markup = multilingual_markup(message_input) + try: + if self.app.sideband.config["trusted_markup_only"] and not self.is_trusted: + message_input = str( escape_markup(m["content"].decode("utf-8")) ).encode("utf-8") + else: + message_input = m["content"] + if renderer == LXMF.RENDERER_MARKDOWN: + message_input = self.app.md_to_bbcode(message_input.decode("utf-8")).encode("utf-8") + message_input = self.app.process_bb_markup(message_input.decode("utf-8")).encode("utf-8") + elif renderer == LXMF.RENDERER_BBCODE: + message_input = self.app.process_bb_markup(message_input.decode("utf-8")).encode("utf-8") + else: + message_input = str(escape_markup(m["content"].decode("utf-8"))).encode("utf-8") + + except Exception as e: + RNS.log(f"Message content could not be decoded: {e}", RNS.LOG_DEBUG) + RNS.trace_exception(e) + message_input = b"" + + if message_input.strip() == b"": + 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") + + # 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"])) @@ -229,11 +566,26 @@ class Messages(): extra_telemetry = {} telemeter = None image_field = None + audio_field = None has_image = False + has_audio = False attachments_field = None has_attachment = False force_markup = False signature_valid = False + stamp_valid = False + stamp_value = None + + delivery_syms = "" + # if m["extras"] != None and "ratchet_id" in m["extras"]: + # delivery_syms += " тЪЩя╕П" + if m["method"] == LXMF.LXMessage.OPPORTUNISTIC: + delivery_syms += " ЁЯУи" + if m["method"] == LXMF.LXMessage.DIRECT: + delivery_syms += " ЁЯФЧ" + if m["method"] == LXMF.LXMessage.PROPAGATED: + delivery_syms += " ЁЯУж" + delivery_syms = multilingual_markup(delivery_syms.encode("utf-8")).decode("utf-8") if "lxm" in m and m["lxm"] != None and m["lxm"].signature_validated: signature_valid = True @@ -244,6 +596,10 @@ class Messages(): except Exception as e: pass + if "extras" in m and m["extras"] != None and "stamp_checked" in m["extras"] and m["extras"]["stamp_checked"] == True: + stamp_valid = m["extras"]["stamp_valid"] + stamp_value = m["extras"]["stamp_value"] + if "lxm" in m and m["lxm"] != None and m["lxm"].fields != None and LXMF.FIELD_COMMANDS in m["lxm"].fields: try: commands = m["lxm"].fields[LXMF.FIELD_COMMANDS] @@ -276,6 +632,13 @@ class Messages(): except Exception as e: pass + if "lxm" in m and m["lxm"] and m["lxm"].fields != None and LXMF.FIELD_AUDIO in m["lxm"].fields: + try: + audio_field = m["lxm"].fields[LXMF.FIELD_AUDIO] + has_audio = True + except Exception as e: + pass + if "lxm" in m and m["lxm"] and m["lxm"].fields != None and LXMF.FIELD_FILE_ATTACHMENTS in m["lxm"].fields: if len(m["lxm"].fields[LXMF.FIELD_FILE_ATTACHMENTS]) > 0: try: @@ -328,36 +691,44 @@ class Messages(): if m["source"] == self.app.sideband.lxmf_destination.hash: if m["state"] == LXMF.LXMessage.DELIVERED: - msg_color = mdc(color_delivered, intensity_msgs) - heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Delivered" + msg_color = mdc(c_delivered, intensity_delivered) + heading_str = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] Delivered" elif m["method"] == LXMF.LXMessage.PROPAGATED and m["state"] == LXMF.LXMessage.SENT: - msg_color = mdc(color_propagated, intensity_msgs) - heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] On Propagation Net" + msg_color = mdc(c_propagated, intensity_msgs) + heading_str = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] On Propagation Net" elif m["method"] == LXMF.LXMessage.PAPER: - msg_color = mdc(color_paper, intensity_msgs) + msg_color = mdc(c_paper, intensity_msgs) heading_str = titlestr+"[b]Created[/b] "+txstr+"\n[b]State[/b] Paper Message" elif m["state"] == LXMF.LXMessage.FAILED: - msg_color = mdc(color_failed, intensity_msgs) + msg_color = mdc(c_failed, intensity_cancelled) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Failed" + elif m["state"] == LXMF.LXMessage.CANCELLED: + msg_color = mdc(c_cancelled, intensity_cancelled) + heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Cancelled" + + elif m["state"] == LXMF.LXMessage.REJECTED: + msg_color = mdc(c_cancelled, intensity_cancelled) + heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Rejected" + elif m["state"] == LXMF.LXMessage.OUTBOUND or m["state"] == LXMF.LXMessage.SENDING: - msg_color = mdc(color_unknown, intensity_msgs) + msg_color = mdc(c_unknown, intensity_msgs) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Sending " else: - msg_color = mdc(color_unknown, intensity_msgs) + msg_color = mdc(c_unknown, intensity_msgs) heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Unknown" else: - msg_color = mdc(color_received, intensity_msgs) + msg_color = mdc(c_received, intensity_msgs) heading_str = titlestr if phy_stats_str != "" and self.app.sideband.config["advanced_stats"]: heading_str += phy_stats_str+"\n" - heading_str += "[b]Sent[/b] "+txstr + heading_str += "[b]Sent[/b] "+txstr+delivery_syms heading_str += "\n[b]Received[/b] "+rxstr if rcvd_d_str != "": @@ -379,14 +750,51 @@ class Messages(): heading_str += str(attachment[0])+", " heading_str = heading_str[:-2] + if has_audio: + 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, ) + item.lsource = m["source"] + item.has_audio = False if has_attachment: item.attachments_field = attachments_field + item.has_attachment = True + else: + item.has_attachment = False + + if has_audio: + def play_audio(sender): + 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 + + 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]) + item.audio_field = audio_field + item.bind(on_release=play_audio) if image_field != None: item.has_image = True @@ -430,6 +838,19 @@ class Messages(): item.ids.content_text.owner = item item.ids.content_text.bind(texture_size=check_textures) + def cbf(w): + def x(dt): + if w.texture_size[0] == 0 and w.texture_size[1] == 0: + w.markup = False + escaped_content = escape_markup(w.text) + def deferred(dt): + w.text = "[i]This message could not be rendered correctly, likely due to an error in its markup. Falling back to plain-text rendering.[/i]\n\n"+escaped_content + w.markup = True + Clock.schedule_once(deferred, 0.1) + return x + + Clock.schedule_once(cbf(item.ids.content_text), 0.25) + if not RNS.vendor.platformutils.is_android(): item.radius = dp(5) @@ -480,6 +901,15 @@ class Messages(): return x + def gen_details(mhash, item): + def x(): + item.dmenu.dismiss() + def cb(dt): + self.message_details_dialog(mhash) + Clock.schedule_once(cb, 0.2) + + return x + def gen_copy(msg, item): def x(): Clipboard.copy(msg) @@ -487,6 +917,13 @@ class Messages(): return x + def gen_cancel(mhash, item): + def x(): + self.app.sideband.cancel_message(mhash) + item.dmenu.dismiss() + + return x + def gen_save_image(item): if RNS.vendor.platformutils.is_android(): def x(): @@ -741,6 +1178,14 @@ class Messages(): "height": dp(40), "on_release": gen_retry(m["hash"], m["content"], item) } + + details_item = { + "viewclass": "OneLineListItem", + "text": "Details", + "height": dp(40), + "on_release": gen_details(m["hash"], item) + } + if m["method"] == LXMF.LXMessage.PAPER: if RNS.vendor.platformutils.is_android(): qr_save_text = "Share QR Code" @@ -761,7 +1206,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy message text", "height": dp(40), - "on_release": gen_copy(m["content"].decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -795,7 +1240,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy message text", "height": dp(40), - "on_release": gen_copy(m["content"].decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -813,7 +1258,7 @@ class Messages(): "viewclass": "OneLineListItem", "text": "Copy", "height": dp(40), - "on_release": gen_copy(m["content"].decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -825,11 +1270,12 @@ class Messages(): else: if telemeter != None: dm_items = [ + details_item, { "viewclass": "OneLineListItem", "text": "Copy", "height": dp(40), - "on_release": gen_copy(m["content"].decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "viewclass": "OneLineListItem", @@ -847,11 +1293,12 @@ class Messages(): else: dm_items = [ + details_item, { "viewclass": "OneLineListItem", "text": "Copy", "height": dp(40), - "on_release": gen_copy(m["content"].decode("utf-8"), item) + "on_release": gen_copy(message_source.decode("utf-8"), item) }, { "text": "Delete", @@ -876,6 +1323,14 @@ class Messages(): "on_release": gen_save_attachment(item) } dm_items.append(extra_item) + if m["source"] == self.app.sideband.lxmf_destination.hash and m["state"] <= LXMF.LXMessage.SENT: + extra_item = { + "viewclass": "OneLineListItem", + "text": "Cancel message", + "height": dp(40), + "on_release": gen_cancel(m["hash"], item) + } + dm_items.append(extra_item) item.dmenu = MDDropdownMenu( caller=item.ids.msg_submenu, @@ -965,7 +1420,27 @@ MDScreen: icon: "key-wireless" text: "Query Network For Keys" on_release: root.app.key_query_action(self) - + + BoxLayout: + id: message_ptt + padding: [dp(16), dp(8), dp(16), dp(8)] + spacing: dp(24) + size_hint_y: None + height: self.minimum_height + + MDRectangleFlatIconButton: + id: message_ptt_button + icon: "microphone" + text: "PTT" + size_hint_x: 1.0 + padding: [dp(10), dp(13), dp(10), dp(14)] + icon_size: dp(24) + font_size: dp(16) + on_press: root.app.message_ptt_down_action(self) + on_release: root.app.message_ptt_up_action(self) + _no_ripple_effect: True + background_normal: "" + background_down: "" BoxLayout: id: message_input_part @@ -976,6 +1451,7 @@ MDScreen: MDTextField: id: message_text + input_type: "text" keyboard_suggestions: True multiline: True hint_text: "Write message" @@ -1017,7 +1493,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)) @@ -1032,6 +1511,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] diff --git a/sbapp/ui/objectdetails.py b/sbapp/ui/objectdetails.py index b8e3be8..e61b36e 100644 --- a/sbapp/ui/objectdetails.py +++ b/sbapp/ui/objectdetails.py @@ -41,6 +41,7 @@ class ObjectDetails(): self.raw_telemetry = None self.from_telemetry = False self.from_conv = False + self.from_objects = False self.viewing_self = False self.delete_dialog = None @@ -84,6 +85,8 @@ class ObjectDetails(): else: if self.from_conv: self.app.open_conversation(self.object_hash, direction="right") + elif self.from_objects: + self.app.objects_action(direction="right") else: self.app.close_sub_map_action() @@ -117,11 +120,11 @@ class ObjectDetails(): def reload_telemetry(self, sender=None, notoast=False): if self.object_hash != None: - self.set_source(self.object_hash, from_conv=self.from_conv, from_telemetry=self.from_telemetry) + self.set_source(self.object_hash, from_conv=self.from_conv, from_objects=self.from_objects, from_telemetry=self.from_telemetry) if not notoast: toast("Reloaded telemetry for object") - def set_source(self, source_dest, from_conv=False, from_telemetry=False, prefetched=None): + def set_source(self, source_dest, from_conv=False, from_objects=False, from_telemetry=False, prefetched=None): try: self.object_hash = source_dest own_address = self.app.sideband.lxmf_destination.hash @@ -140,6 +143,19 @@ class ObjectDetails(): self.from_conv = True else: self.from_conv = False + if from_objects: + self.from_objects = True + else: + self.from_objects = False + + if self.viewing_self: + self.screen.ids.track_button.disabled = True + else: + self.screen.ids.track_button.disabled = False + if self.app.sideband.is_tracking(source_dest): + self.screen.ids.track_button.text = "Stop Live Tracking" + else: + self.screen.ids.track_button.text = "Start Live Tracking" self.coords = None self.telemetry_list.data = [] @@ -211,6 +227,15 @@ class ObjectDetails(): self.clear_widget() self.update() + def live_tracking(self, sender): + if not self.viewing_self: + if not self.app.sideband.is_tracking(self.object_hash): + self.app.sideband.start_tracking(self.object_hash, interval=59, duration=7*24*60*60) + self.screen.ids.track_button.text = "Stop Live Tracking" + else: + self.app.sideband.stop_tracking(self.object_hash) + self.screen.ids.track_button.text = "Start Live Tracking" + def send_update(self): if not self.viewing_self: result = self.app.sideband.send_latest_telemetry(to_addr=self.object_hash) @@ -298,342 +323,548 @@ class RVDetails(MDRecycleView): rendered_telemetry = [] sort = { + "Information": 5, "Physical Link": 10, "Location": 20, "Ambient Light": 30, "Ambient Temperature": 40, "Relative Humidity": 50, "Ambient Pressure": 60, + "Magnetic Field": 61, + "Gravity": 62, + "Angular Velocity": 63, + "Acceleration": 64, + "Proximity": 65, "Battery": 70, - "Timestamp": 80, - "Received": 90, - "Information": 5, + "Processor": 72, + "Random Access Memory": 74, + "Non-Volatile Memory": 76, + "Power Consumption": 80, + "Power Production": 81, + "Tank": 90, + "Fuel": 91, + "Custom": 100, + "Timestamp": 190, + "Received": 200, } + + def pass_job(sender=None): + pass + self.entries = [] rendered_telemetry.sort(key=lambda s: sort[s["name"]] if s["name"] in sort else 1000) for s in rendered_telemetry: - extra_entries = [] - def pass_job(sender=None): - pass - release_function = pass_job - formatted_values = None - name = s["name"] - if name == "Timestamp": - ts = s["values"]["UTC"] - if ts != None: - ts_str = datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") - formatted_values = f"Recorded [b]{RNS.prettytime(time.time()-ts, compact=True)} ago[/b] ({ts_str})" - def copy_info(e=None): - Clipboard.copy(ts_str) - toast("Copied to clipboard") - release_function = copy_info - elif name == "Information": - info = s["values"]["contents"] - if info != None: - istr = str(info) - def copy_info(e=None): - Clipboard.copy(istr) - toast("Copied to clipboard") - release_function = copy_info - external_text = multilingual_markup(escape_markup(istr).encode("utf-8")).decode("utf-8") - formatted_values = f"[b]Information[/b]: {external_text}" - elif name == "Received": - formatted_values = "" - by = s["values"]["by"]; - via = s["values"]["via"]; - - if by == self.app.sideband.lxmf_destination.hash: - if via == self.delegate.object_hash: - formatted_values = "Collected directly by [b]this device[/b], directly [b]from emitter[/b]" - else: - via_str = self.app.sideband.peer_display_name(via) - if via_str == None: - via_str = "an [b]unknown peer[/b]" - formatted_values = f"Collected directly by [b]this device[/b], via {via_str}" - else: - if via != None and via == by: - vstr = self.app.sideband.peer_display_name(via) - formatted_values = f"Received from, and collected by [b]{vstr}[/b]" - - else: - if via != None: - vstr = self.app.sideband.peer_display_name(via) - via_str = f"Received from [b]{vstr}[/b]" - else: - via_str = "Received from an [b]unknown peer[/b]" - - if by != None: - dstr = self.app.sideband.peer_display_name(by) - by_str = f", collected by [b]{dstr}[/b]" - else: - by_str = f", collected by an [b]unknown peer[/b]" - - formatted_values = f"{via_str}{by_str}" - - if formatted_values == "": - formatted_values = None - - if not by == self.app.sideband.lxmf_destination.hash and not self.app.sideband.is_trusted(by): - extra_entries.append({"icon": "alert", "text": "Collected by a [b]non-trusted[/b] peer"}) + try: + extra_entries = [] + release_function = pass_job + formatted_values = None + name = s["name"] - elif name == "Battery": - p = s["values"]["percent"] - cs = s["values"]["_meta"] - if cs != None: cs_str = f" ({cs})" - if p != None: formatted_values = f"{name} [b]{p}%[/b]"+cs_str - elif name == "Ambient Pressure": - p = s["values"]["mbar"] - if p != None: formatted_values = f"{name} [b]{p} mbar[/b]" - dt = "mbar" - if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: - d = s["deltas"][dt] - formatted_values += f" (╬Ф = {d} mbar)" - elif name == "Ambient Temperature": - c = s["values"]["c"] - if c != None: formatted_values = f"{name} [b]{c}┬░ C[/b]" - dt = "c" - if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: - d = s["deltas"][dt] - formatted_values += f" (╬Ф = {d}┬░ C)" - elif name == "Relative Humidity": - r = s["values"]["percent"] - if r != None: formatted_values = f"{name} [b]{r}%[/b]" - dt = "percent" - if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: - d = s["deltas"][dt] - formatted_values += f" (╬Ф = {d}%)" - elif name == "Physical Link": - rssi = s["values"]["rssi"]; rssi_str = None - snr = s["values"]["snr"]; snr_str = None - q = s["values"]["q"]; q_str = None - if q != None: q_str = f"Link Quality [b]{q}%[/b]" - if rssi != None: - rssi_str = f"RSSI [b]{rssi} dBm[/b]" - if q != None: rssi_str = ", "+rssi_str - if snr != None: - snr_str = f"SNR [b]{snr} dB[/b]" - if q != None or rssi != None: snr_str = ", "+snr_str - if q_str or rssi_str or snr_str: - formatted_values = q_str+rssi_str+snr_str - elif name == "Power Consumption": - cs = s["values"] - if cs != None: - for c in cs: - label = c["label"] - watts = c["w"] - prefix = "" - if watts < 1/1e6: - watts *= 1e9 - prefix = "n" - elif watts < 1/1e3: - watts *= 1e6 - prefix = "┬╡" - elif watts < 1: - watts *= 1e3 - prefix = "m" - elif watts >= 1e15: - watts /= 1e15 - prefix = "E" - elif watts >= 1e12: - watts /= 1e12 - prefix = "T" - elif watts >= 1e9: - watts /= 1e9 - prefix = "G" - elif watts >= 1e6: - watts /= 1e6 - prefix = "M" - elif watts >= 1e3: - watts /= 1e3 - prefix = "K" + if name == "Timestamp": + ts = s["values"]["UTC"] + if ts != None: + ts_str = datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") + formatted_values = f"Recorded [b]{RNS.prettytime(time.time()-ts, compact=True)} ago[/b] ({ts_str})" + def copy_info(e=None): + Clipboard.copy(ts_str) + toast("Copied to clipboard") + release_function = copy_info + + elif name == "Information": + info = s["values"]["contents"] + if info != None: + istr = str(info) + def copy_info(e=None): + Clipboard.copy(istr) + toast("Copied to clipboard") + release_function = copy_info + external_text = multilingual_markup(escape_markup(istr).encode("utf-8")).decode("utf-8") + formatted_values = f"[b]Information[/b]: {external_text}" + + elif name == "Received": + formatted_values = "" + by = s["values"]["by"]; + via = s["values"]["via"]; - watts = round(watts, 2) - p_text = f"{label} [b]{watts} {prefix}W[/b]" - extra_entries.append({"icon": s["icon"], "text": p_text}) - - elif name == "Power Production": - cs = s["values"] - if cs != None: - for c in cs: - label = c["label"] - watts = c["w"] - prefix = "" - if watts < 1/1e6: - watts *= 1e9 - prefix = "n" - elif watts < 1/1e3: - watts *= 1e6 - prefix = "┬╡" - elif watts < 1: - watts *= 1e3 - prefix = "m" - elif watts >= 1e15: - watts /= 1e15 - prefix = "E" - elif watts >= 1e12: - watts /= 1e12 - prefix = "T" - elif watts >= 1e9: - watts /= 1e9 - prefix = "G" - elif watts >= 1e6: - watts /= 1e6 - prefix = "M" - elif watts >= 1e3: - watts /= 1e3 - prefix = "K" - - watts = round(watts, 2) - p_text = f"{label} [b]{watts} {prefix}W[/b]" - extra_entries.append({"icon": s["icon"], "text": p_text}) - - elif name == "Location": - lat = s["values"]["latitude"] - lon = s["values"]["longitude"] - alt = s["values"]["altitude"] - speed = s["values"]["speed"] - heading = s["values"]["heading"] - accuracy = s["values"]["accuracy"] - updated = s["values"]["updated"] - updated_str = f", logged [b]{RNS.prettytime(time.time()-updated, compact=True)} ago[/b]" - - coords = f"{lat}, {lon}" - fcoords = f"{round(lat,4)}, {round(lon,4)}" - self.delegate.coords = coords - if alt == 0: - alt_str = "0" - else: - alt_str = RNS.prettydistance(alt) - formatted_values = f"Coordinates [b]{fcoords}[/b], altitude [b]{alt_str}[/b]" - if speed != None: - if speed > 0.000001: - speed_formatted_values = f"Speed [b]{speed} Km/h[/b], heading [b]{heading}┬░[/b]" - else: - speed_formatted_values = f"Speed [b]0 Km/h[/b]" - else: - speed_formatted_values = None - extra_formatted_values = f"Uncertainty [b]{accuracy} meters[/b]"+updated_str - - data = {"icon": s["icon"], "text": f"{formatted_values}"} - - extra_entries.append({"icon": "map-marker-question", "text": extra_formatted_values}) - if speed_formatted_values != None: - extra_entries.append({"icon": "speedometer", "text": speed_formatted_values}) - - if "distance" in s: - if "orthodromic" in s["distance"]: - od = s["distance"]["orthodromic"] - if od != None: - od_text = f"Geodesic distance [b]{RNS.prettydistance(od)}[/b]" - extra_entries.append({"icon": "earth", "text": od_text}) - - if "euclidian" in s["distance"]: - ed = s["distance"]["euclidian"] - if ed != None: - ed_text = f"Euclidian distance [b]{RNS.prettydistance(ed)}[/b]" - extra_entries.append({"icon": "axis-arrow", "text": ed_text}) - - if "vertical" in s["distance"]: - vd = s["distance"]["vertical"] - if vd != None: - if vd < 0: - relstr = "lower" - vd = abs(vd) - else: - relstr = "greater" - vd_text = f"Altitude is [b]{RNS.prettydistance(vd)}[/b] {relstr} than this device" - extra_entries.append({"icon": "altimeter", "text": vd_text}) - - if "angle_to_horizon" in s["values"]: - oath = s["values"]["angle_to_horizon"] - if oath != None: - if self.delegate.viewing_self: - oath_text = f"Local horizon is at [b]{round(oath,3)}┬░[/b]" + if by == self.app.sideband.lxmf_destination.hash: + if via == self.delegate.object_hash: + formatted_values = "Collected directly by [b]this device[/b], directly [b]from emitter[/b]" else: - oath_text = f"Object's horizon is at [b]{round(oath,3)}┬░[/b]" - extra_entries.append({"icon": "arrow-split-horizontal", "text": oath_text}) - - if self.delegate.viewing_self and "radio_horizon" in s["values"]: - orh = s["values"]["radio_horizon"] - if orh != None: - range_text = RNS.prettydistance(orh) - rh_formatted_text = f"Radio horizon of [b]{range_text}[/b]" - extra_entries.append({"icon": "radio-tower", "text": rh_formatted_text}) - - if "azalt" in s and "local_angle_to_horizon" in s["azalt"]: - lath = s["azalt"]["local_angle_to_horizon"] - if lath != None: - lath_text = f"Local horizon is at [b]{round(lath,3)}┬░[/b]" - extra_entries.append({"icon": "align-vertical-distribute", "text": lath_text}) - - if "azalt" in s: - azalt_formatted_text = "" - if "azimuth" in s["azalt"]: - az = s["azalt"]["azimuth"] - az_text = f"Azimuth [b]{round(az,3)}┬░[/b]" - azalt_formatted_text += az_text - - if "altitude" in s["azalt"]: - al = s["azalt"]["altitude"] - al_text = f"altitude [b]{round(al,3)}┬░[/b]" - if len(azalt_formatted_text) != 0: azalt_formatted_text += ", " - azalt_formatted_text += al_text - - extra_entries.append({"icon": "compass-rose", "text": azalt_formatted_text}) - - if "above_horizon" in s["azalt"]: - astr = "above" if s["azalt"]["above_horizon"] == True else "below" - dstr = str(round(s["azalt"]["altitude_delta"], 3)) - ah_text = f"Object is [b]{astr}[/b] the horizon (╬Ф = {dstr}┬░)" - extra_entries.append({"icon": "angle-acute", "text": ah_text}) - - if not self.delegate.viewing_self and "radio_horizon" in s["values"]: - orh = s["values"]["radio_horizon"] - if orh != None: - range_text = RNS.prettydistance(orh) - rh_formatted_text = f"Object's radio horizon is [b]{range_text}[/b]" - extra_entries.append({"icon": "radio-tower", "text": rh_formatted_text}) - - if "radio_horizon" in s: - rh_icon = "circle-outline" - crange_text = RNS.prettydistance(s["radio_horizon"]["combined_range"]) - if s["radio_horizon"]["within_range"]: - rh_formatted_text = f"[b]Within[/b] shared radio horizon of [b]{crange_text}[/b]" - rh_icon = "set-none" + via_str = self.app.sideband.peer_display_name(via) + if via_str == None: + via_str = "an [b]unknown peer[/b]" + formatted_values = f"Collected directly by [b]this device[/b], via {via_str}" else: - rh_formatted_text = f"[b]Outside[/b] shared radio horizon of [b]{crange_text}[/b]" + if via != None and via == by: + vstr = self.app.sideband.peer_display_name(via) + formatted_values = f"Received from, and collected by [b]{vstr}[/b]" + + else: + if via != None: + vstr = self.app.sideband.peer_display_name(via) + via_str = f"Received from [b]{vstr}[/b]" + else: + via_str = "Received from an [b]unknown peer[/b]" + + if by != None: + dstr = self.app.sideband.peer_display_name(by) + by_str = f", collected by [b]{dstr}[/b]" + else: + by_str = f", collected by an [b]unknown peer[/b]" + + formatted_values = f"{via_str}{by_str}" + + if formatted_values == "": + formatted_values = None + + if not by == self.app.sideband.lxmf_destination.hash and not self.app.sideband.is_trusted(by): + extra_entries.append({"icon": "alert", "text": "Collected by a [b]non-trusted[/b] peer"}) - extra_entries.append({"icon": rh_icon, "text": rh_formatted_text}) + elif name == "Battery": + p = s["values"]["percent"] + cs = s["values"]["_meta"] + t = None + if "temperature" in s["values"]: + t = s["values"]["temperature"] + if cs != None: + if t != None: + cs_str = f" ({cs}, {t}┬░ C)" + else: + cs_str = f" ({cs})" - def select(e=None): - geo_uri = f"geo:{lat},{lon}" - def lj(): - webbrowser.open(geo_uri) - threading.Thread(target=lj, daemon=True).start() - - release_function = select - else: - formatted_values = f"{name}" - for vn in s["values"]: - v = s["values"][vn] - formatted_values += f" [b]{v} {vn}[/b]" - - dt = vn + if p != None: formatted_values = f"{name} [b]{p}%[/b]"+cs_str + + elif name == "Ambient Pressure": + p = s["values"]["mbar"] + if p != None: formatted_values = f"{name} [b]{p} mbar[/b]" + dt = "mbar" if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: d = s["deltas"][dt] - formatted_values += f" (╬Ф = {d} {vn})" - - data = None - if formatted_values != None: - if release_function: - data = {"icon": s["icon"], "text": f"{formatted_values}", "on_release": release_function} - else: + formatted_values += f" (╬Ф = {d} mbar)" + + elif name == "Ambient Temperature": + c = s["values"]["c"] + if c != None: formatted_values = f"{name} [b]{c}┬░ C[/b]" + dt = "c" + if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: + d = s["deltas"][dt] + formatted_values += f" (╬Ф = {d}┬░ C)" + + elif name == "Relative Humidity": + r = s["values"]["percent"] + if r != None: formatted_values = f"{name} [b]{r}%[/b]" + dt = "percent" + if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: + d = s["deltas"][dt] + formatted_values += f" (╬Ф = {d}%)" + + elif name == "Physical Link": + rssi = s["values"]["rssi"]; rssi_str = None + snr = s["values"]["snr"]; snr_str = None + q = s["values"]["q"]; q_str = None + if q != None: q_str = f"Link Quality [b]{q}%[/b]" + if rssi != None: + rssi_str = f"RSSI [b]{rssi} dBm[/b]" + if q != None: rssi_str = ", "+rssi_str + if snr != None: + snr_str = f"SNR [b]{snr} dB[/b]" + if q != None or rssi != None: snr_str = ", "+snr_str + if q_str or rssi_str or snr_str: + formatted_values = q_str+rssi_str+snr_str + + elif name == "Power Consumption": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cicon = c["custom_icon"] + watts = c["w"] + prefix = "" + if watts < 1/1e6: + watts *= 1e9 + prefix = "n" + elif watts < 1/1e3: + watts *= 1e6 + prefix = "┬╡" + elif watts < 1: + watts *= 1e3 + prefix = "m" + elif watts >= 1e15: + watts /= 1e15 + prefix = "E" + elif watts >= 1e12: + watts /= 1e12 + prefix = "T" + elif watts >= 1e9: + watts /= 1e9 + prefix = "G" + elif watts >= 1e6: + watts /= 1e6 + prefix = "M" + elif watts >= 1e3: + watts /= 1e3 + prefix = "K" + + if cicon: + set_icon = cicon + else: + set_icon = s["icon"] + + watts = round(watts, 2) + p_text = f"{label} [b]{watts} {prefix}W[/b]" + extra_entries.append({"icon": set_icon, "text": p_text}) + + elif name == "Power Production": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cicon = c["custom_icon"] + watts = c["w"] + prefix = "" + if watts < 1/1e6: + watts *= 1e9 + prefix = "n" + elif watts < 1/1e3: + watts *= 1e6 + prefix = "┬╡" + elif watts < 1: + watts *= 1e3 + prefix = "m" + elif watts >= 1e15: + watts /= 1e15 + prefix = "E" + elif watts >= 1e12: + watts /= 1e12 + prefix = "T" + elif watts >= 1e9: + watts /= 1e9 + prefix = "G" + elif watts >= 1e6: + watts /= 1e6 + prefix = "M" + elif watts >= 1e3: + watts /= 1e3 + prefix = "K" + + if cicon: + set_icon = cicon + else: + set_icon = s["icon"] + + watts = round(watts, 2) + p_text = f"{label} [b]{watts} {prefix}W[/b]" + extra_entries.append({"icon": set_icon, "text": p_text}) + + elif name == "Custom": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cicon = c["custom_icon"] + value = str(c["value"]) + set_icon = cicon if cicon else s["icon"] + e_text = f"{label} [b]{value}[/b]" + extra_entries.append({"icon": set_icon, "text": e_text}) + + elif name == "Tank": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cicon = c["custom_icon"] + unit = c["unit"] + cap = round(c["capacity"], 1) + lvl = round(c["level"], 1) + free = round(c["free"], 1) + pct = round(c["percent"], 1) + + set_icon = cicon if cicon else s["icon"] + e_text = f"{label} level is [b]{lvl} {unit}[/b] ([b]{pct}%[/b])" + extra_entries.append({"icon": set_icon, "text": e_text}) + + elif name == "Fuel": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cicon = c["custom_icon"] + unit = c["unit"] + cap = round(c["capacity"], 1) + lvl = round(c["level"], 1) + free = round(c["free"], 1) + pct = round(c["percent"], 1) + + set_icon = cicon if cicon else s["icon"] + e_text = f"{label} level is [b]{lvl} {unit}[/b] ([b]{pct}%[/b])" + extra_entries.append({"icon": set_icon, "text": e_text}) + + elif name == "Processor": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + load = c["current_load"] + avgs = c["load_avgs"] + clock = c["clock"] + pct = round(load*100.0, 1) + + avgs_str = f", averages are [b]{round(avgs[0],2)}[/b], [b]{round(avgs[1],2)}[/b], [b]{round(avgs[2],2)}[/b]" if avgs != None and len(avgs) == 3 else "" + clock_str = " at [b]"+RNS.prettyfrequency(clock)+"[/b]" if clock != None else "" + + e_text = f"Using [b]{pct}%[/b] of {label}{clock_str}{avgs_str}" + e_text = f"{label} use is [b]{pct}%[/b]{clock_str}{avgs_str}" + extra_entries.append({"icon": s["icon"], "text": e_text}) + + elif name == "Non-Volatile Memory": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cap = RNS.prettysize(c["capacity"]) + use = RNS.prettysize(c["used"]) + free = RNS.prettysize(c["free"]) + pct = round(c["percent"], 1) + + e_text = f"{label} use is [b]{use}[/b] ([b]{pct}%[/b]) of [b]{cap}[/b], with [b]{free}[/b] free" + extra_entries.append({"icon": s["icon"], "text": e_text}) + + elif name == "Random Access Memory": + cs = s["values"] + if cs != None: + for c in cs: + label = c["label"] + cap = RNS.prettysize(c["capacity"]) + use = RNS.prettysize(c["used"]) + free = RNS.prettysize(c["free"]) + pct = round(c["percent"], 1) + + e_text = f"{label} use is [b]{use}[/b] ([b]{pct}%[/b]) of [b]{cap}[/b], with [b]{free}[/b] free" + extra_entries.append({"icon": s["icon"], "text": e_text}) + + elif name == "Location": + lat = s["values"]["latitude"] + lon = s["values"]["longitude"] + alt = s["values"]["altitude"] + speed = s["values"]["speed"] + heading = s["values"]["heading"] + accuracy = s["values"]["accuracy"] + updated = s["values"]["updated"] + updated_str = f", logged [b]{RNS.prettytime(time.time()-updated, compact=True)} ago[/b]" + + coords = f"{lat}, {lon}" + fcoords = f"{round(lat,4)}, {round(lon,4)}" + self.delegate.coords = coords + if alt == 0: + alt_str = "0" + else: + alt_str = RNS.prettydistance(alt) + formatted_values = f"Coordinates [b]{fcoords}[/b], altitude [b]{alt_str}[/b]" + if speed != None: + if speed > 0.1: + speed_formatted_values = f"Speed [b]{speed} Km/h[/b], heading [b]{heading}┬░[/b]" + else: + speed_formatted_values = f"Object is [b]stationary[/b]" + else: + speed_formatted_values = None + extra_formatted_values = f"Uncertainty [b]{accuracy} meters[/b]"+updated_str + data = {"icon": s["icon"], "text": f"{formatted_values}"} - if data != None: - self.entries.append(data) - for extra in extra_entries: - self.entries.append(extra) + extra_entries.append({"icon": "map-marker-question", "text": extra_formatted_values}) + if speed_formatted_values != None: + extra_entries.append({"icon": "speedometer", "text": speed_formatted_values}) + + if "distance" in s: + if "orthodromic" in s["distance"]: + od = s["distance"]["orthodromic"] + if od != None: + od_text = f"Geodesic distance [b]{RNS.prettydistance(od)}[/b]" + extra_entries.append({"icon": "earth", "text": od_text}) + + if "euclidian" in s["distance"]: + ed = s["distance"]["euclidian"] + if ed != None: + ed_text = f"Euclidian distance [b]{RNS.prettydistance(ed)}[/b]" + extra_entries.append({"icon": "axis-arrow", "text": ed_text}) + + if "vertical" in s["distance"]: + vd = s["distance"]["vertical"] + if vd != None: + if vd < 0: + relstr = "lower" + vd = abs(vd) + else: + relstr = "greater" + vd_text = f"Altitude is [b]{RNS.prettydistance(vd)}[/b] {relstr} than this device" + extra_entries.append({"icon": "altimeter", "text": vd_text}) + + if "angle_to_horizon" in s["values"]: + oath = s["values"]["angle_to_horizon"] + if oath != None: + if self.delegate.viewing_self: + oath_text = f"Local horizon is at [b]{round(oath,3)}┬░[/b]" + else: + oath_text = f"Object's horizon is at [b]{round(oath,3)}┬░[/b]" + extra_entries.append({"icon": "arrow-split-horizontal", "text": oath_text}) + + if self.delegate.viewing_self and "radio_horizon" in s["values"]: + orh = s["values"]["radio_horizon"] + if orh != None: + range_text = RNS.prettydistance(orh) + rh_formatted_text = f"Radio horizon of [b]{range_text}[/b]" + extra_entries.append({"icon": "radio-tower", "text": rh_formatted_text}) + + if "azalt" in s and "local_angle_to_horizon" in s["azalt"]: + lath = s["azalt"]["local_angle_to_horizon"] + if lath != None: + lath_text = f"Local horizon is at [b]{round(lath,3)}┬░[/b]" + extra_entries.append({"icon": "align-vertical-distribute", "text": lath_text}) + + if "azalt" in s: + azalt_formatted_text = "" + if "azimuth" in s["azalt"]: + az = s["azalt"]["azimuth"] + az_text = f"Azimuth [b]{round(az,3)}┬░[/b]" + azalt_formatted_text += az_text + + if "altitude" in s["azalt"]: + al = s["azalt"]["altitude"] + al_text = f"altitude [b]{round(al,3)}┬░[/b]" + if len(azalt_formatted_text) != 0: azalt_formatted_text += ", " + azalt_formatted_text += al_text + + extra_entries.append({"icon": "compass-rose", "text": azalt_formatted_text}) + + if "above_horizon" in s["azalt"]: + astr = "above" if s["azalt"]["above_horizon"] == True else "below" + dstr = str(round(s["azalt"]["altitude_delta"], 3)) + ah_text = f"Object is [b]{astr}[/b] the horizon (╬Ф = {dstr}┬░)" + extra_entries.append({"icon": "angle-acute", "text": ah_text}) + + if not self.delegate.viewing_self and "radio_horizon" in s["values"]: + orh = s["values"]["radio_horizon"] + if orh != None: + range_text = RNS.prettydistance(orh) + rh_formatted_text = f"Object's radio horizon is [b]{range_text}[/b]" + extra_entries.append({"icon": "radio-tower", "text": rh_formatted_text}) + + if "radio_horizon" in s: + rh_icon = "circle-outline" + crange_text = RNS.prettydistance(s["radio_horizon"]["combined_range"]) + if s["radio_horizon"]["within_range"]: + rh_formatted_text = f"[b]Within[/b] shared radio horizon of [b]{crange_text}[/b]" + rh_icon = "set-none" + else: + rh_formatted_text = f"[b]Outside[/b] shared radio horizon of [b]{crange_text}[/b]" + + extra_entries.append({"icon": rh_icon, "text": rh_formatted_text}) + + def select(e=None): + geo_uri = f"geo:{lat},{lon}" + def lj(): + webbrowser.open(geo_uri) + 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"]: + v = s["values"][vn] + formatted_values += f" [b]{v} {vn}[/b]" + + dt = vn + if "deltas" in s and dt in s["deltas"] and s["deltas"][dt] != None: + d = s["deltas"][dt] + formatted_values += f" (╬Ф = {d} {vn})" + + formatted_values += ", " + formatted_values = formatted_values[:-2] + + data = None + if formatted_values != None: + if release_function: + data = {"icon": s["icon"], "text": f"{formatted_values}", "on_release": release_function} + else: + data = {"icon": s["icon"], "text": f"{formatted_values}", "on_release": pass_job} + + if data != None: + self.entries.append(data) + for extra in extra_entries: + self.entries.append(extra) + + except Exception as e: + RNS.log("An error ocurred while displaying telemetry for object", RNS.LOG_ERROR) + RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR) + RNS.trace_exception(e) + + try: + ratchet_id = RNS.Identity.current_ratchet_id(self.delegate.object_hash) + if ratchet_id: + self.entries.append({"icon": "lock-check-outline", "text": f"Using ratchet [b]{RNS.prettyhexrep(ratchet_id)}[/b]", "on_release": pass_job}) + + except Exception as e: + RNS.trace_exception(e) + + try: + nh = RNS.Transport.hops_to(self.delegate.object_hash) + nhi = self.delegate.app.sideband.reticulum.get_next_hop_if_name(self.delegate.object_hash) + if nhi and nhi != "None": + self.entries.append({"icon": "routes", "text": f"Current path on [b]{nhi}[/b]", "on_release": pass_job}) + + 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) + 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) + + except Exception as e: + RNS.trace_exception(e) + + try: + ticket_expires = self.delegate.app.sideband.message_router.get_outbound_ticket_expiry(self.delegate.object_hash) + stamp_cost = self.delegate.app.sideband.message_router.get_outbound_stamp_cost(self.delegate.object_hash) + t_str = "" + if ticket_expires: + t_str = ", but have ticket" + if stamp_cost: + self.entries.append({"icon": "postage-stamp", "text": f"Required stamp cost [b]{stamp_cost}[/b]"+t_str, "on_release": pass_job}) + else: + self.entries.append({"icon": "postage-stamp", "text": f"No required stamp cost", "on_release": pass_job}) + if ticket_expires: + valid_for = ticket_expires - time.time() + self.entries.append({"icon": "ticket-confirmation", "text": f"Delivery ticket valid for [b]{RNS.prettytime(valid_for)}[/b]", "on_release": pass_job}) + + except Exception as e: + RNS.trace_exception(e) if len(self.entries) == 0: self.entries.append({"icon": "timeline-question-outline", "text": f"No telemetry available for this device"}) @@ -781,22 +1012,22 @@ MDScreen: on_release: root.delegate.request_update() disabled: False - # MDBoxLayout: - # orientation: "horizontal" - # spacing: dp(16) - # size_hint_y: None - # height: self.minimum_height - # padding: [dp(24), dp(16), dp(24), dp(24)] + MDBoxLayout: + orientation: "horizontal" + spacing: dp(16) + size_hint_y: None + height: self.minimum_height + padding: [dp(24), dp(0), dp(24), dp(24)] - # MDRectangleFlatIconButton: - # id: delete_button - # icon: "trash-can-outline" - # text: "Delete All Telemetry" - # 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.copy_telemetry(self) - # disabled: False + MDRectangleFlatIconButton: + id: track_button + icon: "crosshairs-gps" + text: "Start Live Tracking" + 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.live_tracking(self) + disabled: False """ \ No newline at end of file diff --git a/sbapp/ui/telemetry.py b/sbapp/ui/telemetry.py index 209edd8..1215bd3 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: @@ -366,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"]) @@ -434,14 +468,16 @@ 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: - self.app.sideband.config["telemetry_s_information"] = self.sensors_screen.ids.telemetry_s_information.active run_telemetry_update = True + self.app.sideband.config["telemetry_s_information"] = self.sensors_screen.ids.telemetry_s_information.active if self.app.sideband.config["telemetry_s_information_text"] != self.sensors_screen.ids.telemetry_s_information_text.text: - self.app.sideband.config["telemetry_s_information_text"] = self.sensors_screen.ids.telemetry_s_information_text.text run_telemetry_update = True + self.app.sideband.config["telemetry_s_information_text"] = self.sensors_screen.ids.telemetry_s_information_text.text + try: alt = float(self.sensors_screen.ids.telemetry_s_fixed_altitude.text.strip().replace(" ", "")) @@ -879,6 +915,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: "\\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] + + 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" @@ -1210,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 @@ -1275,7 +1410,7 @@ MDScreen: MDTextField: id: telemetry_s_fixed_altitude size_hint: [0.382, None] - hint_text: "Altitude" + hint_text: "Ellipsoid Height (GPS Altitude)" text: "" font_size: dp(24) diff --git a/sbapp/ui/utilities.py b/sbapp/ui/utilities.py new file mode 100644 index 0000000..aa8da1b --- /dev/null +++ b/sbapp/ui/utilities.py @@ -0,0 +1,492 @@ +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 Utilities(): + 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("utilities_screen"): + self.screen = Builder.load_string(layout_utilities_screen) + self.screen.app = self.app + self.screen.delegate = self + self.app.root.ids.screen_manager.add_widget(self.screen) + + 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." + + if self.app.theme_cls.theme_style == "Dark": + info = "[color=#"+self.app.dark_theme_text_color+"]"+info+"[/color]" + + self.screen.ids.utilities_info.text = info + + + ### RNode Flasher + ###################################### + + def flasher_action(self, sender=None): + yes_button = MDRectangleFlatButton(text="Launch",font_size=dp(18), theme_text_color="Custom", line_color=self.app.color_accept, text_color=self.app.color_accept) + no_button = MDRectangleFlatButton(text="Back",font_size=dp(18)) + dialog = MDDialog( + title="RNode Flasher", + text="You can use the included web-based RNode flasher, by starting Sideband's built-in repository server, and accessing the RNode Flasher page.", + buttons=[ no_button, yes_button ], + # elevation=0, + ) + def dl_yes(s): + dialog.dismiss() + self.app.wants_flasher_launch = True + self.app.sideband.start_webshare() + def cb(dt): + self.app.repository_action() + Clock.schedule_once(cb, 0.6) + + def dl_no(s): + dialog.dismiss() + + yes_button.bind(on_release=dl_yes) + no_button.bind(on_release=dl_no) + dialog.open() + + + ### rnstatus screen + ###################################### + + 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) + + self.update_rnstatus() + + 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 + self.rnstatus_instance = rnstatus + + import io + from contextlib import redirect_stdout + output = "None" + with io.StringIO() as buffer, redirect_stdout(buffer): + with RNS.logging_lock: + self.rnstatus_instance.main(rns_instance=RNS.Reticulum.get_instance()) + output = buffer.getvalue() + + def cb(dt): + self.rnstatus_screen.ids.rnstatus_output.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]{output}[/size][/font]" + Clock.schedule_once(cb, 0.2) + + if self.app.root.ids.screen_manager.current == "rnstatus_screen": + Clock.schedule_once(self.update_rnstatus, 1) + + ### Advanced Configuration screen + ###################################### + + def advanced_action(self, sender=None): + if not self.app.root.ids.screen_manager.has_screen("advanced_screen"): + self.advanced_screen = Builder.load_string(layout_advanced_screen) + self.advanced_screen.app = self.app + self.advanced_screen.delegate = self + self.app.root.ids.screen_manager.add_widget(self.advanced_screen) + + self.app.root.ids.screen_manager.transition.direction = "left" + self.app.root.ids.screen_manager.current = "advanced_screen" + self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) + + self.update_advanced() + + def update_advanced(self, sender=None): + if RNS.vendor.platformutils.is_android(): + ct = self.app.sideband.config["config_template"] + if ct == None: + ct = self.app.sideband.default_config_template + self.advanced_screen.ids.config_template.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]{ct}[/size][/font]" + else: + self.advanced_screen.ids.config_template.text = f"[font=RobotoMono-Regular][size={int(dp(12))}]On this platform, Reticulum configuration is managed by the system. You can change the configuration by editing the file located at:\n\n{self.app.sideband.reticulum.configpath}[/size][/font]" + + def reset_config(self, sender=None): + if RNS.vendor.platformutils.is_android(): + self.app.sideband.config["config_template"] = None + self.app.sideband.save_configuration() + self.update_advanced() + + def copy_config(self, sender=None): + if RNS.vendor.platformutils.is_android(): + if self.app.sideband.config["config_template"]: + Clipboard.copy(self.app.sideband.config["config_template"]) + else: + Clipboard.copy(self.app.sideband.default_config_template) + + def paste_config(self, sender=None): + if RNS.vendor.platformutils.is_android(): + self.app.sideband.config_template = Clipboard.paste() + self.app.sideband.config["config_template"] = self.app.sideband.config_template + self.app.sideband.save_configuration() + self.update_advanced() + + ### Log viewer screen + ###################################### + + def logviewer_action(self, sender=None): + if not self.app.root.ids.screen_manager.has_screen("logviewer_screen"): + self.logviewer_screen = Builder.load_string(layout_logviewer_screen) + self.logviewer_screen.app = self.app + self.logviewer_screen.delegate = self + self.app.root.ids.screen_manager.add_widget(self.logviewer_screen) + + self.app.root.ids.screen_manager.transition.direction = "left" + self.app.root.ids.screen_manager.current = "logviewer_screen" + self.app.sideband.setstate("app.displaying", self.app.root.ids.screen_manager.current) + + self.update_logviewer() + + def update_logviewer(self, sender=None): + 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}" + + 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): + 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": + Clock.schedule_once(self.update_logviewer, 1) + + def logviewer_copy(self, sender=None): + Clipboard.copy(self.logviewer_screen.log_contents) + if True or RNS.vendor.platformutils.is_android(): + toast("Log copied to clipboard") + + +layout_utilities_screen = """ +MDScreen: + name: "utilities_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + title: "Utilities" + 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: utilities_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: utilities_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 + + MDRectangleFlatIconButton: + id: logview_button + icon: "list-box-outline" + text: "Log Viewer" + 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.logviewer_action(self) + disabled: False + + MDRectangleFlatIconButton: + id: flasher_button + icon: "radio-handheld" + text: "RNode Flasher" + 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.flasher_action(self) + disabled: False + + MDRectangleFlatIconButton: + id: advanced_button + icon: "network-pos" + text: "Advanced RNS Configuration" + padding: [dp(0), dp(14), dp(0), dp(14)] + icon_size: dp(24) + font_size: dp(16) + size_hint: [1.0, None] + on_release: root.delegate.advanced_action(self) + disabled: False + +""" + +layout_rnstatus_screen = """ +MDScreen: + name: "rnstatus_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + id: top_bar + title: "Reticulum Status" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + right_action_items: + [ + # ['refresh', lambda x: root.delegate.update_rnstatus()], + ['close', lambda x: root.delegate.close_rnstatus_action(self)], + ] + + MDScrollView: + id: rnstatus_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 + + MDGridLayout: + cols: 1 + padding: [dp(28), dp(14), dp(28), dp(28)] + size_hint_y: None + height: self.minimum_height + + MDLabel: + id: rnstatus_output + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] +""" + +layout_logviewer_screen = """ +MDScreen: + name: "logviewer_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + id: top_bar + title: "Log Viewer" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + right_action_items: + [ + ['content-copy', lambda x: root.delegate.logviewer_copy()], + ['close', lambda x: root.app.close_sub_utilities_action(self)], + ] + + MDScrollView: + id: logviewer_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 + + MDGridLayout: + cols: 1 + padding: [dp(28), dp(14), dp(28), dp(28)] + size_hint_y: None + height: self.minimum_height + + MDLabel: + id: logviewer_output + markup: True + text: "" + 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 = """ +MDScreen: + name: "advanced_screen" + + BoxLayout: + orientation: "vertical" + + MDTopAppBar: + id: top_bar + title: "RNS Configuration" + anchor_title: "left" + elevation: 0 + left_action_items: + [['menu', lambda x: root.app.nav_drawer.set_state("open")]] + right_action_items: + [ + # ['refresh', lambda x: root.delegate.update_rnstatus()], + ['close', lambda x: root.app.close_sub_utilities_action(self)], + ] + + MDScrollView: + id: advanced_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 + + MDGridLayout: + cols: 1 + padding: [dp(28), dp(14), dp(28), dp(28)] + size_hint_y: None + height: self.minimum_height + + MDBoxLayout: + orientation: "horizontal" + spacing: dp(24) + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(14), dp(0), dp(24)] + + MDRectangleFlatIconButton: + id: conf_copy_button + icon: "content-copy" + text: "Copy Configuration" + padding: [dp(0), dp(14), dp(0), dp(14)] + icon_size: dp(24) + font_size: dp(16) + size_hint: [1.0, None] + on_release: root.delegate.copy_config(self) + disabled: False + + MDRectangleFlatIconButton: + id: conf_paste_button + icon: "download" + text: "Paste Configuration" + padding: [dp(0), dp(14), dp(0), dp(14)] + icon_size: dp(24) + font_size: dp(16) + size_hint: [1.0, None] + on_release: root.delegate.paste_config(self) + disabled: False + + MDBoxLayout: + orientation: "horizontal" + spacing: dp(24) + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(0), dp(0), dp(24)] + + MDRectangleFlatIconButton: + id: conf_reset_button + icon: "cog-counterclockwise" + text: "Reset Configuration" + padding: [dp(0), dp(14), dp(0), dp(14)] + icon_size: dp(24) + font_size: dp(16) + size_hint: [1.0, None] + on_release: root.delegate.reset_config(self) + disabled: False + + MDLabel: + id: config_template + markup: True + text: "" + size_hint_y: None + text_size: self.width, None + height: self.texture_size[1] +""" diff --git a/sbapp/ui/voice.py b/sbapp/ui/voice.py new file mode 100644 index 0000000..b54fb10 --- /dev/null +++ b/sbapp/ui/voice.py @@ -0,0 +1,752 @@ +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 +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_date + from android.permissions import request_permissions, check_permission +else: + 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 + +from LXST.Primitives.Telephony import Telephone, Profiles + +class Voice(): + def __init__(self, app): + self.app = app + self.screen = None + self.settings_screen = None + self.dial_target = None + self.ui_updater = None + 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 = [] + 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) + self.screen.app = self.app + self.screen.delegate = self + self.app.root.ids.screen_manager.add_widget(self.screen) + self.update_call_log() + + 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() + self.ui_updater = None + + 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: + db.disabled = True + rb.disabled = True + ih.disabled = True + + else: + 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 + 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 + + 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 + + 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 + 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() + + 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, profile=self.call_profile) + 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 call_profile_action(self, sender=None): + 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() + 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 + 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: + 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: + 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) + 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: + 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() + + self.initial_call_profile = None + + + ### 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): + 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) + + 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() + + # 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: + 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" + 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: + 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" + 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: + 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" + device_button.device = device + 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.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 + 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"]) + + + ### 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): + 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") + + 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)) + + 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) + + 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): + owner = 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.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 + + 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" + + 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: + [ + ['wrench-cog', lambda x: root.delegate.settings_action(self)], + ['close', lambda x: root.app.close_any_action(self)], + ] + + MDBoxLayout: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: [dp(28), dp(12), dp(28), dp(16)] + + 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) + + MDBoxLayout: + orientation: "vertical" + spacing: "24dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(35), dp(0), dp(14)] + + 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 + 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) + + 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 = """ +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(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 + + 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" + padding: [dp(0), dp(96), dp(0), dp(12)] + + 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(64), dp(0), dp(32)] + + MDLabel: + text: "[b]Output[/b]" + font_size: dp(18) + markup: True + + MDBoxLayout: + id: output_devices + orientation: "vertical" + spacing: "12dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(24), 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: "[b]Input[/b]" + font_size: dp(18) + markup: True + + MDBoxLayout: + id: input_devices + orientation: "vertical" + spacing: "12dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(24), dp(0), dp(48)] + + MDLabel: + text: "[b]Ringer[/b]" + font_size: dp(18) + markup: True + + MDBoxLayout: + id: ringer_devices + orientation: "vertical" + spacing: "12dp" + size_hint_y: None + height: self.minimum_height + padding: [dp(0), dp(24), dp(0), dp(48)] + +""" \ No newline at end of file diff --git a/setup.py b/setup.py index e20929c..cd8e2e8 100644 --- a/setup.py +++ b/setup.py @@ -30,7 +30,7 @@ def get_variant() -> str: version = re.findall(version_regex, version_file_data, re.M)[0] return version except IndexError: - raise ValueError(f"Unable to find version string in {version_file}.") + return None __version__ = get_version() __variant__ = get_variant() @@ -47,6 +47,27 @@ def glob_paths(pattern): return out_files +def glob_share(): + out_files = [] + src_path = os.path.join(os.path.dirname(__file__), "sbapp/share") + print(src_path) + + for root, dirs, files in os.walk(src_path): + for file in files: + filepath = os.path.join(str(Path(*Path(root).parts[1:])), file) + + if not "mirrors/unsigned.io" in str(filepath): + out_files.append(filepath.split(f"sbapp{os.sep}")[1]) + + return out_files + +packages = setuptools.find_packages( + exclude=[ + "sbapp.plyer.platforms.android", + "sbapp.kivymd.tools" + "sbapp.kivymd.tools.*" + ]) + package_data = { "": [ "assets/*", @@ -56,11 +77,15 @@ package_data = { "kivymd/images/*", "kivymd/*", "mapview/icons/*", + *glob_share(), *glob_paths(".kv") ] } -print("Packaging Sideband "+__version__+" "+__variant__) +variant_str = "" +if __variant__: + variant_str = " "+__variant__ +print("Packaging Sideband "+__version__+variant_str) setuptools.setup( name="sbapp", @@ -71,7 +96,7 @@ setuptools.setup( long_description=long_description, long_description_content_type="text/markdown", url="https://unsigned.io/sideband", - packages=setuptools.find_packages(), + packages=packages, package_data=package_data, include_package_data=True, classifiers=[ @@ -79,14 +104,30 @@ setuptools.setup( "License :: Other/Proprietary License", "Operating System :: OS Independent", ], + data_files = [ + ('share/applications', ['sbapp/assets/io.unsigned.sideband.desktop']), + ('share/icons/hicolor/512x512/apps', ['sbapp/assets/io.unsigned.sideband.png']), + ], entry_points= { 'console_scripts': [ 'sideband=sbapp:main.run', ] }, - install_requires=["rns>=0.7.3", "lxmf>=0.4.3", "kivy>=2.3.0", "plyer", "pillow>=10.2.0", "qrcode", "materialyoucolor>=2.0.7"], - extras_require={ - "macos": ["pyobjus"], - }, + install_requires=[ + "rns>=1.2.0", + "lxmf>=0.9.6", + "lxst>=0.4.6", + "kivy>=2.3.0", + "numpy>=2.0.0", + "pillow>=10.2.0", + "mistune>=3.0.2", + "qrcode", + "materialyoucolor>=2.0.7", + "beautifulsoup4", + "pycodec2>=4.1.0", + "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', ) diff --git a/sideband.spec b/sideband.spec new file mode 100644 index 0000000..260aa4d --- /dev/null +++ b/sideband.spec @@ -0,0 +1,69 @@ +# -*- mode: python ; coding: utf-8 -*- + +from kivy_deps import sdl2, glew + +a = Analysis( + ['main.py'], + pathex=[], + binaries=[], + datas=[], + hiddenimports=["mistune", "bs4"], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=[], + noarchive=False, + optimize=0, +) +pyz = PYZ(a.pure) + +def extra_datas(mydir): + def rec_glob(p, files): + import os + import glob + for d in glob.glob(p): + if os.path.isfile(d): + files.append(d) + rec_glob("%s/*" % d, files) + files = [] + rec_glob("%s/*" % mydir, files) + extra_datas = [] + for f in files: + extra_datas.append((f, f, 'DATA')) + + return extra_datas + +a.datas += extra_datas('sbapp') +a.datas += extra_datas('RNS') +a.datas += extra_datas('LXMF') +a.datas += extra_datas('LXST') + +exe = EXE( + pyz, + a.scripts, + [], + exclude_binaries=True, + name='Sideband', + icon="sbapp\\assets\\icon.png", + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + console=False, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +) + +coll = COLLECT( + exe, + a.binaries, + a.datas, + *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)], + strip=False, + upx=True, + upx_exclude=[], + name='main', +) diff --git a/sideband_1.9.5.rsm b/sideband_1.9.5.rsm new file mode 100644 index 0000000..373843f Binary files /dev/null and b/sideband_1.9.5.rsm differ diff --git a/sideband_1.9.6.rsm b/sideband_1.9.6.rsm new file mode 100644 index 0000000..440a724 Binary files /dev/null and b/sideband_1.9.6.rsm differ 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