From bab4f35fc5c13341fb9cc96a7cb863c5cd5c3f53 Mon Sep 17 00:00:00 2001 From: P. J. McDermott Date: Sun, 01 Oct 2023 16:32:49 -0400 Subject: New upstream version 0.9.9 --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..080b8b0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,135 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Flatpak +.flatpak-builder/ +build-dir/ +repo/ + diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..de288e1 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.formatting.provider": "black" +} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c84a821 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +FROM ubuntu:21.04 + +ENV DEBIAN_FRONTEND="noninteractive" TZ=" America/Los_Angeles" + +# xvfb is used to mock out the display for testing and is not required for real builds +RUN apt update && apt install -y \ + libgtk-3-dev python3-pip meson python3-dbus gtk-update-icon-cache desktop-file-utils gettext appstream-util libglib2.0-dev && \ + apt install -y xvfb && \ + rm -rf /var/lib/apt/lists/* && apt clean + +RUN pip3 install gatt requests black + +COPY . /siglo + +WORKDIR /siglo + +RUN pwd && ls && mkdir -p ./build && \ + meson --reconfigure ./build/ && \ + cd ./build && ninja install + +CMD ["/bin/bash"] + +# Once the container is running, you should have all the dependencies you need +# Start system dbus, then kickoff the app. For more details, you can see GTK's setup: +# https://gitlab.gnome.org/GNOME/gtk/-/blob/fb052c8d2546706b49e5adb87bc88ad600f31752/.gitlab-ci.yml#L122 +# +# /etc/init.d/dbus start && dbus-run-session xvfb-run -a -s "-screen 0 1024x768x24" siglo diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..94dc20f --- /dev/null +++ b/README.md @@ -0,0 +1,110 @@ +# siglo + +GTK app to sync InfiniTime watch with PinePhone + +'siglo' means century in Spanish + +## Requirements +Gtk >= 3.30 + +## Download and Install +[Download the latest stable version from Flathub](https://flathub.org/apps/details/com.github.theironrobin.siglo) (Warning: SMS Notifications currently broken in flatpak https://github.com/theironrobin/siglo/issues/80). + +### Alpine +Works for Alpine and other Alpine-based distribution, such as [postmarketOS](https://postmarketos.org/). + +```sh +sudo apk add gettext glib-dev meson py3-dbus py3-pip python3 +pip3 install gatt +``` + +### Arch Linux + +```sh +sudo pacman -S --needed meson python-pip base-devel bluez bluez-utils dbus-python python-gobject +pip3 install gatt +``` + +### Fedora + +``` +sudo dnf install meson glib2-devel +pip3 install gatt +``` + +### Ubuntu + +```sh +sudo apt install libgtk-3-dev python3-pip meson python3-dbus gtk-update-icon-cache desktop-file-utils gettext appstream-util libglib2.0-dev +pip3 install gatt requests black +``` + +## Build/Install + +``` +git clone https://github.com/theironrobin/siglo.git +cd siglo +mkdir build +meson build/ +cd build +sudo ninja install +``` + +### Mocked Testing with Docker + +While you won't get bluetooth connectivity, you can get some high-level vetting in a container, which +will open the way forward to better CI testing on GitHub. + +The [`Dockerfile`](Dockerfile) contains all required dependencies, in addition to +[`xvfb`](https://www.x.org/releases/X11R7.6/doc/man/man1/Xvfb.1.xhtml) which allows us to make sure +the app can execute. + +```sh +sudo docker build . --tag siglo; and sudo docker run --name siglo --volume (pwd):/siglo --rm -it siglo:latest +``` + +Once the container is running, you can launch the app: + +```sh +/etc/init.d/dbus start && dbus-run-session xvfb-run -a -s "-screen 0 1024x768x24" siglo +``` + +## Building and installing Flatpak app + +### Building and installing on target architecture + +```sh +flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo +flatpak install --user flathub org.gnome.Sdk//42 org.gnome.Platform//42 + +flatpak-builder --user --install --repo=repo --force-clean build-dir/ com.github.theironrobin.siglo.json +``` + +### Cross-compiling for PinePhone + +Example cross-compiling for PinePhone on an `x86_64` Fedora machine: + +```sh +sudo dnf install qemu-system-arm qemu-user-static +flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo +flatpak install --user flathub org.gnome.Sdk/aarch64/42 org.gnome.Platform/aarch64/42 + +flatpak-builder --arch=aarch64 --repo=repo --force-clean build-dir com.github.theironrobin.siglo.json +flatpak build-bundle --arch=aarch64 ./repo/ siglo.flatpak com.github.theironrobin.siglo +``` + +Transfer the `siglo.flatpak` file on the PinePhone and install it with the following command: + +```sh +sudo flatpak install ./siglo.flatpak +``` + +## + +If this project helped you, you can buy me a cup of coffee :) +

+[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/theironrobin) +

+DOGE address: DLDNfkXoJeueb2GRx4scnmRc12SX1H22VW + +Icons by svgrepo.com diff --git a/build-aux/meson/postinstall.py b/build-aux/meson/postinstall.py new file mode 100755 index 0000000..6a3ea97 --- /dev/null +++ b/build-aux/meson/postinstall.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +from os import environ, path +from subprocess import call + +prefix = environ.get('MESON_INSTALL_PREFIX', '/usr/local') +datadir = path.join(prefix, 'share') +destdir = environ.get('DESTDIR', '') + +# Package managers set this so we don't need to run +if not destdir: + print('Updating icon cache...') + call(['gtk-update-icon-cache', '-qtf', path.join(datadir, 'icons', 'hicolor')]) + + print('Updating desktop database...') + call(['update-desktop-database', '-q', path.join(datadir, 'applications')]) + + print('Compiling GSettings schemas...') + call(['glib-compile-schemas', path.join(datadir, 'glib-2.0', 'schemas')]) + + diff --git a/com.github.theironrobin.siglo.json b/com.github.theironrobin.siglo.json new file mode 100644 index 0000000..5c04c79 --- /dev/null +++ b/com.github.theironrobin.siglo.json @@ -0,0 +1,41 @@ +{ + "app-id" : "com.github.theironrobin.siglo", + "runtime" : "org.gnome.Platform", + "runtime-version" : "42", + "sdk" : "org.gnome.Sdk", + "command" : "siglo", + "finish-args" : [ + "--allow=bluetooth", + "--share=network", + "--share=ipc", + "--socket=fallback-x11", + "--system-talk-name=org.bluez", + "--socket=wayland" + ], + "cleanup" : [ + "/include", + "/lib/pkgconfig", + "/man", + "/share/doc", + "/share/gtk-doc", + "/share/man", + "/share/pkgconfig", + "*.la", + "*.a" + ], + "modules" : [ + "python3-modules.json", + { + "name" : "siglo", + "builddir" : true, + "buildsystem" : "meson", + "sources" : [ + { + "type" : "git", + "url" : "https://github.com/theironrobin/siglo", + "tag" : "v0.9.9" + } + ] + } + ] +} diff --git a/data/com.github.theironrobin.siglo.appdata.xml.in b/data/com.github.theironrobin.siglo.appdata.xml.in new file mode 100644 index 0000000..e24c5fc --- /dev/null +++ b/data/com.github.theironrobin.siglo.appdata.xml.in @@ -0,0 +1,50 @@ + + + com.github.theironrobin.siglo.desktop + Siglo + Sync PineTime with your PinePhone + CC0-1.0 + MPL-2.0 + Alex R + +

+ Features: +

    +
  • Scan for one or more InfiniTime devices
  • +
  • Sync the time
  • +
  • Update your firmware—either manually or directly from the InfiniTime release page
  • +
  • Optionally Keep Paired for Chatty notifications (currently broken in flatpak)
  • +
+

+

+ Supports all Phosh-based PinePhone distros. +

+
+ + Utility + + https://github.com/theironrobin/siglo + + + https://ironrobin.net/images/siglo-screenshot-1.png + + + https://ironrobin.net/images/siglo-screenshot-2.png + + + https://ironrobin.net/images/siglo-screenshot-3.png + + + + + + + + + + + + workstation + mobile + +
diff --git a/data/com.github.theironrobin.siglo.desktop.in b/data/com.github.theironrobin.siglo.desktop.in new file mode 100644 index 0000000..4e5cac1 --- /dev/null +++ b/data/com.github.theironrobin.siglo.desktop.in @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=Siglo +Exec=siglo +Terminal=false +Type=Application +Categories=GTK; +StartupNotify=true +Icon=com.github.theironrobin.siglo +X-Purism-FormFactor=Workstation;Mobile; diff --git a/data/com.github.theironrobin.siglo.gschema.xml b/data/com.github.theironrobin.siglo.gschema.xml new file mode 100644 index 0000000..76f3413 --- /dev/null +++ b/data/com.github.theironrobin.siglo.gschema.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/data/icons/com.github.theironrobin.siglo.svg b/data/icons/com.github.theironrobin.siglo.svg new file mode 100644 index 0000000..72415aa --- /dev/null +++ b/data/icons/com.github.theironrobin.siglo.svg @@ -0,0 +1,153 @@ + +image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/meson.build b/data/meson.build new file mode 100644 index 0000000..25d0c11 --- /dev/null +++ b/data/meson.build @@ -0,0 +1,48 @@ +desktop_file = i18n.merge_file( + input: 'com.github.theironrobin.siglo.desktop.in', + output: 'com.github.theironrobin.siglo.desktop', + type: 'desktop', + po_dir: '../po', + install: true, + install_dir: join_paths(get_option('datadir'), 'applications') +) + +desktop_utils = find_program('desktop-file-validate', required: false) +if desktop_utils.found() + test('Validate desktop file', desktop_utils, + args: [desktop_file] + ) +endif + +install_data(join_paths('icons', 'com.github.theironrobin.siglo.svg'), + install_dir: join_paths(get_option('datadir'), 'icons/hicolor/scalable/apps') +) + +install_data('siglo.service', install_dir: '/etc/systemd/user/') + +appstream_file = i18n.merge_file( + input: 'com.github.theironrobin.siglo.appdata.xml.in', + output: 'com.github.theironrobin.siglo.appdata.xml', + po_dir: '../po', + install: true, + install_dir: join_paths(get_option('datadir'), 'metainfo') +) + +appstream_util = find_program('appstream-util', required: false) +if appstream_util.found() + test('Validate appstream file', appstream_util, + args: ['validate', appstream_file] + ) +endif + +install_data('com.github.theironrobin.siglo.gschema.xml', + install_dir: join_paths(get_option('datadir'), 'glib-2.0/schemas') +) + +compile_schemas = find_program('glib-compile-schemas', required: false) +if compile_schemas.found() + test('Validate schema file', compile_schemas, + args: ['--strict', '--dry-run', meson.current_source_dir()] + ) +endif + diff --git a/data/siglo.service b/data/siglo.service new file mode 100644 index 0000000..fde41b6 --- /dev/null +++ b/data/siglo.service @@ -0,0 +1,6 @@ +[Unit] +Description=siglo service +[Service] +ExecStart=siglo --start +ExecStop=siglo --stop +Environment=PYTHONUNBUFFERED=1 diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..5f7b862 --- /dev/null +++ b/meson.build @@ -0,0 +1,15 @@ +project('siglo', + version: '0.1.0', + meson_version: '>= 0.55.0', + default_options: [ 'warning_level=2', + ], +) + +i18n = import('i18n') + + +subdir('data') +subdir('src') +subdir('po') + +meson.add_install_script('build-aux/meson/postinstall.py') \ No newline at end of file diff --git a/po/LINGUAS b/po/LINGUAS new file mode 100644 index 0000000..267a150 --- /dev/null +++ b/po/LINGUAS @@ -0,0 +1 @@ +nl diff --git a/po/POTFILES b/po/POTFILES new file mode 100644 index 0000000..ae36bcd --- /dev/null +++ b/po/POTFILES @@ -0,0 +1,7 @@ +data/com.github.theironrobin.siglo.desktop.in +data/com.github.theironrobin.siglo.appdata.xml.in +data/com.github.theironrobin.siglo.gschema.xml +src/window.ui +src/main.py +src/window.py + diff --git a/po/meson.build b/po/meson.build new file mode 100644 index 0000000..c0ade3d --- /dev/null +++ b/po/meson.build @@ -0,0 +1 @@ +i18n.gettext('siglo', preset: 'glib') diff --git a/po/nl.po b/po/nl.po new file mode 100644 index 0000000..0d971ea --- /dev/null +++ b/po/nl.po @@ -0,0 +1,93 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the siglo package. +# FIRST AUTHOR , YEAR. +# +msgid "" +msgstr "" +"Project-Id-Version: siglo\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2021-04-22 18:15+0200\n" +"PO-Revision-Date: 2021-04-22 18:18+0200\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.4.2\n" +"Last-Translator: Heimen Stoffels \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Language: nl\n" + +#: data/com.github.theironrobin.siglo.desktop.in:3 +msgid "Siglo" +msgstr "Siglo" + +#: src/window.ui:12 +msgid "Multi-Device Mode" +msgstr "Meerdere apparaten" + +#: src/window.ui:21 +msgid "Manual OTA File" +msgstr "Eigen ota-bestand" + +#: src/window.ui:42 +msgid "Scanning..." +msgstr "Bezig met zoeken…" + +#: src/window.ui:102 +msgid "0 / 0" +msgstr "0 / 0" + +#: src/window.ui:127 +msgid "default scan pass text" +msgstr "standaard scantekst" + +#: src/window.ui:158 +msgid "OTA Update:" +msgstr "OTA-update:" + +#: src/window.ui:170 +msgid "OTA Update (.zip)" +msgstr "OTA-update (.zip)" + +#: src/window.ui:208 +msgid "Tag: " +msgstr "Label: " + +#: src/window.ui:220 +msgid "Tag" +msgstr "Label" + +#: src/window.ui:245 +msgid "Asset: " +msgstr "Waarde: " + +#: src/window.ui:289 +msgid "Cancel" +msgstr "Annuleren" + +#: src/window.ui:306 +msgid "Flash It!" +msgstr "Flashen!" + +#: src/window.ui:330 +msgid "Time Sync" +msgstr "Tijdsynchronisatie" + +#: src/window.ui:364 +msgid "" +"Make sure InfiniTime is ON but NOT connected\n" +"\n" +"To check, go to Settings->Bluetooth->Devices\n" +"\n" +"Might take a few scans." +msgstr "" +"Zorg dat je smartwatch met InfiniTime is opgestart, en dat het NIET is verbonden met bluetooth\n" +"\n" +"Controleer dit via Settings → Bluetooth → Devices\n" +"\n" +"Wellicht moet je een paar keer opnieuw zoeken." + +#: src/window.ui:386 +msgid "Rescan" +msgstr "Opnieuw zoeken" diff --git a/python3-modules.json b/python3-modules.json new file mode 100644 index 0000000..6552b89 --- /dev/null +++ b/python3-modules.json @@ -0,0 +1,69 @@ +{ + "name": "python3-modules", + "buildsystem": "simple", + "build-commands": [], + "modules": [ + { + "name": "python3-gatt", + "buildsystem": "simple", + "build-commands": [ + "pip3 install --verbose --exists-action=i --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} \"gatt\" --no-build-isolation" + ], + "sources": [ + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/96/d0/d66154053d5b47996731d80ee66f65bdf7b790258addc0b6a5f50bcc3579/gatt-0.2.7.tar.gz", + "sha256": "626d9de24a178b6eaff78c31b0bd29f962681da7caf18eb20363f6288d014e3a" + } + ] + }, + { + "name": "python3-dbus-python", + "buildsystem": "simple", + "build-commands": [ + "pip3 install --verbose --exists-action=i --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} \"dbus-python\" --no-build-isolation" + ], + "sources": [ + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/62/7e/d4fb56a1695fa65da0c8d3071855fa5408447b913c58c01933c2f81a269a/dbus-python-1.2.16.tar.gz", + "sha256": "11238f1d86c995d8aed2e22f04a1e3779f0d70e587caffeab4857f3c662ed5a4" + } + ] + }, + { + "name": "python3-requests", + "buildsystem": "simple", + "build-commands": [ + "pip3 install --verbose --exists-action=i --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} \"requests\" --no-build-isolation" + ], + "sources": [ + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/4f/5a/597ef5911cb8919efe4d86206aa8b2658616d676a7088f0825ca08bd7cb8/urllib3-1.26.6.tar.gz", + "sha256": "f57b4c16c62fa2760b7e3d97c35b255512fb6b59a259730f36ba32ce9f8e342f" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/cb/38/4c4d00ddfa48abe616d7e572e02a04273603db446975ab46bbcd36552005/idna-3.2.tar.gz", + "sha256": "467fbad99067910785144ce333826c71fb0e63a425657295239737f7ecd125f3" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/e7/4e/2af0238001648ded297fb54ceb425ca26faa15b341b4fac5371d3938666e/charset-normalizer-2.0.4.tar.gz", + "sha256": "f23667ebe1084be45f6ae0538e4a5a865206544097e4e8bbcacf42cd02a348f3" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/6d/78/f8db8d57f520a54f0b8a438319c342c61c22759d8f9a1cd2e2180b5e5ea9/certifi-2021.5.30.tar.gz", + "sha256": "2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee" + }, + { + "type": "file", + "url": "https://files.pythonhosted.org/packages/e7/01/3569e0b535fb2e4a6c384bdbed00c55b9d78b5084e0fb7f4d0bf523d7670/requests-2.26.0.tar.gz", + "sha256": "b8aa58f8cf793ffd8782d3d8cb19e66ef36f7aba4353eec859e74678b01b07a7" + } + ] + } + ] +} \ No newline at end of file diff --git a/reinstall.sh b/reinstall.sh new file mode 100755 index 0000000..1638c8e --- /dev/null +++ b/reinstall.sh @@ -0,0 +1,5 @@ +rm -rf build/ +meson build +cd build +sudo ninja install + diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/__init__.py diff --git a/src/ble_dfu.py b/src/ble_dfu.py new file mode 100644 index 0000000..83d20d6 --- /dev/null +++ b/src/ble_dfu.py @@ -0,0 +1,334 @@ +from array import array +import gatt +import os +from .util import * +import math +from struct import unpack + +class InfiniTimeDFU(gatt.Device): + # Class constants + UUID_DFU_SERVICE = "00001530-1212-efde-1523-785feabcd123" + UUID_CTRL_POINT = "00001531-1212-efde-1523-785feabcd123" + UUID_PACKET = "00001532-1212-efde-1523-785feabcd123" + UUID_VERSION = "00001534-1212-efde-1523-785feabcd123" + + def __init__(self, mac_address, manager, window, firmware_path, datfile_path, verbose): + self.firmware_path = firmware_path + self.datfile_path = datfile_path + self.target_mac = mac_address + self.window = window + self.verbose = verbose + self.current_step = 0 + self.pkt_receipt_interval = 10 + self.pkt_payload_size = 20 + self.size_per_receipt = self.pkt_payload_size * self.pkt_receipt_interval + self.done = False + self.packet_recipt_count = 0 + self.total_receipt_size = 0 + self.update_in_progress = False + self.caffeinator = Caffeinator() + self.success = False + + super().__init__(mac_address, manager) + + def connect(self): + self.successful_connection = True + super().connect() + + def input_setup(self): + """Bin: read binfile into bin_array""" + print( + "preparing " + + os.path.split(self.firmware_path)[1] + + " for " + + self.target_mac + ) + + if self.firmware_path == None: + raise Exception("input invalid") + + name, extent = os.path.splitext(self.firmware_path) + + if extent == ".bin": + self.bin_array = array("B", open(self.firmware_path, "rb").read()) + + self.image_size = len(self.bin_array) + print("Binary image size: %d" % self.image_size) + print( + "Binary CRC32: %d" % crc32_unsigned(array_to_hex_string(self.bin_array)) + ) + return + raise Exception("input invalid") + + def connect_succeeded(self): + super().connect_succeeded() + print("[%s] Connected" % (self.mac_address)) + + def connect_failed(self, error): + super().connect_failed(error) + self.successful_connection = False + print("[%s] Connection failed: %s" % (self.mac_address, str(error))) + + def disconnect_succeeded(self): + super().disconnect_succeeded() + if not self.success: + self.on_failure() + print("[%s] Disconnected" % (self.mac_address)) + + def characteristic_enable_notifications_succeeded(self, characteristic): + if self.verbose and characteristic.uuid == self.UUID_CTRL_POINT: + print("Notification Enable succeeded for Control Point Characteristic") + self.step_one() + + def characteristic_write_value_succeeded(self, characteristic): + if self.verbose and characteristic.uuid == self.UUID_CTRL_POINT: + print( + "Characteristic value was written successfully for Control Point Characteristic" + ) + if self.verbose and characteristic.uuid == self.UUID_PACKET: + print( + "Characteristic value was written successfully for Packet Characteristic" + ) + if self.current_step == 1: + self.step_two() + elif self.current_step == 3: + self.step_four() + elif self.current_step == 5: + self.step_six() + elif self.current_step == 6: + print("Begin DFU") + self.caffeinator.caffeinate() + self.step_seven() + + def characteristic_write_value_failed(self, characteristic, error): + print("[WARN ] write value failed", str(error)) + self.update_in_progress = True + self.disconnect() + + def characteristic_value_updated(self, characteristic, value): + if self.verbose: + if characteristic.uuid == self.UUID_CTRL_POINT: + print( + "Characteristic value was updated for Control Point Characteristic" + ) + if characteristic.uuid == self.UUID_PACKET: + print("Characteristic value was updated for Packet Characteristic") + print("New value is:", value) + + hexval = array_to_hex_string(value) + + if hexval[:4] == "1001": + # Response::StartDFU + if hexval[4:] == "01": + self.step_three() + else: + print("[WARN ] StartDFU failed") + self.disconnect() + elif hexval[:4] == "1002": + # Response::InitDFUParameters + if hexval[4:] == "01": + self.step_five() + else: + print("[WARN ] InitDFUParameters failed") + self.disconnect() + elif hexval[:2] == "11": + # PacketReceiptNotification + self.packet_recipt_count += 1 + self.total_receipt_size += self.size_per_receipt + # verify that the returned size correspond to what was sent + ack_size = unpack(' 0: + print(alert_dict) + self.device.send_notification(alert_dict) + diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..a6cdb94 --- /dev/null +++ b/src/main.py @@ -0,0 +1,51 @@ +import sys +import gi + +gi.require_version("Gtk", "3.0") + +from gi.repository import Gtk, Gio, Gdk +from .window import SigloWindow +from .config import config + + +class Application(Gtk.Application): + def __init__(self): + self.manager = None + self.conf = config() + self.conf.load_defaults() + super().__init__( + application_id="com.github.theironrobin.siglo", flags=Gio.ApplicationFlags.FLAGS_NONE + ) + + def do_activate(self): + win = self.props.active_window + if not win: + win = SigloWindow(application=self) + win.present() + win.do_scanning() + + def do_window_removed(self, window): + win = self.props.active_window + if win: + win.destroy_manager() + self.quit() + + +def main(version): + def gtk_style(): + css = b""" +#multi_mac_label { font-size: 33px; } +#bluetooth_button { background-color: blue; + background-image: none; } + """ + style_provider = Gtk.CssProvider() + style_provider.load_from_data(css) + Gtk.StyleContext.add_provider_for_screen( + Gdk.Screen.get_default(), + style_provider, + Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, + ) + + gtk_style() + app = Application() + return app.run(sys.argv) diff --git a/src/meson.build b/src/meson.build new file mode 100644 index 0000000..cf633bd --- /dev/null +++ b/src/meson.build @@ -0,0 +1,41 @@ +pkgdatadir = join_paths(get_option('prefix'), get_option('datadir'), meson.project_name()) +moduledir = join_paths(pkgdatadir, 'siglo') +gnome = import('gnome') + +gnome.compile_resources('siglo', + 'siglo.gresource.xml', + gresource_bundle: true, + install: true, + install_dir: pkgdatadir, +) + +python = import('python') + +conf = configuration_data() +conf.set('PYTHON', python.find_installation('python3', modules: ['gatt']).full_path()) +conf.set('VERSION', meson.project_version()) +conf.set('localedir', join_paths(get_option('prefix'), get_option('localedir'))) +conf.set('pkgdatadir', pkgdatadir) + +configure_file( + input: 'siglo.in', + output: 'siglo', + configuration: conf, + install: true, + install_dir: get_option('bindir') +) + +siglo_sources = [ + '__init__.py', + 'daemon.py', + 'quick_deploy.py', + 'main.py', + 'config.py', + 'window.py', + 'bluetooth.py', + 'ble_dfu.py', + 'ota/util.py', + 'ota/unpacker.py', +] + +install_data(siglo_sources, install_dir: moduledir) diff --git a/src/ota/Fork.txt b/src/ota/Fork.txt new file mode 100644 index 0000000..dbc1056 --- /dev/null +++ b/src/ota/Fork.txt @@ -0,0 +1 @@ +This directory contains source forked from https://github.com/daniel-thompson/ota-dfu-python. diff --git a/src/ota/LICENSE b/src/ota/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/src/ota/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/ota/unpacker.py b/src/ota/unpacker.py new file mode 100644 index 0000000..ab2ecbc --- /dev/null +++ b/src/ota/unpacker.py @@ -0,0 +1,52 @@ +import os.path +import zipfile +import tempfile +import random +import string +import shutil +import re + +from os.path import basename + +class Unpacker(object): + #-------------------------------------------------------------------------- + # + #-------------------------------------------------------------------------- + def entropy(self, length): + return ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in range (length)) + + #-------------------------------------------------------------------------- + # + #-------------------------------------------------------------------------- + def unpack_zipfile(self, file): + + if not os.path.isfile(file): + raise Exception("Error: file, not found!") + + # Create unique working direction into which the zip file is expanded + self.unzip_dir = "{0}/{1}_{2}".format(tempfile.gettempdir(), os.path.splitext(basename(file))[0], self.entropy(6)) + + datfilename = "" + binfilename = "" + + with zipfile.ZipFile(file, 'r') as zip: + files = [item.filename for item in zip.infolist()] + datfilename = [m.group(0) for f in files for m in [re.search('.*\.dat', f)] if m].pop() + binfilename = [m.group(0) for f in files for m in [re.search('.*\.bin', f)] if m].pop() + + zip.extractall(r'{0}'.format(self.unzip_dir)) + + datfile = "{0}/{1}".format(self.unzip_dir, datfilename) + binfile = "{0}/{1}".format(self.unzip_dir, binfilename) + + # print "DAT file: " + datfile + # print "BIN file: " + binfile + + return binfile, datfile + + #-------------------------------------------------------------------------- + # + #-------------------------------------------------------------------------- + def delete(self): + # delete self.unzip_dir and its contents + shutil.rmtree(self.unzip_dir) diff --git a/src/ota/util.py b/src/ota/util.py new file mode 100644 index 0000000..401d494 --- /dev/null +++ b/src/ota/util.py @@ -0,0 +1,70 @@ +import sys +import binascii +import re + +def bytes_to_uint32_le(bytes): + return (int(bytes[3], 16) << 24) | (int(bytes[2], 16) << 16) | (int(bytes[1], 16) << 8) | (int(bytes[0], 16) << 0) + +def uint32_to_bytes_le(uint32): + return [(uint32 >> 0) & 0xff, + (uint32 >> 8) & 0xff, + (uint32 >> 16) & 0xff, + (uint32 >> 24) & 0xff] + +def uint16_to_bytes_le(value): + return [(value >> 0 & 0xFF), + (value >> 8 & 0xFF)] + +def zero_pad_array_le(data, padsize): + for i in range(0, padsize): + data.insert(0, 0) + +def array_to_hex_string(arr): + hex_str = "" + for val in arr: + if val > 255: + raise Exception("Value is greater than it is possible to represent with one byte") + hex_str += "%02x" % val + + return hex_str + +def crc32_unsigned(bytestring): + return binascii.crc32(bytestring.encode('UTF-8')) % (1 << 32) + +def mac_string_to_uint(mac): + parts = list(re.match('(..):(..):(..):(..):(..):(..)', mac).groups()) + ints = [int(x, 16) for x in parts] + + res = 0 + for i in range(0, len(ints)): + res += (ints[len(ints)-1 - i] << 8*i) + + return res + +def uint_to_mac_string(mac): + ints = [0, 0, 0, 0, 0, 0] + for i in range(0, len(ints)): + ints[len(ints)-1 - i] = (mac >> 8*i) & 0xff + + return ':'.join(['{:02x}'.format(x).upper() for x in ints]) + +# Print a nice console progress bar +def print_progress(iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): + """ + Call in a loop to create terminal progress bar + @params: + iteration - Required : current iteration (Int) + total - Required : total iterations (Int) + prefix - Optional : prefix string (Str) + suffix - Optional : suffix string (Str) + decimals - Optional : positive number of decimals in percent complete (Int) + barLength - Optional : character length of bar (Int) + """ + formatStr = "{0:." + str(decimals) + "f}" + percents = formatStr.format(100 * (iteration / float(total))) + filledLength = int(round(barLength * iteration / float(total))) + bar = 'x' * filledLength + '-' * (barLength - filledLength) + sys.stdout.write('\r%s |%s| %s%s %s (%d of %d bytes)' % (prefix, bar, percents, '%', suffix, iteration, total)), + if iteration == total: + sys.stdout.write('\n') + sys.stdout.flush() diff --git a/src/quick_deploy.py b/src/quick_deploy.py new file mode 100644 index 0000000..e55079f --- /dev/null +++ b/src/quick_deploy.py @@ -0,0 +1,65 @@ +import requests +import json + +url = "https://api.github.com/repos/JF002/InfiniTime/releases" +version_blacklist = ( + "0.6.0", + "0.6.1", + "0.6.2", + "0.7.0", + "0.7.1", + "0.8.0-develop", + "0.8.1-develop", + "0.8.2-develop", + "0.9.0-develop", + "0.9.0", + "0.8.3", + "0.8.2", + "0.10.0", + "0.11.0", + "0.12.0", + "0.12.1", +) + + +def get_quick_deploy_list(): + try: + r = requests.get(url) + except requests.exceptions.ConnectionError: + return [] + d = json.loads(r.content) + quick_deploy_list = [] + for item in d: + for asset in item["assets"]: + if ( + asset["content_type"] == "application/zip" + and item["tag_name"] not in version_blacklist + ): + helper_dict = { + "tag_name": item["tag_name"], + "name": asset["name"], + "browser_download_url": asset["browser_download_url"], + } + quick_deploy_list.append(helper_dict) + return quick_deploy_list + + +def get_tags(full_list): + tags = set() + for element in full_list: + tags.add(element["tag_name"]) + return sorted(tags, reverse=True) + + +def get_assets_by_tag(tag, full_list): + asset_list = [] + for element in full_list: + if tag == element["tag_name"]: + asset_list.append(element["name"]) + return asset_list + + +def get_download_url(name, tag, full_list): + for element in full_list: + if tag == element["tag_name"] and name == element["name"]: + return element["browser_download_url"] diff --git a/src/siglo.gresource.xml b/src/siglo.gresource.xml new file mode 100644 index 0000000..2c769e8 --- /dev/null +++ b/src/siglo.gresource.xml @@ -0,0 +1,11 @@ + + + + window.ui + watch.svg + watch-icon.svg + watch-check.svg + watch-progress.svg + watch-error.svg + + diff --git a/src/siglo.in b/src/siglo.in new file mode 100755 index 0000000..3f27cea --- /dev/null +++ b/src/siglo.in @@ -0,0 +1,47 @@ +#!@PYTHON@ + + +import os +import sys +import signal +import gettext +import argparse + +VERSION = '@VERSION@' +pkgdatadir = '@pkgdatadir@' +localedir = '@localedir@' + +sys.path.insert(1, pkgdatadir) +signal.signal(signal.SIGINT, signal.SIG_DFL) +gettext.install('siglo', localedir) + +def main(): + p = argparse.ArgumentParser(description="app to sync InfiniTime watch") + p.add_argument('--start', '-d', required=False, action='store_true', help="start daemon") + p.add_argument('--stop', '-x', required=False, action='store_true', help="stop daemon") + args = p.parse_args() + + from siglo import config + config = config.config() + config.load_defaults() + + from siglo import daemon + d = daemon.daemon() + + if args.start: + d.start() + elif args.stop: + d.stop() + else: + import gi + + from gi.repository import Gio + resource = Gio.Resource.load(os.path.join(pkgdatadir, 'siglo.gresource')) + resource._register() + + from siglo import main + sys.exit(main.main(VERSION)) + +if __name__ == '__main__': + main() + diff --git a/src/watch-check.svg b/src/watch-check.svg new file mode 100644 index 0000000..1b9ea75 --- /dev/null +++ b/src/watch-check.svg @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + diff --git a/src/watch-error.svg b/src/watch-error.svg new file mode 100644 index 0000000..577e401 --- /dev/null +++ b/src/watch-error.svg @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + diff --git a/src/watch-icon.svg b/src/watch-icon.svg new file mode 100644 index 0000000..e155e98 --- /dev/null +++ b/src/watch-icon.svg @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/src/watch-progress.svg b/src/watch-progress.svg new file mode 100644 index 0000000..155c782 --- /dev/null +++ b/src/watch-progress.svg @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + diff --git a/src/watch.svg b/src/watch.svg new file mode 100644 index 0000000..0c79681 --- /dev/null +++ b/src/watch.svg @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/src/window.py b/src/window.py new file mode 100644 index 0000000..939299c --- /dev/null +++ b/src/window.py @@ -0,0 +1,381 @@ +import subprocess +import configparser +import threading +import urllib.request +from pathlib import Path +import gatt +from gi.repository import Gtk, GObject, GLib +from .bluetooth import ( + InfiniTimeDevice, + InfiniTimeManager, + BluetoothDisabled, + NoAdapterFound, +) +from .ble_dfu import InfiniTimeDFU +from .unpacker import Unpacker +from .quick_deploy import * +from .config import config + + +class ConnectionThread(threading.Thread): + def __init__(self, manager, mac, callback): + threading.Thread.__init__(self) + self.mac = mac + self.manager = manager + self.callback = callback + self.device = None + + def run(self): + self.device = InfiniTimeDevice( + manager=self.manager, mac_address=self.mac, thread=True + ) + self.device.services_done = self.data_received + self.device.connect() + + def data_received(self): + firmware = bytes(self.device.firmware).decode() + if self.device.battery == -1: + battery = "n/a" + else: + battery = "{}%".format(self.device.battery) + GLib.idle_add(self.callback, [firmware, battery]) + + +@Gtk.Template(resource_path="/com/github/theironrobin/siglo/window.ui") +class SigloWindow(Gtk.ApplicationWindow): + __gtype_name__ = "SigloWindow" + # Navigation + main_stack = Gtk.Template.Child() + header_stack = Gtk.Template.Child() + + # Watches view + watches_listbox = Gtk.Template.Child() + + # Watch view + watch_name = Gtk.Template.Child() + watch_address = Gtk.Template.Child() + watch_firmware = Gtk.Template.Child() + watch_battery = Gtk.Template.Child() + ota_pick_tag_combobox = Gtk.Template.Child() + ota_pick_asset_combobox = Gtk.Template.Child() + firmware_run = Gtk.Template.Child() + firmware_file = Gtk.Template.Child() + firmware_run_file = Gtk.Template.Child() + keep_paired_switch = Gtk.Template.Child() + + # Flasher + dfu_stack = Gtk.Template.Child() + dfu_progress_bar = Gtk.Template.Child() + dfu_progress_text = Gtk.Template.Child() + + def __init__(self, **kwargs): + self.ble_dfu = None + self.ota_file = None + self.manager = None + self.current_mac = None + self.asset = None + self.asset_download_url = None + self.tag = None + self.conf = config() + super().__init__(**kwargs) + GObject.threads_init() + self.full_list = get_quick_deploy_list() + GObject.signal_new( + "flash-signal", + self, + GObject.SIGNAL_RUN_LAST, + GObject.TYPE_PYOBJECT, + (GObject.TYPE_PYOBJECT,), + ) + + def disconnect_paired_device(self): + try: + devices = self.manager.devices() + for d in devices: + if d.mac_address == self.manager.get_mac_address() and d.is_connected(): + d.disconnect() + finally: + self.conf.set_property("paired", "False") + + def destroy_manager(self): + if self.manager: + self.manager.stop() + self.manager = None + + def make_watch_row(self, name, mac): + row = Gtk.ListBoxRow() + grid = Gtk.Grid() + grid.set_hexpand(True) + grid.set_row_spacing(8) + grid.set_column_spacing(8) + grid.set_margin_top(8) + grid.set_margin_bottom(8) + grid.set_margin_left(8) + grid.set_margin_right(8) + row.add(grid) + + icon = Gtk.Image.new_from_resource("/com/github/theironrobin/siglo/watch-icon.svg") + grid.attach(icon, 0, 0, 1, 2) + + label_alias = Gtk.Label(label="Name", xalign=1.0) + label_alias.get_style_context().add_class("dim-label") + grid.attach(label_alias, 1, 0, 1, 1) + value_alias = Gtk.Label(label=name, xalign=0.0) + value_alias.set_hexpand(True) + grid.attach(value_alias, 2, 0, 1, 1) + + label_mac = Gtk.Label(label="Address", xalign=1.0) + label_mac.get_style_context().add_class("dim-label") + grid.attach(label_mac, 1, 1, 1, 1) + value_mac = Gtk.Label(label=mac, xalign=0.0) + grid.attach(value_mac, 2, 1, 1, 1) + + arrow = Gtk.Image.new_from_icon_name("go-next-symbolic", Gtk.IconSize.BUTTON) + grid.attach(arrow, 4, 0, 1, 2) + + row.show_all() + return row + + def do_scanning(self): + print("Start scanning") + self.main_stack.set_visible_child_name("scan") + self.header_stack.set_visible_child_name("scan") + if not self.manager: + # create manager if not present yet + try: + self.manager = InfiniTimeManager() + except (gatt.errors.NotReady, BluetoothDisabled): + print("Bluetooth is disabled") + self.main_stack.set_visible_child_name("nodevice") + except NoAdapterFound: + print("No bluetooth adapter found") + self.main_stack.set_visible_child_name("nodevice") + if not self.manager: + return + + if self.conf.get_property("paired"): + self.disconnect_paired_device() + + self.depopulate_listbox() + self.manager.scan_result = False + try: + self.manager.scan_for_infinitime() + except (gatt.errors.NotReady, gatt.errors.Failed) as e: + print(e) + self.main_stack.set_visible_child_name("nodevice") + self.destroy_manager() + try: + if len(self.manager.get_device_set()) > 0: + self.main_stack.set_visible_child_name("watches") + self.header_stack.set_visible_child_name("watches") + else: + self.main_stack.set_visible_child_name("nodevice") + for mac in self.manager.get_device_set(): + print("Found {}".format(mac)) + row = self.make_watch_row(self.manager.aliases[mac], mac) + row.mac = mac + row.alias = self.manager.aliases[mac] + self.watches_listbox.add(row) + except AttributeError as e: + print(e) + self.main_stack.set_visible_child_name("nodevice") + self.destroy_manager() + self.populate_tagbox() + + def depopulate_listbox(self): + children = self.watches_listbox.get_children() + for child in children: + self.watches_listbox.remove(child) + + def populate_tagbox(self): + self.ota_pick_tag_combobox.remove_all() + for tag in get_tags(self.full_list): + self.ota_pick_tag_combobox.append_text(tag) + + def populate_assetbox(self): + self.ota_pick_asset_combobox.remove_all() + for asset in get_assets_by_tag(self.tag, self.full_list): + self.ota_pick_asset_combobox.append_text(asset) + + def callback_device_connect(self, data): + firmware, battery = data + + self.watch_firmware.set_text(firmware) + self.watch_battery.set_text(battery) + + @Gtk.Template.Callback() + def on_watches_listbox_row_activated(self, widget, row): + mac = row.mac + self.current_mac = mac + alias = row.alias + + if self.keep_paired_switch.get_active(): + # Start daemon + subprocess.Popen(["systemctl", "--user", "start", "siglo"]) + self.conf.set_property("paired", "True") + + if self.manager is not None: + thread = ConnectionThread(self.manager, mac, self.callback_device_connect) + thread.daemon = True + thread.start() + + self.watch_name.set_text(alias) + self.watch_address.set_text(mac) + self.main_stack.set_visible_child_name("watch") + self.header_stack.set_visible_child_name("watch") + + @Gtk.Template.Callback() + def on_back_to_devices_clicked(self, *args): + self.main_stack.set_visible_child_name("watches") + self.header_stack.set_visible_child_name("watches") + + @Gtk.Template.Callback() + def ota_pick_tag_combobox_changed_cb(self, widget): + self.tag = self.ota_pick_tag_combobox.get_active_text() + self.populate_assetbox() + + @Gtk.Template.Callback() + def ota_pick_asset_combobox_changed_cb(self, widget): + self.asset = self.ota_pick_asset_combobox.get_active_text() + if self.asset is not None: + self.firmware_run.set_sensitive(True) + self.asset_download_url = get_download_url( + self.asset, self.tag, self.full_list + ) + else: + self.firmware_run.set_sensitive(False) + self.asset_download_url = None + + @Gtk.Template.Callback() + def firmware_file_file_set_cb(self, widget): + print("File set!") + filename = widget.get_filename() + self.ota_file = filename + self.firmware_run_file.set_sensitive(True) + + @Gtk.Template.Callback() + def rescan_button_clicked(self, widget): + self.do_scanning() + + @Gtk.Template.Callback() + def on_bluetooth_settings_clicked(self, widget): + subprocess.Popen(["gnome-control-center", "bluetooth"]) + + @Gtk.Template.Callback() + def ota_file_selected(self, widget): + filename = widget.get_filename() + self.ota_file = filename + self.main_info.set_text("File: " + filename.split("/")[-1]) + self.ota_picked_box.set_visible(True) + self.ota_selection_box.set_visible(False) + self.ota_picked_box.set_sensitive(True) + + @Gtk.Template.Callback() + def firmware_run_file_clicked_cb(self, widget): + self.dfu_stack.set_visible_child_name("ok") + self.main_stack.set_visible_child_name("firmware") + + self.firmware_mode = "manual" + + self.start_flash() + + @Gtk.Template.Callback() + def on_firmware_run_clicked(self, widget): + self.dfu_stack.set_visible_child_name("ok") + self.main_stack.set_visible_child_name("firmware") + + self.firmware_mode = "auto" + + file_name = "/tmp/" + self.asset + + print("Downloading {}".format(self.asset_download_url)) + + local_filename, headers = urllib.request.urlretrieve( + self.asset_download_url, file_name + ) + self.ota_file = local_filename + + self.start_flash() + + def start_flash(self): + unpacker = Unpacker() + try: + binfile, datfile = unpacker.unpack_zipfile(self.ota_file) + except Exception as e: + print("ERR") + print(e) + pass + + self.ble_dfu = InfiniTimeDFU( + mac_address=self.current_mac, + manager=self.manager, + window=self, + firmware_path=binfile, + datfile_path=datfile, + verbose=False, + ) + self.ble_dfu.on_failure = self.on_flash_failed + self.ble_dfu.on_success = self.on_flash_done + self.ble_dfu.input_setup() + self.dfu_progress_text.set_text(self.get_prog_text()) + self.ble_dfu.connect() + + def on_flash_failed(self): + self.dfu_stack.set_visible_child_name("fail") + + def on_flash_done(self): + self.dfu_stack.set_visible_child_name("done") + + @Gtk.Template.Callback() + def on_dfu_retry_clicked(self, widget): + if self.firmware_mode == "auto": + self.on_firmware_run_clicked(widget) + + @Gtk.Template.Callback() + def flash_it_button_clicked(self, widget): + if self.deploy_type == "quick": + file_name = "/tmp/" + self.asset + local_filename, headers = urllib.request.urlretrieve( + self.asset_download_url, file_name + ) + self.ota_file = local_filename + + @Gtk.Template.Callback() + def deploy_type_toggled(self, widget): + if ( + self.conf.get_property("deploy_type") == "manual" + and self.auto_switch_deploy_type + ): + self.auto_switch_deploy_type = False + else: + if self.conf.get_property("deploy_type") == "quick": + self.conf.set_property("deploy_type", "manual") + else: + self.conf.set_property("deploy_type", "quick") + self.rescan_button.emit("clicked") + + def update_progress_bar(self): + self.dfu_progress_bar.set_fraction( + self.ble_dfu.total_receipt_size / self.ble_dfu.image_size + ) + self.dfu_progress_text.set_text(self.get_prog_text()) + + def get_prog_text(self): + return ( + str(self.ble_dfu.total_receipt_size) + + " / " + + str(self.ble_dfu.image_size) + + " bytes received" + ) + + def show_complete(self, success): + if success: + self.rescan_button.set_sensitive("True") + self.main_info.set_text("OTA Update Complete") + else: + self.main_info.set_text("OTA Update Failed") + self.bt_spinner.set_visible(False) + self.dfu_progress_box.set_visible(False) + self.ota_picked_box.set_visible(True) + if self.conf.get_property("deploy_type") == "quick": + self.auto_bbox_scan_pass.set_visible(True) diff --git a/src/window.ui b/src/window.ui new file mode 100644 index 0000000..e183823 --- /dev/null +++ b/src/window.ui @@ -0,0 +1,1355 @@ + + + + + + True + False + + + True + False + Manual OTA File + True + + + + + + True + False + + + + + -- cgit v0.9.1